1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective C declarations.
12 //===----------------------------------------------------------------------===//
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"
30 using namespace clang;
32 /// Check whether the given method, which must be in the 'init'
33 /// family, is a valid member of that family.
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
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;
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).
49 // We ignore protocols here. Should we? What about Class?
51 const ObjCObjectType *result = method->getResultType()
52 ->castAs<ObjCObjectPointerType>()->getObjectType();
54 if (result->isObjCId()) {
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
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()))
69 // Otherwise, we try to compare class types.
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())
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
95 SourceLocation loc = method->getLocation();
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"));
105 // Otherwise, it's an error.
106 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
107 method->setInvalidDecl();
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();
125 // Figure out which class this method is part of, if any.
126 ObjCInterfaceDecl *CurrentClass
127 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
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();
140 Diag(NewMethod->getLocation(),
141 diag::warn_related_result_type_compatibility_class)
142 << Context.getObjCInterfaceType(CurrentClass)
146 Diag(NewMethod->getLocation(),
147 diag::warn_related_result_type_compatibility_protocol)
152 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
153 Diag(Overridden->getLocation(),
154 diag::note_related_result_type_family)
155 << /*overridden method*/ 0
158 Diag(Overridden->getLocation(),
159 diag::note_related_result_type_overridden);
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)
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)
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)
194 /// \brief Check a method declaration for compatibility with the Objective-C
196 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
197 ObjCMethodFamily family = method->getMethodFamily();
203 case OMF_autorelease:
204 case OMF_retainCount:
206 case OMF_performSelector:
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)");
220 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
221 << method->getResultType()
222 << FixItHint::CreateReplacement(ResultTypeRange, "void");
228 // If the method doesn't obey the init rules, don't bother annotating it.
229 if (checkInitMethod(method, QualType()))
232 method->addAttr(new (Context) NSConsumesSelfAttr(SourceLocation(),
235 // Don't add a second copy of this attribute, but otherwise don't
236 // let it be suppressed.
237 if (method->hasAttr<NSReturnsRetainedAttr>())
243 case OMF_mutableCopy:
245 if (method->hasAttr<NSReturnsRetainedAttr>() ||
246 method->hasAttr<NSReturnsNotRetainedAttr>() ||
247 method->hasAttr<NSReturnsAutoreleasedAttr>())
252 method->addAttr(new (Context) NSReturnsRetainedAttr(SourceLocation(),
257 static void DiagnoseObjCImplementedDeprecations(Sema &S,
259 SourceLocation ImplLoc,
261 if (ND && ND->isDeprecated()) {
262 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
264 S.Diag(ND->getLocation(), diag::note_method_declared_at)
265 << ND->getDeclName();
267 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
271 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
273 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
274 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
276 // If we don't have a valid method decl, simply return.
279 if (MDecl->isInstanceMethod())
280 AddInstanceMethodToGlobalPool(MDecl, true);
282 AddFactoryMethodToGlobalPool(MDecl, true);
285 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
286 /// has explicit ownership attribute; false otherwise.
288 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
289 QualType T = Param->getType();
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();
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();
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);
310 // If we don't have a valid method decl, simply return.
314 // Allow all of Sema to see that we are entering a method definition.
315 PushDeclContext(FnBodyScope, MDecl);
318 // Create Decl objects for each parameter, entrring them in the scope for
319 // binding to their use.
321 // Insert the invisible arguments, self and _cmd!
322 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
324 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
325 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
327 // Introduce all of the other parameters into this scope.
328 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
329 E = MDecl->param_end(); PI != E; ++PI) {
330 ParmVarDecl *Param = (*PI);
331 if (!Param->isInvalidDecl() &&
332 RequireCompleteType(Param->getLocation(), Param->getType(),
333 diag::err_typecheck_decl_incomplete_type))
334 Param->setInvalidDecl();
335 if (!Param->isInvalidDecl() &&
336 getLangOpts().ObjCAutoRefCount &&
337 !HasExplicitOwnershipAttr(*this, Param))
338 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
341 if ((*PI)->getIdentifier())
342 PushOnScopeChains(*PI, FnBodyScope);
345 // In ARC, disallow definition of retain/release/autorelease/retainCount
346 if (getLangOpts().ObjCAutoRefCount) {
347 switch (MDecl->getMethodFamily()) {
349 case OMF_retainCount:
351 case OMF_autorelease:
352 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
353 << MDecl->getSelector();
361 case OMF_mutableCopy:
365 case OMF_performSelector:
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());
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);
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;
405 } else if (Family == OMF_finalize) {
406 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
407 getCurFunction()->ObjCShouldCallSuper = true;
410 const ObjCMethodDecl *SuperMethod =
411 SuperClass->lookupMethod(MDecl->getSelector(),
412 MDecl->isInstanceMethod());
413 getCurFunction()->ObjCShouldCallSuper =
414 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
422 // Callback to only accept typo corrections that are Objective-C classes.
423 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
424 // function will reject corrections to that class.
425 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
427 ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {}
428 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
429 : CurrentIDecl(IDecl) {}
431 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
432 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
433 return ID && !declaresSameEntity(ID, CurrentIDecl);
437 ObjCInterfaceDecl *CurrentIDecl;
443 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
444 IdentifierInfo *ClassName, SourceLocation ClassLoc,
445 IdentifierInfo *SuperName, SourceLocation SuperLoc,
446 Decl * const *ProtoRefs, unsigned NumProtoRefs,
447 const SourceLocation *ProtoLocs,
448 SourceLocation EndProtoLoc, AttributeList *AttrList) {
449 assert(ClassName && "Missing class identifier");
451 // Check for another declaration kind with the same name.
452 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
453 LookupOrdinaryName, ForRedeclaration);
455 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
456 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
457 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
460 // Create a declaration to describe this @interface.
461 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
462 ObjCInterfaceDecl *IDecl
463 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
464 PrevIDecl, ClassLoc);
467 // Class already seen. Was it a definition?
468 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
469 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
470 << PrevIDecl->getDeclName();
471 Diag(Def->getLocation(), diag::note_previous_definition);
472 IDecl->setInvalidDecl();
477 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
478 PushOnScopeChains(IDecl, TUScope);
480 // Start the definition of this class. If we're in a redefinition case, there
481 // may already be a definition, so we'll end up adding to it.
482 if (!IDecl->hasDefinition())
483 IDecl->startDefinition();
486 // Check if a different kind of symbol declared in this scope.
487 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
491 // Try to correct for a typo in the superclass name without correcting
492 // to the class we're defining.
493 ObjCInterfaceValidatorCCC Validator(IDecl);
494 if (TypoCorrection Corrected = CorrectTypo(
495 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
497 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
498 Diag(SuperLoc, diag::err_undef_superclass_suggest)
499 << SuperName << ClassName << PrevDecl->getDeclName();
500 Diag(PrevDecl->getLocation(), diag::note_previous_decl)
501 << PrevDecl->getDeclName();
505 if (declaresSameEntity(PrevDecl, IDecl)) {
506 Diag(SuperLoc, diag::err_recursive_superclass)
507 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
508 IDecl->setEndOfDefinitionLoc(ClassLoc);
510 ObjCInterfaceDecl *SuperClassDecl =
511 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
513 // Diagnose classes that inherit from deprecated classes.
515 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
517 if (PrevDecl && SuperClassDecl == 0) {
518 // The previous declaration was not a class decl. Check if we have a
519 // typedef. If we do, get the underlying class type.
520 if (const TypedefNameDecl *TDecl =
521 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
522 QualType T = TDecl->getUnderlyingType();
523 if (T->isObjCObjectType()) {
524 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
525 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
526 // This handles the following case:
527 // @interface NewI @end
528 // typedef NewI DeprI __attribute__((deprecated("blah")))
529 // @interface SI : DeprI /* warn here */ @end
530 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
535 // This handles the following case:
537 // typedef int SuperClass;
538 // @interface MyClass : SuperClass {} @end
540 if (!SuperClassDecl) {
541 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
542 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
546 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
548 Diag(SuperLoc, diag::err_undef_superclass)
549 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
550 else if (RequireCompleteType(SuperLoc,
551 Context.getObjCInterfaceType(SuperClassDecl),
552 diag::err_forward_superclass,
553 SuperClassDecl->getDeclName(),
555 SourceRange(AtInterfaceLoc, ClassLoc))) {
559 IDecl->setSuperClass(SuperClassDecl);
560 IDecl->setSuperClassLoc(SuperLoc);
561 IDecl->setEndOfDefinitionLoc(SuperLoc);
563 } else { // we have a root class.
564 IDecl->setEndOfDefinitionLoc(ClassLoc);
567 // Check then save referenced protocols.
569 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
571 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
574 CheckObjCDeclScope(IDecl);
575 return ActOnObjCContainerStartDefinition(IDecl);
578 /// ActOnCompatibilityAlias - this action is called after complete parsing of
579 /// a \@compatibility_alias declaration. It sets up the alias relationships.
580 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
581 IdentifierInfo *AliasName,
582 SourceLocation AliasLocation,
583 IdentifierInfo *ClassName,
584 SourceLocation ClassLocation) {
585 // Look for previous declaration of alias name
586 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
587 LookupOrdinaryName, ForRedeclaration);
589 if (isa<ObjCCompatibleAliasDecl>(ADecl))
590 Diag(AliasLocation, diag::warn_previous_alias_decl);
592 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
593 Diag(ADecl->getLocation(), diag::note_previous_declaration);
596 // Check for class declaration
597 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
598 LookupOrdinaryName, ForRedeclaration);
599 if (const TypedefNameDecl *TDecl =
600 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
601 QualType T = TDecl->getUnderlyingType();
602 if (T->isObjCObjectType()) {
603 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
604 ClassName = IDecl->getIdentifier();
605 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
606 LookupOrdinaryName, ForRedeclaration);
610 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
612 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
614 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
618 // Everything checked out, instantiate a new alias declaration AST.
619 ObjCCompatibleAliasDecl *AliasDecl =
620 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
622 if (!CheckObjCDeclScope(AliasDecl))
623 PushOnScopeChains(AliasDecl, TUScope);
628 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
629 IdentifierInfo *PName,
630 SourceLocation &Ploc, SourceLocation PrevLoc,
631 const ObjCList<ObjCProtocolDecl> &PList) {
634 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
635 E = PList.end(); I != E; ++I) {
636 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
638 if (PDecl->getIdentifier() == PName) {
639 Diag(Ploc, diag::err_protocol_has_circular_dependency);
640 Diag(PrevLoc, diag::note_previous_definition);
644 if (!PDecl->hasDefinition())
647 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
648 PDecl->getLocation(), PDecl->getReferencedProtocols()))
656 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
657 IdentifierInfo *ProtocolName,
658 SourceLocation ProtocolLoc,
659 Decl * const *ProtoRefs,
660 unsigned NumProtoRefs,
661 const SourceLocation *ProtoLocs,
662 SourceLocation EndProtoLoc,
663 AttributeList *AttrList) {
665 // FIXME: Deal with AttrList.
666 assert(ProtocolName && "Missing protocol identifier");
667 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
669 ObjCProtocolDecl *PDecl = 0;
670 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : 0) {
671 // If we already have a definition, complain.
672 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
673 Diag(Def->getLocation(), diag::note_previous_definition);
675 // Create a new protocol that is completely distinct from previous
676 // declarations, and do not make this protocol available for name lookup.
677 // That way, we'll end up completely ignoring the duplicate.
678 // FIXME: Can we turn this into an error?
679 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
680 ProtocolLoc, AtProtoInterfaceLoc,
682 PDecl->startDefinition();
685 // Check for circular dependencies among protocol declarations. This can
686 // only happen if this protocol was forward-declared.
687 ObjCList<ObjCProtocolDecl> PList;
688 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
689 err = CheckForwardProtocolDeclarationForCircularDependency(
690 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
693 // Create the new declaration.
694 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
695 ProtocolLoc, AtProtoInterfaceLoc,
696 /*PrevDecl=*/PrevDecl);
698 PushOnScopeChains(PDecl, TUScope);
699 PDecl->startDefinition();
703 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
705 // Merge attributes from previous declarations.
707 mergeDeclAttributes(PDecl, PrevDecl);
709 if (!err && NumProtoRefs ) {
710 /// Check then save referenced protocols.
711 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
715 CheckObjCDeclScope(PDecl);
716 return ActOnObjCContainerStartDefinition(PDecl);
719 /// FindProtocolDeclaration - This routine looks up protocols and
720 /// issues an error if they are not declared. It returns list of
721 /// protocol declarations in its 'Protocols' argument.
723 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
724 const IdentifierLocPair *ProtocolId,
725 unsigned NumProtocols,
726 SmallVectorImpl<Decl *> &Protocols) {
727 for (unsigned i = 0; i != NumProtocols; ++i) {
728 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
729 ProtocolId[i].second);
731 DeclFilterCCC<ObjCProtocolDecl> Validator;
732 TypoCorrection Corrected = CorrectTypo(
733 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
734 LookupObjCProtocolName, TUScope, NULL, Validator);
735 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
736 Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
737 << ProtocolId[i].first << Corrected.getCorrection();
738 Diag(PDecl->getLocation(), diag::note_previous_decl)
739 << PDecl->getDeclName();
744 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
745 << ProtocolId[i].first;
749 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
751 // If this is a forward declaration and we are supposed to warn in this
753 // FIXME: Recover nicely in the hidden case.
754 if (WarnOnDeclarations &&
755 (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()))
756 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
757 << ProtocolId[i].first;
758 Protocols.push_back(PDecl);
762 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
763 /// a class method in its extension.
765 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
766 ObjCInterfaceDecl *ID) {
768 return; // Possibly due to previous error
770 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
771 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
772 e = ID->meth_end(); i != e; ++i) {
773 ObjCMethodDecl *MD = *i;
774 MethodMap[MD->getSelector()] = MD;
777 if (MethodMap.empty())
779 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
780 e = CAT->meth_end(); i != e; ++i) {
781 ObjCMethodDecl *Method = *i;
782 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
783 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
784 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
785 << Method->getDeclName();
786 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
791 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
793 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
794 const IdentifierLocPair *IdentList,
796 AttributeList *attrList) {
797 SmallVector<Decl *, 8> DeclsInGroup;
798 for (unsigned i = 0; i != NumElts; ++i) {
799 IdentifierInfo *Ident = IdentList[i].first;
800 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
802 ObjCProtocolDecl *PDecl
803 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
804 IdentList[i].second, AtProtocolLoc,
807 PushOnScopeChains(PDecl, TUScope);
808 CheckObjCDeclScope(PDecl);
811 ProcessDeclAttributeList(TUScope, PDecl, attrList);
814 mergeDeclAttributes(PDecl, PrevDecl);
816 DeclsInGroup.push_back(PDecl);
819 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
823 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
824 IdentifierInfo *ClassName, SourceLocation ClassLoc,
825 IdentifierInfo *CategoryName,
826 SourceLocation CategoryLoc,
827 Decl * const *ProtoRefs,
828 unsigned NumProtoRefs,
829 const SourceLocation *ProtoLocs,
830 SourceLocation EndProtoLoc) {
831 ObjCCategoryDecl *CDecl;
832 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
834 /// Check that class of this category is already completely declared.
837 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
838 diag::err_category_forward_interface,
839 CategoryName == 0)) {
840 // Create an invalid ObjCCategoryDecl to serve as context for
841 // the enclosing method declarations. We mark the decl invalid
842 // to make it clear that this isn't a valid AST.
843 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
844 ClassLoc, CategoryLoc, CategoryName,IDecl);
845 CDecl->setInvalidDecl();
846 CurContext->addDecl(CDecl);
849 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
850 return ActOnObjCContainerStartDefinition(CDecl);
853 if (!CategoryName && IDecl->getImplementation()) {
854 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
855 Diag(IDecl->getImplementation()->getLocation(),
856 diag::note_implementation_declared);
860 /// Check for duplicate interface declaration for this category
861 if (ObjCCategoryDecl *Previous
862 = IDecl->FindCategoryDeclaration(CategoryName)) {
863 // Class extensions can be declared multiple times, categories cannot.
864 Diag(CategoryLoc, diag::warn_dup_category_def)
865 << ClassName << CategoryName;
866 Diag(Previous->getLocation(), diag::note_previous_definition);
870 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
871 ClassLoc, CategoryLoc, CategoryName, IDecl);
872 // FIXME: PushOnScopeChains?
873 CurContext->addDecl(CDecl);
876 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
878 // Protocols in the class extension belong to the class.
879 if (CDecl->IsClassExtension())
880 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
881 NumProtoRefs, Context);
884 CheckObjCDeclScope(CDecl);
885 return ActOnObjCContainerStartDefinition(CDecl);
888 /// ActOnStartCategoryImplementation - Perform semantic checks on the
889 /// category implementation declaration and build an ObjCCategoryImplDecl
891 Decl *Sema::ActOnStartCategoryImplementation(
892 SourceLocation AtCatImplLoc,
893 IdentifierInfo *ClassName, SourceLocation ClassLoc,
894 IdentifierInfo *CatName, SourceLocation CatLoc) {
895 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
896 ObjCCategoryDecl *CatIDecl = 0;
897 if (IDecl && IDecl->hasDefinition()) {
898 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
900 // Category @implementation with no corresponding @interface.
901 // Create and install one.
902 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
905 CatIDecl->setImplicit();
909 ObjCCategoryImplDecl *CDecl =
910 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
911 ClassLoc, AtCatImplLoc, CatLoc);
912 /// Check that class of this category is already completely declared.
914 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
915 CDecl->setInvalidDecl();
916 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
917 diag::err_undef_interface)) {
918 CDecl->setInvalidDecl();
921 // FIXME: PushOnScopeChains?
922 CurContext->addDecl(CDecl);
924 // If the interface is deprecated/unavailable, warn/error about it.
926 DiagnoseUseOfDecl(IDecl, ClassLoc);
928 /// Check that CatName, category name, is not used in another implementation.
930 if (CatIDecl->getImplementation()) {
931 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
933 Diag(CatIDecl->getImplementation()->getLocation(),
934 diag::note_previous_definition);
936 CatIDecl->setImplementation(CDecl);
937 // Warn on implementating category of deprecated class under
938 // -Wdeprecated-implementations flag.
939 DiagnoseObjCImplementedDeprecations(*this,
940 dyn_cast<NamedDecl>(IDecl),
941 CDecl->getLocation(), 2);
945 CheckObjCDeclScope(CDecl);
946 return ActOnObjCContainerStartDefinition(CDecl);
949 Decl *Sema::ActOnStartClassImplementation(
950 SourceLocation AtClassImplLoc,
951 IdentifierInfo *ClassName, SourceLocation ClassLoc,
952 IdentifierInfo *SuperClassname,
953 SourceLocation SuperClassLoc) {
954 ObjCInterfaceDecl* IDecl = 0;
955 // Check for another declaration kind with the same name.
957 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
959 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
960 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
961 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
962 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
963 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
964 diag::warn_undef_interface);
966 // We did not find anything with the name ClassName; try to correct for
967 // typos in the class name.
968 ObjCInterfaceValidatorCCC Validator;
969 if (TypoCorrection Corrected = CorrectTypo(
970 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
972 // Suggest the (potentially) correct interface name. However, put the
973 // fix-it hint itself in a separate note, since changing the name in
974 // the warning would make the fix-it change semantics.However, don't
975 // provide a code-modification hint or use the typo name for recovery,
976 // because this is just a warning. The program may actually be correct.
977 IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
978 DeclarationName CorrectedName = Corrected.getCorrection();
979 Diag(ClassLoc, diag::warn_undef_interface_suggest)
980 << ClassName << CorrectedName;
981 Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
982 << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
985 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
989 // Check that super class name is valid class name
990 ObjCInterfaceDecl* SDecl = 0;
991 if (SuperClassname) {
992 // Check if a different kind of symbol declared in this scope.
993 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
995 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
996 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
998 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1000 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1001 if (SDecl && !SDecl->hasDefinition())
1004 Diag(SuperClassLoc, diag::err_undef_superclass)
1005 << SuperClassname << ClassName;
1006 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1007 // This implementation and its interface do not have the same
1009 Diag(SuperClassLoc, diag::err_conflicting_super_class)
1010 << SDecl->getDeclName();
1011 Diag(SDecl->getLocation(), diag::note_previous_definition);
1017 // Legacy case of @implementation with no corresponding @interface.
1018 // Build, chain & install the interface decl into the identifier.
1020 // FIXME: Do we support attributes on the @implementation? If so we should
1022 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1023 ClassName, /*PrevDecl=*/0, ClassLoc,
1025 IDecl->startDefinition();
1027 IDecl->setSuperClass(SDecl);
1028 IDecl->setSuperClassLoc(SuperClassLoc);
1029 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1031 IDecl->setEndOfDefinitionLoc(ClassLoc);
1034 PushOnScopeChains(IDecl, TUScope);
1036 // Mark the interface as being completed, even if it was just as
1038 // declaration; the user cannot reopen it.
1039 if (!IDecl->hasDefinition())
1040 IDecl->startDefinition();
1043 ObjCImplementationDecl* IMPDecl =
1044 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1045 ClassLoc, AtClassImplLoc);
1047 if (CheckObjCDeclScope(IMPDecl))
1048 return ActOnObjCContainerStartDefinition(IMPDecl);
1050 // Check that there is no duplicate implementation of this class.
1051 if (IDecl->getImplementation()) {
1052 // FIXME: Don't leak everything!
1053 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1054 Diag(IDecl->getImplementation()->getLocation(),
1055 diag::note_previous_definition);
1056 } else { // add it to the list.
1057 IDecl->setImplementation(IMPDecl);
1058 PushOnScopeChains(IMPDecl, TUScope);
1059 // Warn on implementating deprecated class under
1060 // -Wdeprecated-implementations flag.
1061 DiagnoseObjCImplementedDeprecations(*this,
1062 dyn_cast<NamedDecl>(IDecl),
1063 IMPDecl->getLocation(), 1);
1065 return ActOnObjCContainerStartDefinition(IMPDecl);
1068 Sema::DeclGroupPtrTy
1069 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1070 SmallVector<Decl *, 64> DeclsInGroup;
1071 DeclsInGroup.reserve(Decls.size() + 1);
1073 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1074 Decl *Dcl = Decls[i];
1077 if (Dcl->getDeclContext()->isFileContext())
1078 Dcl->setTopLevelDeclInObjCContainer();
1079 DeclsInGroup.push_back(Dcl);
1082 DeclsInGroup.push_back(ObjCImpDecl);
1084 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
1087 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1088 ObjCIvarDecl **ivars, unsigned numIvars,
1089 SourceLocation RBrace) {
1090 assert(ImpDecl && "missing implementation decl");
1091 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1094 /// Check case of non-existing \@interface decl.
1095 /// (legacy objective-c \@implementation decl without an \@interface decl).
1096 /// Add implementations's ivar to the synthesize class's ivar list.
1097 if (IDecl->isImplicitInterfaceDecl()) {
1098 IDecl->setEndOfDefinitionLoc(RBrace);
1099 // Add ivar's to class's DeclContext.
1100 for (unsigned i = 0, e = numIvars; i != e; ++i) {
1101 ivars[i]->setLexicalDeclContext(ImpDecl);
1102 IDecl->makeDeclVisibleInContext(ivars[i]);
1103 ImpDecl->addDecl(ivars[i]);
1108 // If implementation has empty ivar list, just return.
1112 assert(ivars && "missing @implementation ivars");
1113 if (LangOpts.ObjCRuntime.isNonFragile()) {
1114 if (ImpDecl->getSuperClass())
1115 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1116 for (unsigned i = 0; i < numIvars; i++) {
1117 ObjCIvarDecl* ImplIvar = ivars[i];
1118 if (const ObjCIvarDecl *ClsIvar =
1119 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1120 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1121 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1124 // Instance ivar to Implementation's DeclContext.
1125 ImplIvar->setLexicalDeclContext(ImpDecl);
1126 IDecl->makeDeclVisibleInContext(ImplIvar);
1127 ImpDecl->addDecl(ImplIvar);
1131 // Check interface's Ivar list against those in the implementation.
1132 // names and types must match.
1135 ObjCInterfaceDecl::ivar_iterator
1136 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1137 for (; numIvars > 0 && IVI != IVE; ++IVI) {
1138 ObjCIvarDecl* ImplIvar = ivars[j++];
1139 ObjCIvarDecl* ClsIvar = *IVI;
1140 assert (ImplIvar && "missing implementation ivar");
1141 assert (ClsIvar && "missing class ivar");
1143 // First, make sure the types match.
1144 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1145 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1146 << ImplIvar->getIdentifier()
1147 << ImplIvar->getType() << ClsIvar->getType();
1148 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1149 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1150 ImplIvar->getBitWidthValue(Context) !=
1151 ClsIvar->getBitWidthValue(Context)) {
1152 Diag(ImplIvar->getBitWidth()->getLocStart(),
1153 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1154 Diag(ClsIvar->getBitWidth()->getLocStart(),
1155 diag::note_previous_definition);
1157 // Make sure the names are identical.
1158 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1159 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1160 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1161 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1167 Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
1168 else if (IVI != IVE)
1169 Diag(IVI->getLocation(), diag::err_inconsistant_ivar_count);
1172 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1173 bool &IncompleteImpl, unsigned DiagID) {
1174 // No point warning no definition of method which is 'unavailable'.
1175 switch (method->getAvailability()) {
1180 // Don't warn about unavailable or not-yet-introduced methods.
1181 case AR_NotYetIntroduced:
1182 case AR_Unavailable:
1186 // FIXME: For now ignore 'IncompleteImpl'.
1187 // Previously we grouped all unimplemented methods under a single
1188 // warning, but some users strongly voiced that they would prefer
1189 // separate warnings. We will give that approach a try, as that
1190 // matches what we do with protocols.
1192 Diag(ImpLoc, DiagID) << method->getDeclName();
1194 // Issue a note to the original declaration.
1195 SourceLocation MethodLoc = method->getLocStart();
1196 if (MethodLoc.isValid())
1197 Diag(MethodLoc, diag::note_method_declared_at) << method;
1200 /// Determines if type B can be substituted for type A. Returns true if we can
1201 /// guarantee that anything that the user will do to an object of type A can
1202 /// also be done to an object of type B. This is trivially true if the two
1203 /// types are the same, or if B is a subclass of A. It becomes more complex
1204 /// in cases where protocols are involved.
1206 /// Object types in Objective-C describe the minimum requirements for an
1207 /// object, rather than providing a complete description of a type. For
1208 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1209 /// The principle of substitutability means that we may use an instance of A
1210 /// anywhere that we may use an instance of B - it will implement all of the
1211 /// ivars of B and all of the methods of B.
1213 /// This substitutability is important when type checking methods, because
1214 /// the implementation may have stricter type definitions than the interface.
1215 /// The interface specifies minimum requirements, but the implementation may
1216 /// have more accurate ones. For example, a method may privately accept
1217 /// instances of B, but only publish that it accepts instances of A. Any
1218 /// object passed to it will be type checked against B, and so will implicitly
1219 /// by a valid A*. Similarly, a method may return a subclass of the class that
1220 /// it is declared as returning.
1222 /// This is most important when considering subclassing. A method in a
1223 /// subclass must accept any object as an argument that its superclass's
1224 /// implementation accepts. It may, however, accept a more general type
1225 /// without breaking substitutability (i.e. you can still use the subclass
1226 /// anywhere that you can use the superclass, but not vice versa). The
1227 /// converse requirement applies to return types: the return type for a
1228 /// subclass method must be a valid object of the kind that the superclass
1229 /// advertises, but it may be specified more accurately. This avoids the need
1230 /// for explicit down-casting by callers.
1232 /// Note: This is a stricter requirement than for assignment.
1233 static bool isObjCTypeSubstitutable(ASTContext &Context,
1234 const ObjCObjectPointerType *A,
1235 const ObjCObjectPointerType *B,
1237 // Reject a protocol-unqualified id.
1238 if (rejectId && B->isObjCIdType()) return false;
1240 // If B is a qualified id, then A must also be a qualified id and it must
1241 // implement all of the protocols in B. It may not be a qualified class.
1242 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1243 // stricter definition so it is not substitutable for id<A>.
1244 if (B->isObjCQualifiedIdType()) {
1245 return A->isObjCQualifiedIdType() &&
1246 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1252 // id is a special type that bypasses type checking completely. We want a
1253 // warning when it is used in one place but not another.
1254 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1257 // If B is a qualified id, then A must also be a qualified id (which it isn't
1258 // if we've got this far)
1259 if (B->isObjCQualifiedIdType()) return false;
1262 // Now we know that A and B are (potentially-qualified) class types. The
1263 // normal rules for assignment apply.
1264 return Context.canAssignObjCInterfaces(A, B);
1267 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1268 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1271 static bool CheckMethodOverrideReturn(Sema &S,
1272 ObjCMethodDecl *MethodImpl,
1273 ObjCMethodDecl *MethodDecl,
1274 bool IsProtocolMethodDecl,
1275 bool IsOverridingMode,
1277 if (IsProtocolMethodDecl &&
1278 (MethodDecl->getObjCDeclQualifier() !=
1279 MethodImpl->getObjCDeclQualifier())) {
1281 S.Diag(MethodImpl->getLocation(),
1283 diag::warn_conflicting_overriding_ret_type_modifiers
1284 : diag::warn_conflicting_ret_type_modifiers))
1285 << MethodImpl->getDeclName()
1286 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1287 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1288 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1294 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
1295 MethodDecl->getResultType()))
1301 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1302 : diag::warn_conflicting_ret_types;
1304 // Mismatches between ObjC pointers go into a different warning
1305 // category, and sometimes they're even completely whitelisted.
1306 if (const ObjCObjectPointerType *ImplPtrTy =
1307 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
1308 if (const ObjCObjectPointerType *IfacePtrTy =
1309 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
1310 // Allow non-matching return types as long as they don't violate
1311 // the principle of substitutability. Specifically, we permit
1312 // return types that are subclasses of the declared return type,
1313 // or that are more-qualified versions of the declared type.
1314 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1318 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1319 : diag::warn_non_covariant_ret_types;
1323 S.Diag(MethodImpl->getLocation(), DiagID)
1324 << MethodImpl->getDeclName()
1325 << MethodDecl->getResultType()
1326 << MethodImpl->getResultType()
1327 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1328 S.Diag(MethodDecl->getLocation(),
1329 IsOverridingMode ? diag::note_previous_declaration
1330 : diag::note_previous_definition)
1331 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1335 static bool CheckMethodOverrideParam(Sema &S,
1336 ObjCMethodDecl *MethodImpl,
1337 ObjCMethodDecl *MethodDecl,
1338 ParmVarDecl *ImplVar,
1339 ParmVarDecl *IfaceVar,
1340 bool IsProtocolMethodDecl,
1341 bool IsOverridingMode,
1343 if (IsProtocolMethodDecl &&
1344 (ImplVar->getObjCDeclQualifier() !=
1345 IfaceVar->getObjCDeclQualifier())) {
1347 if (IsOverridingMode)
1348 S.Diag(ImplVar->getLocation(),
1349 diag::warn_conflicting_overriding_param_modifiers)
1350 << getTypeRange(ImplVar->getTypeSourceInfo())
1351 << MethodImpl->getDeclName();
1352 else S.Diag(ImplVar->getLocation(),
1353 diag::warn_conflicting_param_modifiers)
1354 << getTypeRange(ImplVar->getTypeSourceInfo())
1355 << MethodImpl->getDeclName();
1356 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1357 << getTypeRange(IfaceVar->getTypeSourceInfo());
1363 QualType ImplTy = ImplVar->getType();
1364 QualType IfaceTy = IfaceVar->getType();
1366 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1372 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1373 : diag::warn_conflicting_param_types;
1375 // Mismatches between ObjC pointers go into a different warning
1376 // category, and sometimes they're even completely whitelisted.
1377 if (const ObjCObjectPointerType *ImplPtrTy =
1378 ImplTy->getAs<ObjCObjectPointerType>()) {
1379 if (const ObjCObjectPointerType *IfacePtrTy =
1380 IfaceTy->getAs<ObjCObjectPointerType>()) {
1381 // Allow non-matching argument types as long as they don't
1382 // violate the principle of substitutability. Specifically, the
1383 // implementation must accept any objects that the superclass
1384 // accepts, however it may also accept others.
1385 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1389 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1390 : diag::warn_non_contravariant_param_types;
1394 S.Diag(ImplVar->getLocation(), DiagID)
1395 << getTypeRange(ImplVar->getTypeSourceInfo())
1396 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1397 S.Diag(IfaceVar->getLocation(),
1398 (IsOverridingMode ? diag::note_previous_declaration
1399 : diag::note_previous_definition))
1400 << getTypeRange(IfaceVar->getTypeSourceInfo());
1404 /// In ARC, check whether the conventional meanings of the two methods
1405 /// match. If they don't, it's a hard error.
1406 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1407 ObjCMethodDecl *decl) {
1408 ObjCMethodFamily implFamily = impl->getMethodFamily();
1409 ObjCMethodFamily declFamily = decl->getMethodFamily();
1410 if (implFamily == declFamily) return false;
1412 // Since conventions are sorted by selector, the only possibility is
1413 // that the types differ enough to cause one selector or the other
1414 // to fall out of the family.
1415 assert(implFamily == OMF_None || declFamily == OMF_None);
1417 // No further diagnostics required on invalid declarations.
1418 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1420 const ObjCMethodDecl *unmatched = impl;
1421 ObjCMethodFamily family = declFamily;
1422 unsigned errorID = diag::err_arc_lost_method_convention;
1423 unsigned noteID = diag::note_arc_lost_method_convention;
1424 if (declFamily == OMF_None) {
1426 family = implFamily;
1427 errorID = diag::err_arc_gained_method_convention;
1428 noteID = diag::note_arc_gained_method_convention;
1431 // Indexes into a %select clause in the diagnostic.
1432 enum FamilySelector {
1433 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1435 FamilySelector familySelector = FamilySelector();
1438 case OMF_None: llvm_unreachable("logic error, no method convention");
1441 case OMF_autorelease:
1444 case OMF_retainCount:
1446 case OMF_performSelector:
1447 // Mismatches for these methods don't change ownership
1448 // conventions, so we don't care.
1451 case OMF_init: familySelector = F_init; break;
1452 case OMF_alloc: familySelector = F_alloc; break;
1453 case OMF_copy: familySelector = F_copy; break;
1454 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1455 case OMF_new: familySelector = F_new; break;
1458 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1459 ReasonSelector reasonSelector;
1461 // The only reason these methods don't fall within their families is
1462 // due to unusual result types.
1463 if (unmatched->getResultType()->isObjCObjectPointerType()) {
1464 reasonSelector = R_UnrelatedReturn;
1466 reasonSelector = R_NonObjectReturn;
1469 S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
1470 S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
1475 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1476 ObjCMethodDecl *MethodDecl,
1477 bool IsProtocolMethodDecl) {
1478 if (getLangOpts().ObjCAutoRefCount &&
1479 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1482 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1483 IsProtocolMethodDecl, false,
1486 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1487 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1488 EF = MethodDecl->param_end();
1489 IM != EM && IF != EF; ++IM, ++IF) {
1490 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1491 IsProtocolMethodDecl, false, true);
1494 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1495 Diag(ImpMethodDecl->getLocation(),
1496 diag::warn_conflicting_variadic);
1497 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1501 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1502 ObjCMethodDecl *Overridden,
1503 bool IsProtocolMethodDecl) {
1505 CheckMethodOverrideReturn(*this, Method, Overridden,
1506 IsProtocolMethodDecl, true,
1509 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1510 IF = Overridden->param_begin(), EM = Method->param_end(),
1511 EF = Overridden->param_end();
1512 IM != EM && IF != EF; ++IM, ++IF) {
1513 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1514 IsProtocolMethodDecl, true, true);
1517 if (Method->isVariadic() != Overridden->isVariadic()) {
1518 Diag(Method->getLocation(),
1519 diag::warn_conflicting_overriding_variadic);
1520 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1524 /// WarnExactTypedMethods - This routine issues a warning if method
1525 /// implementation declaration matches exactly that of its declaration.
1526 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1527 ObjCMethodDecl *MethodDecl,
1528 bool IsProtocolMethodDecl) {
1529 // don't issue warning when protocol method is optional because primary
1530 // class is not required to implement it and it is safe for protocol
1532 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1534 // don't issue warning when primary class's method is
1535 // depecated/unavailable.
1536 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1537 MethodDecl->hasAttr<DeprecatedAttr>())
1540 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1541 IsProtocolMethodDecl, false, false);
1543 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1544 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1545 EF = MethodDecl->param_end();
1546 IM != EM && IF != EF; ++IM, ++IF) {
1547 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1549 IsProtocolMethodDecl, false, false);
1554 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1556 match = !(MethodDecl->isClassMethod() &&
1557 MethodDecl->getSelector() == GetNullarySelector("load", Context));
1560 Diag(ImpMethodDecl->getLocation(),
1561 diag::warn_category_method_impl_match);
1562 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1563 << MethodDecl->getDeclName();
1567 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1568 /// improve the efficiency of selector lookups and type checking by associating
1569 /// with each protocol / interface / category the flattened instance tables. If
1570 /// we used an immutable set to keep the table then it wouldn't add significant
1571 /// memory cost and it would be handy for lookups.
1573 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1574 /// Declared in protocol, and those referenced by it.
1575 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
1576 ObjCProtocolDecl *PDecl,
1577 bool& IncompleteImpl,
1578 const SelectorSet &InsMap,
1579 const SelectorSet &ClsMap,
1580 ObjCContainerDecl *CDecl) {
1581 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1582 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1583 : dyn_cast<ObjCInterfaceDecl>(CDecl);
1584 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1586 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1587 ObjCInterfaceDecl *NSIDecl = 0;
1588 if (getLangOpts().ObjCRuntime.isNeXTFamily()) {
1589 // check to see if class implements forwardInvocation method and objects
1590 // of this class are derived from 'NSProxy' so that to forward requests
1591 // from one object to another.
1592 // Under such conditions, which means that every method possible is
1593 // implemented in the class, we should not issue "Method definition not
1595 // FIXME: Use a general GetUnarySelector method for this.
1596 IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1597 Selector fISelector = Context.Selectors.getSelector(1, &II);
1598 if (InsMap.count(fISelector))
1599 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1600 // need be implemented in the implementation.
1601 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1604 // If this is a forward protocol declaration, get its definition.
1605 if (!PDecl->isThisDeclarationADefinition() &&
1606 PDecl->getDefinition())
1607 PDecl = PDecl->getDefinition();
1609 // If a method lookup fails locally we still need to look and see if
1610 // the method was implemented by a base class or an inherited
1611 // protocol. This lookup is slow, but occurs rarely in correct code
1612 // and otherwise would terminate in a warning.
1614 // check unimplemented instance methods.
1616 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1617 E = PDecl->instmeth_end(); I != E; ++I) {
1618 ObjCMethodDecl *method = *I;
1619 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1620 !method->isPropertyAccessor() &&
1621 !InsMap.count(method->getSelector()) &&
1622 (!Super || !Super->lookupInstanceMethod(method->getSelector()))) {
1623 // If a method is not implemented in the category implementation but
1624 // has been declared in its primary class, superclass,
1625 // or in one of their protocols, no need to issue the warning.
1626 // This is because method will be implemented in the primary class
1627 // or one of its super class implementation.
1629 // Ugly, but necessary. Method declared in protcol might have
1630 // have been synthesized due to a property declared in the class which
1631 // uses the protocol.
1632 if (ObjCMethodDecl *MethodInClass =
1633 IDecl->lookupInstanceMethod(method->getSelector(),
1634 true /*shallowCategoryLookup*/))
1635 if (C || MethodInClass->isPropertyAccessor())
1637 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1638 if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1639 != DiagnosticsEngine::Ignored) {
1640 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1641 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1642 << PDecl->getDeclName();
1646 // check unimplemented class methods
1647 for (ObjCProtocolDecl::classmeth_iterator
1648 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1650 ObjCMethodDecl *method = *I;
1651 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1652 !ClsMap.count(method->getSelector()) &&
1653 (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1654 // See above comment for instance method lookups.
1655 if (C && IDecl->lookupClassMethod(method->getSelector(),
1656 true /*shallowCategoryLookup*/))
1658 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1659 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
1660 DiagnosticsEngine::Ignored) {
1661 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1662 Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1663 PDecl->getDeclName();
1667 // Check on this protocols's referenced protocols, recursively.
1668 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1669 E = PDecl->protocol_end(); PI != E; ++PI)
1670 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, CDecl);
1673 /// MatchAllMethodDeclarations - Check methods declared in interface
1674 /// or protocol against those declared in their implementations.
1676 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1677 const SelectorSet &ClsMap,
1678 SelectorSet &InsMapSeen,
1679 SelectorSet &ClsMapSeen,
1680 ObjCImplDecl* IMPDecl,
1681 ObjCContainerDecl* CDecl,
1682 bool &IncompleteImpl,
1683 bool ImmediateClass,
1684 bool WarnCategoryMethodImpl) {
1685 // Check and see if instance methods in class interface have been
1686 // implemented in the implementation class. If so, their types match.
1687 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1688 E = CDecl->instmeth_end(); I != E; ++I) {
1689 if (InsMapSeen.count((*I)->getSelector()))
1691 InsMapSeen.insert((*I)->getSelector());
1692 if (!(*I)->isPropertyAccessor() &&
1693 !InsMap.count((*I)->getSelector())) {
1695 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1696 diag::warn_undef_method_impl);
1699 ObjCMethodDecl *ImpMethodDecl =
1700 IMPDecl->getInstanceMethod((*I)->getSelector());
1701 assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
1702 "Expected to find the method through lookup as well");
1703 ObjCMethodDecl *MethodDecl = *I;
1704 // ImpMethodDecl may be null as in a @dynamic property.
1705 if (ImpMethodDecl) {
1706 if (!WarnCategoryMethodImpl)
1707 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1708 isa<ObjCProtocolDecl>(CDecl));
1709 else if (!MethodDecl->isPropertyAccessor())
1710 WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1711 isa<ObjCProtocolDecl>(CDecl));
1716 // Check and see if class methods in class interface have been
1717 // implemented in the implementation class. If so, their types match.
1718 for (ObjCInterfaceDecl::classmeth_iterator
1719 I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1720 if (ClsMapSeen.count((*I)->getSelector()))
1722 ClsMapSeen.insert((*I)->getSelector());
1723 if (!ClsMap.count((*I)->getSelector())) {
1725 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1726 diag::warn_undef_method_impl);
1728 ObjCMethodDecl *ImpMethodDecl =
1729 IMPDecl->getClassMethod((*I)->getSelector());
1730 assert(CDecl->getClassMethod((*I)->getSelector()) &&
1731 "Expected to find the method through lookup as well");
1732 ObjCMethodDecl *MethodDecl = *I;
1733 if (!WarnCategoryMethodImpl)
1734 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1735 isa<ObjCProtocolDecl>(CDecl));
1737 WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1738 isa<ObjCProtocolDecl>(CDecl));
1742 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1743 // when checking that methods in implementation match their declaration,
1744 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1745 // extension; as well as those in categories.
1746 if (!WarnCategoryMethodImpl) {
1747 for (ObjCInterfaceDecl::visible_categories_iterator
1748 Cat = I->visible_categories_begin(),
1749 CatEnd = I->visible_categories_end();
1750 Cat != CatEnd; ++Cat) {
1751 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1752 IMPDecl, *Cat, IncompleteImpl, false,
1753 WarnCategoryMethodImpl);
1756 // Also methods in class extensions need be looked at next.
1757 for (ObjCInterfaceDecl::visible_extensions_iterator
1758 Ext = I->visible_extensions_begin(),
1759 ExtEnd = I->visible_extensions_end();
1760 Ext != ExtEnd; ++Ext) {
1761 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1762 IMPDecl, *Ext, IncompleteImpl, false,
1763 WarnCategoryMethodImpl);
1767 // Check for any implementation of a methods declared in protocol.
1768 for (ObjCInterfaceDecl::all_protocol_iterator
1769 PI = I->all_referenced_protocol_begin(),
1770 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1771 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1773 (*PI), IncompleteImpl, false,
1774 WarnCategoryMethodImpl);
1776 // FIXME. For now, we are not checking for extact match of methods
1777 // in category implementation and its primary class's super class.
1778 if (!WarnCategoryMethodImpl && I->getSuperClass())
1779 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1781 I->getSuperClass(), IncompleteImpl, false);
1785 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1786 /// category matches with those implemented in its primary class and
1787 /// warns each time an exact match is found.
1788 void Sema::CheckCategoryVsClassMethodMatches(
1789 ObjCCategoryImplDecl *CatIMPDecl) {
1790 SelectorSet InsMap, ClsMap;
1792 for (ObjCImplementationDecl::instmeth_iterator
1793 I = CatIMPDecl->instmeth_begin(),
1794 E = CatIMPDecl->instmeth_end(); I!=E; ++I)
1795 InsMap.insert((*I)->getSelector());
1797 for (ObjCImplementationDecl::classmeth_iterator
1798 I = CatIMPDecl->classmeth_begin(),
1799 E = CatIMPDecl->classmeth_end(); I != E; ++I)
1800 ClsMap.insert((*I)->getSelector());
1801 if (InsMap.empty() && ClsMap.empty())
1804 // Get category's primary class.
1805 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1808 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1811 SelectorSet InsMapSeen, ClsMapSeen;
1812 bool IncompleteImpl = false;
1813 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1815 IncompleteImpl, false,
1816 true /*WarnCategoryMethodImpl*/);
1819 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1820 ObjCContainerDecl* CDecl,
1821 bool IncompleteImpl) {
1823 // Check and see if instance methods in class interface have been
1824 // implemented in the implementation class.
1825 for (ObjCImplementationDecl::instmeth_iterator
1826 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1827 InsMap.insert((*I)->getSelector());
1829 // Check and see if properties declared in the interface have either 1)
1830 // an implementation or 2) there is a @synthesize/@dynamic implementation
1831 // of the property in the @implementation.
1832 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl))
1833 if (!(LangOpts.ObjCDefaultSynthProperties &&
1834 LangOpts.ObjCRuntime.isNonFragile()) ||
1835 IDecl->isObjCRequiresPropertyDefs())
1836 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1839 for (ObjCImplementationDecl::classmeth_iterator
1840 I = IMPDecl->classmeth_begin(),
1841 E = IMPDecl->classmeth_end(); I != E; ++I)
1842 ClsMap.insert((*I)->getSelector());
1844 // Check for type conflict of methods declared in a class/protocol and
1845 // its implementation; if any.
1846 SelectorSet InsMapSeen, ClsMapSeen;
1847 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1849 IncompleteImpl, true);
1851 // check all methods implemented in category against those declared
1852 // in its primary class.
1853 if (ObjCCategoryImplDecl *CatDecl =
1854 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1855 CheckCategoryVsClassMethodMatches(CatDecl);
1857 // Check the protocol list for unimplemented methods in the @implementation
1859 // Check and see if class methods in class interface have been
1860 // implemented in the implementation class.
1862 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1863 for (ObjCInterfaceDecl::all_protocol_iterator
1864 PI = I->all_referenced_protocol_begin(),
1865 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1866 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1868 // Check class extensions (unnamed categories)
1869 for (ObjCInterfaceDecl::visible_extensions_iterator
1870 Ext = I->visible_extensions_begin(),
1871 ExtEnd = I->visible_extensions_end();
1872 Ext != ExtEnd; ++Ext) {
1873 ImplMethodsVsClassMethods(S, IMPDecl, *Ext, IncompleteImpl);
1875 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1876 // For extended class, unimplemented methods in its protocols will
1877 // be reported in the primary class.
1878 if (!C->IsClassExtension()) {
1879 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1880 E = C->protocol_end(); PI != E; ++PI)
1881 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1882 InsMap, ClsMap, CDecl);
1883 // Report unimplemented properties in the category as well.
1884 // When reporting on missing setter/getters, do not report when
1885 // setter/getter is implemented in category's primary class
1887 if (ObjCInterfaceDecl *ID = C->getClassInterface())
1888 if (ObjCImplDecl *IMP = ID->getImplementation()) {
1889 for (ObjCImplementationDecl::instmeth_iterator
1890 I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1891 InsMap.insert((*I)->getSelector());
1893 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1896 llvm_unreachable("invalid ObjCContainerDecl type.");
1899 /// ActOnForwardClassDeclaration -
1900 Sema::DeclGroupPtrTy
1901 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1902 IdentifierInfo **IdentList,
1903 SourceLocation *IdentLocs,
1905 SmallVector<Decl *, 8> DeclsInGroup;
1906 for (unsigned i = 0; i != NumElts; ++i) {
1907 // Check for another declaration kind with the same name.
1909 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1910 LookupOrdinaryName, ForRedeclaration);
1911 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1912 // Maybe we will complain about the shadowed template parameter.
1913 DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1914 // Just pretend that we didn't see the previous declaration.
1918 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1919 // GCC apparently allows the following idiom:
1921 // typedef NSObject < XCElementTogglerP > XCElementToggler;
1922 // @class XCElementToggler;
1924 // Here we have chosen to ignore the forward class declaration
1925 // with a warning. Since this is the implied behavior.
1926 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1927 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1928 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1929 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1931 // a forward class declaration matching a typedef name of a class refers
1932 // to the underlying class. Just ignore the forward class with a warning
1933 // as this will force the intended behavior which is to lookup the typedef
1935 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
1936 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
1937 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1943 // Create a declaration to describe this forward declaration.
1944 ObjCInterfaceDecl *PrevIDecl
1945 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1946 ObjCInterfaceDecl *IDecl
1947 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1948 IdentList[i], PrevIDecl, IdentLocs[i]);
1949 IDecl->setAtEndRange(IdentLocs[i]);
1951 PushOnScopeChains(IDecl, TUScope);
1952 CheckObjCDeclScope(IDecl);
1953 DeclsInGroup.push_back(IDecl);
1956 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
1959 static bool tryMatchRecordTypes(ASTContext &Context,
1960 Sema::MethodMatchStrategy strategy,
1961 const Type *left, const Type *right);
1963 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
1964 QualType leftQT, QualType rightQT) {
1966 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
1968 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
1970 if (left == right) return true;
1972 // If we're doing a strict match, the types have to match exactly.
1973 if (strategy == Sema::MMS_strict) return false;
1975 if (left->isIncompleteType() || right->isIncompleteType()) return false;
1977 // Otherwise, use this absurdly complicated algorithm to try to
1978 // validate the basic, low-level compatibility of the two types.
1980 // As a minimum, require the sizes and alignments to match.
1981 if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
1984 // Consider all the kinds of non-dependent canonical types:
1985 // - functions and arrays aren't possible as return and parameter types
1987 // - vector types of equal size can be arbitrarily mixed
1988 if (isa<VectorType>(left)) return isa<VectorType>(right);
1989 if (isa<VectorType>(right)) return false;
1991 // - references should only match references of identical type
1992 // - structs, unions, and Objective-C objects must match more-or-less
1994 // - everything else should be a scalar
1995 if (!left->isScalarType() || !right->isScalarType())
1996 return tryMatchRecordTypes(Context, strategy, left, right);
1998 // Make scalars agree in kind, except count bools as chars, and group
1999 // all non-member pointers together.
2000 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2001 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2002 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2003 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
2004 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2005 leftSK = Type::STK_ObjCObjectPointer;
2006 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2007 rightSK = Type::STK_ObjCObjectPointer;
2009 // Note that data member pointers and function member pointers don't
2010 // intermix because of the size differences.
2012 return (leftSK == rightSK);
2015 static bool tryMatchRecordTypes(ASTContext &Context,
2016 Sema::MethodMatchStrategy strategy,
2017 const Type *lt, const Type *rt) {
2018 assert(lt && rt && lt != rt);
2020 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2021 RecordDecl *left = cast<RecordType>(lt)->getDecl();
2022 RecordDecl *right = cast<RecordType>(rt)->getDecl();
2024 // Require union-hood to match.
2025 if (left->isUnion() != right->isUnion()) return false;
2027 // Require an exact match if either is non-POD.
2028 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2029 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2032 // Require size and alignment to match.
2033 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
2035 // Require fields to match.
2036 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2037 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2038 for (; li != le && ri != re; ++li, ++ri) {
2039 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2042 return (li == le && ri == re);
2045 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2046 /// returns true, or false, accordingly.
2047 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
2048 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2049 const ObjCMethodDecl *right,
2050 MethodMatchStrategy strategy) {
2051 if (!matchTypes(Context, strategy,
2052 left->getResultType(), right->getResultType()))
2055 // If either is hidden, it is not considered to match.
2056 if (left->isHidden() || right->isHidden())
2059 if (getLangOpts().ObjCAutoRefCount &&
2060 (left->hasAttr<NSReturnsRetainedAttr>()
2061 != right->hasAttr<NSReturnsRetainedAttr>() ||
2062 left->hasAttr<NSConsumesSelfAttr>()
2063 != right->hasAttr<NSConsumesSelfAttr>()))
2066 ObjCMethodDecl::param_const_iterator
2067 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2068 re = right->param_end();
2070 for (; li != le && ri != re; ++li, ++ri) {
2071 assert(ri != right->param_end() && "Param mismatch");
2072 const ParmVarDecl *lparm = *li, *rparm = *ri;
2074 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2077 if (getLangOpts().ObjCAutoRefCount &&
2078 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2084 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
2085 // If the list is empty, make it a singleton list.
2086 if (List->Method == 0) {
2087 List->Method = Method;
2092 // We've seen a method with this name, see if we have already seen this type
2094 ObjCMethodList *Previous = List;
2095 for (; List; Previous = List, List = List->Next) {
2096 if (!MatchTwoMethodDeclarations(Method, List->Method))
2099 ObjCMethodDecl *PrevObjCMethod = List->Method;
2101 // Propagate the 'defined' bit.
2102 if (Method->isDefined())
2103 PrevObjCMethod->setDefined(true);
2105 // If a method is deprecated, push it in the global pool.
2106 // This is used for better diagnostics.
2107 if (Method->isDeprecated()) {
2108 if (!PrevObjCMethod->isDeprecated())
2109 List->Method = Method;
2111 // If new method is unavailable, push it into global pool
2112 // unless previous one is deprecated.
2113 if (Method->isUnavailable()) {
2114 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2115 List->Method = Method;
2121 // We have a new signature for an existing method - add it.
2122 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2123 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2124 Previous->Next = new (Mem) ObjCMethodList(Method, 0);
2127 /// \brief Read the contents of the method pool for a given selector from
2128 /// external storage.
2129 void Sema::ReadMethodPool(Selector Sel) {
2130 assert(ExternalSource && "We need an external AST source");
2131 ExternalSource->ReadMethodPool(Sel);
2134 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2136 // Ignore methods of invalid containers.
2137 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2141 ReadMethodPool(Method->getSelector());
2143 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2144 if (Pos == MethodPool.end())
2145 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2146 GlobalMethods())).first;
2148 Method->setDefined(impl);
2150 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2151 addMethodToGlobalList(&Entry, Method);
2154 /// Determines if this is an "acceptable" loose mismatch in the global
2155 /// method pool. This exists mostly as a hack to get around certain
2156 /// global mismatches which we can't afford to make warnings / errors.
2157 /// Really, what we want is a way to take a method out of the global
2159 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2160 ObjCMethodDecl *other) {
2161 if (!chosen->isInstanceMethod())
2164 Selector sel = chosen->getSelector();
2165 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2168 // Don't complain about mismatches for -length if the method we
2169 // chose has an integral result type.
2170 return (chosen->getResultType()->isIntegerType());
2173 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2174 bool receiverIdOrClass,
2175 bool warn, bool instance) {
2177 ReadMethodPool(Sel);
2179 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2180 if (Pos == MethodPool.end())
2183 // Gather the non-hidden methods.
2184 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2185 llvm::SmallVector<ObjCMethodDecl *, 4> Methods;
2186 for (ObjCMethodList *M = &MethList; M; M = M->Next) {
2187 if (M->Method && !M->Method->isHidden()) {
2188 // If we're not supposed to warn about mismatches, we're done.
2192 Methods.push_back(M->Method);
2196 // If there aren't any visible methods, we're done.
2197 // FIXME: Recover if there are any known-but-hidden methods?
2198 if (Methods.empty())
2201 if (Methods.size() == 1)
2204 // We found multiple methods, so we may have to complain.
2205 bool issueDiagnostic = false, issueError = false;
2207 // We support a warning which complains about *any* difference in
2208 // method signature.
2209 bool strictSelectorMatch =
2210 (receiverIdOrClass && warn &&
2211 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
2213 != DiagnosticsEngine::Ignored));
2214 if (strictSelectorMatch) {
2215 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2216 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2217 issueDiagnostic = true;
2223 // If we didn't see any strict differences, we won't see any loose
2224 // differences. In ARC, however, we also need to check for loose
2225 // mismatches, because most of them are errors.
2226 if (!strictSelectorMatch ||
2227 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2228 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2229 // This checks if the methods differ in type mismatch.
2230 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2231 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2232 issueDiagnostic = true;
2233 if (getLangOpts().ObjCAutoRefCount)
2239 if (issueDiagnostic) {
2241 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2242 else if (strictSelectorMatch)
2243 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2245 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2247 Diag(Methods[0]->getLocStart(),
2248 issueError ? diag::note_possibility : diag::note_using)
2249 << Methods[0]->getSourceRange();
2250 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2251 Diag(Methods[I]->getLocStart(), diag::note_also_found)
2252 << Methods[I]->getSourceRange();
2258 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2259 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2260 if (Pos == MethodPool.end())
2263 GlobalMethods &Methods = Pos->second;
2265 if (Methods.first.Method && Methods.first.Method->isDefined())
2266 return Methods.first.Method;
2267 if (Methods.second.Method && Methods.second.Method->isDefined())
2268 return Methods.second.Method;
2272 /// DiagnoseDuplicateIvars -
2273 /// Check for duplicate ivars in the entire class at the start of
2274 /// \@implementation. This becomes necesssary because class extension can
2275 /// add ivars to a class in random order which will not be known until
2276 /// class's \@implementation is seen.
2277 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2278 ObjCInterfaceDecl *SID) {
2279 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
2280 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
2281 ObjCIvarDecl* Ivar = *IVI;
2282 if (Ivar->isInvalidDecl())
2284 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2285 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2287 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2288 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2289 Ivar->setInvalidDecl();
2295 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2296 switch (CurContext->getDeclKind()) {
2297 case Decl::ObjCInterface:
2298 return Sema::OCK_Interface;
2299 case Decl::ObjCProtocol:
2300 return Sema::OCK_Protocol;
2301 case Decl::ObjCCategory:
2302 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2303 return Sema::OCK_ClassExtension;
2305 return Sema::OCK_Category;
2306 case Decl::ObjCImplementation:
2307 return Sema::OCK_Implementation;
2308 case Decl::ObjCCategoryImpl:
2309 return Sema::OCK_CategoryImplementation;
2312 return Sema::OCK_None;
2316 // Note: For class/category implemenations, allMethods/allProperties is
2318 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
2319 Decl **allMethods, unsigned allNum,
2320 Decl **allProperties, unsigned pNum,
2321 DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
2323 if (getObjCContainerKind() == Sema::OCK_None)
2326 assert(AtEnd.isValid() && "Invalid location for '@end'");
2328 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2329 Decl *ClassDecl = cast<Decl>(OCD);
2331 bool isInterfaceDeclKind =
2332 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2333 || isa<ObjCProtocolDecl>(ClassDecl);
2334 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2336 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2337 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2338 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2340 for (unsigned i = 0; i < allNum; i++ ) {
2341 ObjCMethodDecl *Method =
2342 cast_or_null<ObjCMethodDecl>(allMethods[i]);
2344 if (!Method) continue; // Already issued a diagnostic.
2345 if (Method->isInstanceMethod()) {
2346 /// Check for instance method of the same name with incompatible types
2347 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2348 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2350 if ((isInterfaceDeclKind && PrevMethod && !match)
2351 || (checkIdenticalMethods && match)) {
2352 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2353 << Method->getDeclName();
2354 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2355 Method->setInvalidDecl();
2358 Method->setAsRedeclaration(PrevMethod);
2359 if (!Context.getSourceManager().isInSystemHeader(
2360 Method->getLocation()))
2361 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2362 << Method->getDeclName();
2363 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2365 InsMap[Method->getSelector()] = Method;
2366 /// The following allows us to typecheck messages to "id".
2367 AddInstanceMethodToGlobalPool(Method);
2370 /// Check for class method of the same name with incompatible types
2371 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2372 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2374 if ((isInterfaceDeclKind && PrevMethod && !match)
2375 || (checkIdenticalMethods && match)) {
2376 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2377 << Method->getDeclName();
2378 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2379 Method->setInvalidDecl();
2382 Method->setAsRedeclaration(PrevMethod);
2383 if (!Context.getSourceManager().isInSystemHeader(
2384 Method->getLocation()))
2385 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2386 << Method->getDeclName();
2387 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2389 ClsMap[Method->getSelector()] = Method;
2390 AddFactoryMethodToGlobalPool(Method);
2394 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2395 // Nothing to do here.
2396 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2397 // Categories are used to extend the class by declaring new methods.
2398 // By the same token, they are also used to add new properties. No
2399 // need to compare the added property to those in the class.
2401 if (C->IsClassExtension()) {
2402 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2403 DiagnoseClassExtensionDupMethods(C, CCPrimary);
2406 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2407 if (CDecl->getIdentifier())
2408 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2409 // user-defined setter/getter. It also synthesizes setter/getter methods
2410 // and adds them to the DeclContext and global method pools.
2411 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
2412 E = CDecl->prop_end();
2414 ProcessPropertyDecl(*I, CDecl);
2415 CDecl->setAtEndRange(AtEnd);
2417 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2418 IC->setAtEndRange(AtEnd);
2419 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2420 // Any property declared in a class extension might have user
2421 // declared setter or getter in current class extension or one
2422 // of the other class extensions. Mark them as synthesized as
2423 // property will be synthesized when property with same name is
2424 // seen in the @implementation.
2425 for (ObjCInterfaceDecl::visible_extensions_iterator
2426 Ext = IDecl->visible_extensions_begin(),
2427 ExtEnd = IDecl->visible_extensions_end();
2428 Ext != ExtEnd; ++Ext) {
2429 for (ObjCContainerDecl::prop_iterator I = Ext->prop_begin(),
2430 E = Ext->prop_end(); I != E; ++I) {
2431 ObjCPropertyDecl *Property = *I;
2432 // Skip over properties declared @dynamic
2433 if (const ObjCPropertyImplDecl *PIDecl
2434 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2435 if (PIDecl->getPropertyImplementation()
2436 == ObjCPropertyImplDecl::Dynamic)
2439 for (ObjCInterfaceDecl::visible_extensions_iterator
2440 Ext = IDecl->visible_extensions_begin(),
2441 ExtEnd = IDecl->visible_extensions_end();
2442 Ext != ExtEnd; ++Ext) {
2443 if (ObjCMethodDecl *GetterMethod
2444 = Ext->getInstanceMethod(Property->getGetterName()))
2445 GetterMethod->setPropertyAccessor(true);
2446 if (!Property->isReadOnly())
2447 if (ObjCMethodDecl *SetterMethod
2448 = Ext->getInstanceMethod(Property->getSetterName()))
2449 SetterMethod->setPropertyAccessor(true);
2453 ImplMethodsVsClassMethods(S, IC, IDecl);
2454 AtomicPropertySetterGetterRules(IC, IDecl);
2455 DiagnoseOwningPropertyGetterSynthesis(IC);
2457 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2458 if (IDecl->getSuperClass() == NULL) {
2459 // This class has no superclass, so check that it has been marked with
2460 // __attribute((objc_root_class)).
2461 if (!HasRootClassAttr) {
2462 SourceLocation DeclLoc(IDecl->getLocation());
2463 SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc));
2464 Diag(DeclLoc, diag::warn_objc_root_class_missing)
2465 << IDecl->getIdentifier();
2466 // See if NSObject is in the current scope, and if it is, suggest
2467 // adding " : NSObject " to the class declaration.
2468 NamedDecl *IF = LookupSingleName(TUScope,
2469 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2470 DeclLoc, LookupOrdinaryName);
2471 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2472 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2473 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2474 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2476 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2479 } else if (HasRootClassAttr) {
2480 // Complain that only root classes may have this attribute.
2481 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2484 if (LangOpts.ObjCRuntime.isNonFragile()) {
2485 while (IDecl->getSuperClass()) {
2486 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2487 IDecl = IDecl->getSuperClass();
2491 SetIvarInitializers(IC);
2492 } else if (ObjCCategoryImplDecl* CatImplClass =
2493 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2494 CatImplClass->setAtEndRange(AtEnd);
2496 // Find category interface decl and then check that all methods declared
2497 // in this interface are implemented in the category @implementation.
2498 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2499 if (ObjCCategoryDecl *Cat
2500 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2501 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
2505 if (isInterfaceDeclKind) {
2506 // Reject invalid vardecls.
2507 for (unsigned i = 0; i != tuvNum; i++) {
2508 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2509 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2510 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2511 if (!VDecl->hasExternalStorage())
2512 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2516 ActOnObjCContainerFinishDefinition();
2518 for (unsigned i = 0; i != tuvNum; i++) {
2519 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2520 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2521 (*I)->setTopLevelDeclInObjCContainer();
2522 Consumer.HandleTopLevelDeclInObjCContainer(DG);
2525 ActOnDocumentableDecl(ClassDecl);
2530 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2531 /// objective-c's type qualifier from the parser version of the same info.
2532 static Decl::ObjCDeclQualifier
2533 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2534 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2538 unsigned countAlignAttr(const AttrVec &A) {
2540 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
2541 if ((*i)->getKind() == attr::Aligned)
2547 bool containsInvalidMethodImplAttribute(ObjCMethodDecl *IMD,
2549 // If method is only declared in implementation (private method),
2550 // No need to issue any diagnostics on method definition with attributes.
2554 // method declared in interface has no attribute.
2555 // But implementation has attributes. This is invalid.
2556 // Except when implementation has 'Align' attribute which is
2557 // immaterial to method declared in interface.
2558 if (!IMD->hasAttrs())
2559 return (A.size() > countAlignAttr(A));
2561 const AttrVec &D = IMD->getAttrs();
2563 unsigned countAlignOnImpl = countAlignAttr(A);
2564 if (!countAlignOnImpl && (A.size() != D.size()))
2566 else if (countAlignOnImpl) {
2567 unsigned countAlignOnDecl = countAlignAttr(D);
2568 if (countAlignOnDecl && (A.size() != D.size()))
2570 else if (!countAlignOnDecl &&
2571 ((A.size()-countAlignOnImpl) != D.size()))
2575 // attributes on method declaration and definition must match exactly.
2576 // Note that we have at most a couple of attributes on methods, so this
2577 // n*n search is good enough.
2578 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i) {
2579 if ((*i)->getKind() == attr::Aligned)
2582 for (AttrVec::const_iterator i1 = D.begin(), e1 = D.end(); i1 != e1; ++i1) {
2583 if ((*i)->getKind() == (*i1)->getKind()) {
2595 /// \brief Check whether the declared result type of the given Objective-C
2596 /// method declaration is compatible with the method's class.
2598 static Sema::ResultTypeCompatibilityKind
2599 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2600 ObjCInterfaceDecl *CurrentClass) {
2601 QualType ResultType = Method->getResultType();
2603 // If an Objective-C method inherits its related result type, then its
2604 // declared result type must be compatible with its own class type. The
2605 // declared result type is compatible if:
2606 if (const ObjCObjectPointerType *ResultObjectType
2607 = ResultType->getAs<ObjCObjectPointerType>()) {
2608 // - it is id or qualified id, or
2609 if (ResultObjectType->isObjCIdType() ||
2610 ResultObjectType->isObjCQualifiedIdType())
2611 return Sema::RTC_Compatible;
2614 if (ObjCInterfaceDecl *ResultClass
2615 = ResultObjectType->getInterfaceDecl()) {
2616 // - it is the same as the method's class type, or
2617 if (declaresSameEntity(CurrentClass, ResultClass))
2618 return Sema::RTC_Compatible;
2620 // - it is a superclass of the method's class type
2621 if (ResultClass->isSuperClassOf(CurrentClass))
2622 return Sema::RTC_Compatible;
2625 // Any Objective-C pointer type might be acceptable for a protocol
2626 // method; we just don't know.
2627 return Sema::RTC_Unknown;
2631 return Sema::RTC_Incompatible;
2635 /// A helper class for searching for methods which a particular method
2637 class OverrideSearch {
2640 ObjCMethodDecl *Method;
2641 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2645 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2646 Selector selector = method->getSelector();
2648 // Bypass this search if we've never seen an instance/class method
2649 // with this selector before.
2650 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2651 if (it == S.MethodPool.end()) {
2652 if (!S.getExternalSource()) return;
2653 S.ReadMethodPool(selector);
2655 it = S.MethodPool.find(selector);
2656 if (it == S.MethodPool.end())
2659 ObjCMethodList &list =
2660 method->isInstanceMethod() ? it->second.first : it->second.second;
2661 if (!list.Method) return;
2663 ObjCContainerDecl *container
2664 = cast<ObjCContainerDecl>(method->getDeclContext());
2666 // Prevent the search from reaching this container again. This is
2667 // important with categories, which override methods from the
2668 // interface and each other.
2669 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2670 searchFromContainer(container);
2671 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2672 searchFromContainer(Interface);
2674 searchFromContainer(container);
2678 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
2679 iterator begin() const { return Overridden.begin(); }
2680 iterator end() const { return Overridden.end(); }
2683 void searchFromContainer(ObjCContainerDecl *container) {
2684 if (container->isInvalidDecl()) return;
2686 switch (container->getDeclKind()) {
2687 #define OBJCCONTAINER(type, base) \
2689 searchFrom(cast<type##Decl>(container)); \
2691 #define ABSTRACT_DECL(expansion)
2692 #define DECL(type, base) \
2694 #include "clang/AST/DeclNodes.inc"
2695 llvm_unreachable("not an ObjC container!");
2699 void searchFrom(ObjCProtocolDecl *protocol) {
2700 if (!protocol->hasDefinition())
2703 // A method in a protocol declaration overrides declarations from
2704 // referenced ("parent") protocols.
2705 search(protocol->getReferencedProtocols());
2708 void searchFrom(ObjCCategoryDecl *category) {
2709 // A method in a category declaration overrides declarations from
2710 // the main class and from protocols the category references.
2711 // The main class is handled in the constructor.
2712 search(category->getReferencedProtocols());
2715 void searchFrom(ObjCCategoryImplDecl *impl) {
2716 // A method in a category definition that has a category
2717 // declaration overrides declarations from the category
2719 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2721 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2724 // Otherwise it overrides declarations from the class.
2725 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2730 void searchFrom(ObjCInterfaceDecl *iface) {
2731 // A method in a class declaration overrides declarations from
2732 if (!iface->hasDefinition())
2736 for (ObjCInterfaceDecl::known_categories_iterator
2737 cat = iface->known_categories_begin(),
2738 catEnd = iface->known_categories_end();
2739 cat != catEnd; ++cat) {
2743 // - the super class, and
2744 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2747 // - any referenced protocols.
2748 search(iface->getReferencedProtocols());
2751 void searchFrom(ObjCImplementationDecl *impl) {
2752 // A method in a class implementation overrides declarations from
2753 // the class interface.
2754 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2759 void search(const ObjCProtocolList &protocols) {
2760 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2765 void search(ObjCContainerDecl *container) {
2766 // Check for a method in this container which matches this selector.
2767 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2768 Method->isInstanceMethod(),
2769 /*AllowHidden=*/true);
2771 // If we find one, record it and bail out.
2773 Overridden.insert(meth);
2777 // Otherwise, search for methods that a hypothetical method here
2778 // would have overridden.
2780 // Note that we're now in a recursive case.
2783 searchFromContainer(container);
2788 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
2789 ObjCInterfaceDecl *CurrentClass,
2790 ResultTypeCompatibilityKind RTC) {
2791 // Search for overridden methods and merge information down from them.
2792 OverrideSearch overrides(*this, ObjCMethod);
2793 // Keep track if the method overrides any method in the class's base classes,
2794 // its protocols, or its categories' protocols; we will keep that info
2795 // in the ObjCMethodDecl.
2796 // For this info, a method in an implementation is not considered as
2797 // overriding the same method in the interface or its categories.
2798 bool hasOverriddenMethodsInBaseOrProtocol = false;
2799 for (OverrideSearch::iterator
2800 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2801 ObjCMethodDecl *overridden = *i;
2803 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
2804 CurrentClass != overridden->getClassInterface() ||
2805 overridden->isOverriding())
2806 hasOverriddenMethodsInBaseOrProtocol = true;
2808 // Propagate down the 'related result type' bit from overridden methods.
2809 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
2810 ObjCMethod->SetRelatedResultType();
2812 // Then merge the declarations.
2813 mergeObjCMethodDecls(ObjCMethod, overridden);
2815 if (ObjCMethod->isImplicit() && overridden->isImplicit())
2816 continue; // Conflicting properties are detected elsewhere.
2818 // Check for overriding methods
2819 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
2820 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
2821 CheckConflictingOverridingMethod(ObjCMethod, overridden,
2822 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
2824 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
2825 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
2826 !overridden->isImplicit() /* not meant for properties */) {
2827 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
2828 E = ObjCMethod->param_end();
2829 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
2830 PrevE = overridden->param_end();
2831 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
2832 assert(PrevI != overridden->param_end() && "Param mismatch");
2833 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
2834 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
2835 // If type of argument of method in this class does not match its
2836 // respective argument type in the super class method, issue warning;
2837 if (!Context.typesAreCompatible(T1, T2)) {
2838 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
2840 Diag(overridden->getLocation(), diag::note_previous_declaration);
2847 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
2850 Decl *Sema::ActOnMethodDeclaration(
2852 SourceLocation MethodLoc, SourceLocation EndLoc,
2853 tok::TokenKind MethodType,
2854 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
2855 ArrayRef<SourceLocation> SelectorLocs,
2857 // optional arguments. The number of types/arguments is obtained
2858 // from the Sel.getNumArgs().
2859 ObjCArgInfo *ArgInfo,
2860 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
2861 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
2862 bool isVariadic, bool MethodDefinition) {
2863 // Make sure we can establish a context for the method.
2864 if (!CurContext->isObjCContainer()) {
2865 Diag(MethodLoc, diag::error_missing_method_context);
2868 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2869 Decl *ClassDecl = cast<Decl>(OCD);
2870 QualType resultDeclType;
2872 bool HasRelatedResultType = false;
2873 TypeSourceInfo *ResultTInfo = 0;
2875 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
2877 // Methods cannot return interface types. All ObjC objects are
2878 // passed by reference.
2879 if (resultDeclType->isObjCObjectType()) {
2880 Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
2881 << 0 << resultDeclType;
2885 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
2886 } else { // get the type for "id".
2887 resultDeclType = Context.getObjCIdType();
2888 Diag(MethodLoc, diag::warn_missing_method_return_type)
2889 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
2892 ObjCMethodDecl* ObjCMethod =
2893 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel,
2897 MethodType == tok::minus, isVariadic,
2898 /*isPropertyAccessor=*/false,
2899 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
2900 MethodDeclKind == tok::objc_optional
2901 ? ObjCMethodDecl::Optional
2902 : ObjCMethodDecl::Required,
2903 HasRelatedResultType);
2905 SmallVector<ParmVarDecl*, 16> Params;
2907 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
2911 if (ArgInfo[i].Type == 0) {
2912 ArgType = Context.getObjCIdType();
2915 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
2918 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
2919 LookupOrdinaryName, ForRedeclaration);
2921 if (R.isSingleResult()) {
2922 NamedDecl *PrevDecl = R.getFoundDecl();
2923 if (S->isDeclScope(PrevDecl)) {
2924 Diag(ArgInfo[i].NameLoc,
2925 (MethodDefinition ? diag::warn_method_param_redefinition
2926 : diag::warn_method_param_declaration))
2928 Diag(PrevDecl->getLocation(),
2929 diag::note_previous_declaration);
2933 SourceLocation StartLoc = DI
2934 ? DI->getTypeLoc().getBeginLoc()
2935 : ArgInfo[i].NameLoc;
2937 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
2938 ArgInfo[i].NameLoc, ArgInfo[i].Name,
2939 ArgType, DI, SC_None);
2941 Param->setObjCMethodScopeInfo(i);
2943 Param->setObjCDeclQualifier(
2944 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
2946 // Apply the attributes to the parameter.
2947 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
2949 if (Param->hasAttr<BlocksAttr>()) {
2950 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
2951 Param->setInvalidDecl();
2954 IdResolver.AddDecl(Param);
2956 Params.push_back(Param);
2959 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
2960 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
2961 QualType ArgType = Param->getType();
2962 if (ArgType.isNull())
2963 ArgType = Context.getObjCIdType();
2965 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2966 ArgType = Context.getAdjustedParameterType(ArgType);
2967 if (ArgType->isObjCObjectType()) {
2968 Diag(Param->getLocation(),
2969 diag::err_object_cannot_be_passed_returned_by_value)
2971 Param->setInvalidDecl();
2973 Param->setDeclContext(ObjCMethod);
2975 Params.push_back(Param);
2978 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
2979 ObjCMethod->setObjCDeclQualifier(
2980 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
2983 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
2985 // Add the method now.
2986 const ObjCMethodDecl *PrevMethod = 0;
2987 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
2988 if (MethodType == tok::minus) {
2989 PrevMethod = ImpDecl->getInstanceMethod(Sel);
2990 ImpDecl->addInstanceMethod(ObjCMethod);
2992 PrevMethod = ImpDecl->getClassMethod(Sel);
2993 ImpDecl->addClassMethod(ObjCMethod);
2996 ObjCMethodDecl *IMD = 0;
2997 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
2998 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
2999 ObjCMethod->isInstanceMethod());
3000 if (ObjCMethod->hasAttrs() &&
3001 containsInvalidMethodImplAttribute(IMD, ObjCMethod->getAttrs())) {
3002 SourceLocation MethodLoc = IMD->getLocation();
3003 if (!getSourceManager().isInSystemHeader(MethodLoc)) {
3004 Diag(EndLoc, diag::warn_attribute_method_def);
3005 Diag(MethodLoc, diag::note_method_declared_at)
3006 << ObjCMethod->getDeclName();
3010 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
3014 // You can never have two method definitions with the same name.
3015 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
3016 << ObjCMethod->getDeclName();
3017 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3020 // If this Objective-C method does not have a related result type, but we
3021 // are allowed to infer related result types, try to do so based on the
3023 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3024 if (!CurrentClass) {
3025 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3026 CurrentClass = Cat->getClassInterface();
3027 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3028 CurrentClass = Impl->getClassInterface();
3029 else if (ObjCCategoryImplDecl *CatImpl
3030 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3031 CurrentClass = CatImpl->getClassInterface();
3034 ResultTypeCompatibilityKind RTC
3035 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
3037 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
3039 bool ARCError = false;
3040 if (getLangOpts().ObjCAutoRefCount)
3041 ARCError = CheckARCMethodDecl(ObjCMethod);
3043 // Infer the related result type when possible.
3044 if (!ARCError && RTC == Sema::RTC_Compatible &&
3045 !ObjCMethod->hasRelatedResultType() &&
3046 LangOpts.ObjCInferRelatedResultType) {
3047 bool InferRelatedResultType = false;
3048 switch (ObjCMethod->getMethodFamily()) {
3053 case OMF_mutableCopy:
3055 case OMF_retainCount:
3056 case OMF_performSelector:
3061 InferRelatedResultType = ObjCMethod->isClassMethod();
3065 case OMF_autorelease:
3068 InferRelatedResultType = ObjCMethod->isInstanceMethod();
3072 if (InferRelatedResultType)
3073 ObjCMethod->SetRelatedResultType();
3076 ActOnDocumentableDecl(ObjCMethod);
3081 bool Sema::CheckObjCDeclScope(Decl *D) {
3082 // Following is also an error. But it is caused by a missing @end
3083 // and diagnostic is issued elsewhere.
3084 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
3087 // If we switched context to translation unit while we are still lexically in
3088 // an objc container, it means the parser missed emitting an error.
3089 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3092 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3093 D->setInvalidDecl();
3098 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
3099 /// instance variables of ClassName into Decls.
3100 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3101 IdentifierInfo *ClassName,
3102 SmallVectorImpl<Decl*> &Decls) {
3103 // Check that ClassName is a valid class
3104 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
3106 Diag(DeclStart, diag::err_undef_interface) << ClassName;
3109 if (LangOpts.ObjCRuntime.isNonFragile()) {
3110 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3114 // Collect the instance variables
3115 SmallVector<const ObjCIvarDecl*, 32> Ivars;
3116 Context.DeepCollectObjCIvars(Class, true, Ivars);
3117 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
3118 for (unsigned i = 0; i < Ivars.size(); i++) {
3119 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
3120 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
3121 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3122 /*FIXME: StartL=*/ID->getLocation(),
3124 ID->getIdentifier(), ID->getType(),
3126 Decls.push_back(FD);
3129 // Introduce all of these fields into the appropriate scope.
3130 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
3131 D != Decls.end(); ++D) {
3132 FieldDecl *FD = cast<FieldDecl>(*D);
3133 if (getLangOpts().CPlusPlus)
3134 PushOnScopeChains(cast<FieldDecl>(FD), S);
3135 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
3136 Record->addDecl(FD);
3140 /// \brief Build a type-check a new Objective-C exception variable declaration.
3141 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3142 SourceLocation StartLoc,
3143 SourceLocation IdLoc,
3146 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3147 // duration shall not be qualified by an address-space qualifier."
3148 // Since all parameters have automatic store duration, they can not have
3149 // an address space.
3150 if (T.getAddressSpace() != 0) {
3151 Diag(IdLoc, diag::err_arg_with_address_space);
3155 // An @catch parameter must be an unqualified object pointer type;
3156 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3158 // Don't do any further checking.
3159 } else if (T->isDependentType()) {
3160 // Okay: we don't know what this type will instantiate to.
3161 } else if (!T->isObjCObjectPointerType()) {
3163 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3164 } else if (T->isObjCQualifiedIdType()) {
3166 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3169 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3171 New->setExceptionVariable(true);
3173 // In ARC, infer 'retaining' for variables of retainable type.
3174 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3178 New->setInvalidDecl();
3182 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3183 const DeclSpec &DS = D.getDeclSpec();
3185 // We allow the "register" storage class on exception variables because
3186 // GCC did, but we drop it completely. Any other storage class is an error.
3187 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3188 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3189 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3190 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
3191 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3192 << DS.getStorageClassSpec();
3194 if (D.getDeclSpec().isThreadSpecified())
3195 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
3196 D.getMutableDeclSpec().ClearStorageClassSpecs();
3198 DiagnoseFunctionSpecifiers(D.getDeclSpec());
3200 // Check that there are no default arguments inside the type of this
3201 // exception object (C++ only).
3202 if (getLangOpts().CPlusPlus)
3203 CheckExtraCXXDefaultArguments(D);
3205 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3206 QualType ExceptionType = TInfo->getType();
3208 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3209 D.getSourceRange().getBegin(),
3210 D.getIdentifierLoc(),
3214 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3215 if (D.getCXXScopeSpec().isSet()) {
3216 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3217 << D.getCXXScopeSpec().getRange();
3218 New->setInvalidDecl();
3221 // Add the parameter declaration into this scope.
3223 if (D.getIdentifier())
3224 IdResolver.AddDecl(New);
3226 ProcessDeclAttributes(S, New, D);
3228 if (New->hasAttr<BlocksAttr>())
3229 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3233 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3235 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3236 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3237 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3238 Iv= Iv->getNextIvar()) {
3239 QualType QT = Context.getBaseElementType(Iv->getType());
3240 if (QT->isRecordType())
3241 Ivars.push_back(Iv);
3245 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3246 // Load referenced selectors from the external source.
3247 if (ExternalSource) {
3248 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3249 ExternalSource->ReadReferencedSelectors(Sels);
3250 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3251 ReferencedSelectors[Sels[I].first] = Sels[I].second;
3254 // Warning will be issued only when selector table is
3255 // generated (which means there is at lease one implementation
3256 // in the TU). This is to match gcc's behavior.
3257 if (ReferencedSelectors.empty() ||
3258 !Context.AnyObjCImplementation())
3260 for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3261 ReferencedSelectors.begin(),
3262 E = ReferencedSelectors.end(); S != E; ++S) {
3263 Selector Sel = (*S).first;
3264 if (!LookupImplementedMethodInGlobalPool(Sel))
3265 Diag((*S).second, diag::warn_unimplemented_selector) << Sel;