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/Sema/Lookup.h"
16 #include "clang/Sema/ExternalSemaSource.h"
17 #include "clang/Sema/Scope.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/AST/ASTConsumer.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/AST/ASTContext.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Sema/DeclSpec.h"
26 #include "llvm/ADT/DenseSet.h"
28 using namespace clang;
30 /// Check whether the given method, which must be in the 'init'
31 /// family, is a valid member of that family.
33 /// \param receiverTypeIfCall - if null, check this as if declaring it;
34 /// if non-null, check this as if making a call to it with the given
37 /// \return true to indicate that there was an error and appropriate
38 /// actions were taken
39 bool Sema::checkInitMethod(ObjCMethodDecl *method,
40 QualType receiverTypeIfCall) {
41 if (method->isInvalidDecl()) return true;
43 // This castAs is safe: methods that don't return an object
44 // pointer won't be inferred as inits and will reject an explicit
45 // objc_method_family(init).
47 // We ignore protocols here. Should we? What about Class?
49 const ObjCObjectType *result = method->getResultType()
50 ->castAs<ObjCObjectPointerType>()->getObjectType();
52 if (result->isObjCId()) {
54 } else if (result->isObjCClass()) {
55 // fall through: always an error
57 ObjCInterfaceDecl *resultClass = result->getInterface();
58 assert(resultClass && "unexpected object type!");
60 // It's okay for the result type to still be a forward declaration
61 // if we're checking an interface declaration.
62 if (resultClass->isForwardDecl()) {
63 if (receiverTypeIfCall.isNull() &&
64 !isa<ObjCImplementationDecl>(method->getDeclContext()))
67 // Otherwise, we try to compare class types.
69 // If this method was declared in a protocol, we can't check
70 // anything unless we have a receiver type that's an interface.
71 const ObjCInterfaceDecl *receiverClass = 0;
72 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
73 if (receiverTypeIfCall.isNull())
76 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79 // This can be null for calls to e.g. id<Foo>.
80 if (!receiverClass) return false;
82 receiverClass = method->getClassInterface();
83 assert(receiverClass && "method not associated with a class!");
86 // If either class is a subclass of the other, it's fine.
87 if (receiverClass->isSuperClassOf(resultClass) ||
88 resultClass->isSuperClassOf(receiverClass))
93 SourceLocation loc = method->getLocation();
95 // If we're in a system header, and this is not a call, just make
96 // the method unusable.
97 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
98 method->addAttr(new (Context) UnavailableAttr(loc, Context,
99 "init method returns a type unrelated to its receiver type"));
103 // Otherwise, it's an error.
104 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
105 method->setInvalidDecl();
109 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
110 const ObjCMethodDecl *Overridden,
111 bool IsImplementation) {
112 if (Overridden->hasRelatedResultType() &&
113 !NewMethod->hasRelatedResultType()) {
114 // This can only happen when the method follows a naming convention that
115 // implies a related result type, and the original (overridden) method has
116 // a suitable return type, but the new (overriding) method does not have
117 // a suitable return type.
118 QualType ResultType = NewMethod->getResultType();
119 SourceRange ResultTypeRange;
120 if (const TypeSourceInfo *ResultTypeInfo
121 = NewMethod->getResultTypeSourceInfo())
122 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
124 // Figure out which class this method is part of, if any.
125 ObjCInterfaceDecl *CurrentClass
126 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
128 DeclContext *DC = NewMethod->getDeclContext();
129 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
130 CurrentClass = Cat->getClassInterface();
131 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
132 CurrentClass = Impl->getClassInterface();
133 else if (ObjCCategoryImplDecl *CatImpl
134 = dyn_cast<ObjCCategoryImplDecl>(DC))
135 CurrentClass = CatImpl->getClassInterface();
139 Diag(NewMethod->getLocation(),
140 diag::warn_related_result_type_compatibility_class)
141 << Context.getObjCInterfaceType(CurrentClass)
145 Diag(NewMethod->getLocation(),
146 diag::warn_related_result_type_compatibility_protocol)
151 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
152 Diag(Overridden->getLocation(),
153 diag::note_related_result_type_overridden_family)
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
159 if (getLangOptions().ObjCAutoRefCount) {
160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
163 diag::err_nsreturns_retained_attribute_mismatch) << 1;
164 Diag(Overridden->getLocation(), diag::note_previous_decl)
167 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
168 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
169 Diag(NewMethod->getLocation(),
170 diag::err_nsreturns_retained_attribute_mismatch) << 0;
171 Diag(Overridden->getLocation(), diag::note_previous_decl)
174 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin();
175 for (ObjCMethodDecl::param_iterator
176 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
177 ni != ne; ++ni, ++oi) {
178 const ParmVarDecl *oldDecl = (*oi);
179 ParmVarDecl *newDecl = (*ni);
180 if (newDecl->hasAttr<NSConsumedAttr>() !=
181 oldDecl->hasAttr<NSConsumedAttr>()) {
182 Diag(newDecl->getLocation(),
183 diag::err_nsconsumed_attribute_mismatch);
184 Diag(oldDecl->getLocation(), diag::note_previous_decl)
191 /// \brief Check a method declaration for compatibility with the Objective-C
193 static bool CheckARCMethodDecl(Sema &S, ObjCMethodDecl *method) {
194 ObjCMethodFamily family = method->getMethodFamily();
201 case OMF_autorelease:
202 case OMF_retainCount:
204 case OMF_performSelector:
208 // If the method doesn't obey the init rules, don't bother annotating it.
209 if (S.checkInitMethod(method, QualType()))
212 method->addAttr(new (S.Context) NSConsumesSelfAttr(SourceLocation(),
215 // Don't add a second copy of this attribute, but otherwise don't
216 // let it be suppressed.
217 if (method->hasAttr<NSReturnsRetainedAttr>())
223 case OMF_mutableCopy:
225 if (method->hasAttr<NSReturnsRetainedAttr>() ||
226 method->hasAttr<NSReturnsNotRetainedAttr>() ||
227 method->hasAttr<NSReturnsAutoreleasedAttr>())
232 method->addAttr(new (S.Context) NSReturnsRetainedAttr(SourceLocation(),
237 static void DiagnoseObjCImplementedDeprecations(Sema &S,
239 SourceLocation ImplLoc,
241 if (ND && ND->isDeprecated()) {
242 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
244 S.Diag(ND->getLocation(), diag::note_method_declared_at);
246 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
250 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
252 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
253 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
255 // If we don't have a valid method decl, simply return.
258 if (MDecl->isInstanceMethod())
259 AddInstanceMethodToGlobalPool(MDecl, true);
261 AddFactoryMethodToGlobalPool(MDecl, true);
264 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
265 /// and user declared, in the method definition's AST.
266 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
267 assert(getCurMethodDecl() == 0 && "Method parsing confused");
268 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
270 // If we don't have a valid method decl, simply return.
274 // Allow all of Sema to see that we are entering a method definition.
275 PushDeclContext(FnBodyScope, MDecl);
278 // Create Decl objects for each parameter, entrring them in the scope for
279 // binding to their use.
281 // Insert the invisible arguments, self and _cmd!
282 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
284 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
285 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
287 // Introduce all of the other parameters into this scope.
288 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
289 E = MDecl->param_end(); PI != E; ++PI) {
290 ParmVarDecl *Param = (*PI);
291 if (!Param->isInvalidDecl() &&
292 RequireCompleteType(Param->getLocation(), Param->getType(),
293 diag::err_typecheck_decl_incomplete_type))
294 Param->setInvalidDecl();
295 if ((*PI)->getIdentifier())
296 PushOnScopeChains(*PI, FnBodyScope);
299 // In ARC, disallow definition of retain/release/autorelease/retainCount
300 if (getLangOptions().ObjCAutoRefCount) {
301 switch (MDecl->getMethodFamily()) {
303 case OMF_retainCount:
305 case OMF_autorelease:
306 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
307 << MDecl->getSelector();
315 case OMF_mutableCopy:
319 case OMF_performSelector:
324 // Warn on deprecated methods under -Wdeprecated-implementations,
325 // and prepare for warning on missing super calls.
326 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
327 if (ObjCMethodDecl *IMD =
328 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
329 DiagnoseObjCImplementedDeprecations(*this,
330 dyn_cast<NamedDecl>(IMD),
331 MDecl->getLocation(), 0);
333 // If this is "dealloc" or "finalize", set some bit here.
334 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
335 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
336 // Only do this if the current class actually has a superclass.
337 if (IC->getSuperClass()) {
338 ObjCShouldCallSuperDealloc =
339 !(Context.getLangOptions().ObjCAutoRefCount ||
340 Context.getLangOptions().getGC() == LangOptions::GCOnly) &&
341 MDecl->getMethodFamily() == OMF_dealloc;
342 ObjCShouldCallSuperFinalize =
343 Context.getLangOptions().getGC() != LangOptions::NonGC &&
344 MDecl->getMethodFamily() == OMF_finalize;
350 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
351 IdentifierInfo *ClassName, SourceLocation ClassLoc,
352 IdentifierInfo *SuperName, SourceLocation SuperLoc,
353 Decl * const *ProtoRefs, unsigned NumProtoRefs,
354 const SourceLocation *ProtoLocs,
355 SourceLocation EndProtoLoc, AttributeList *AttrList) {
356 assert(ClassName && "Missing class identifier");
358 // Check for another declaration kind with the same name.
359 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
360 LookupOrdinaryName, ForRedeclaration);
362 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
363 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
364 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
367 ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
369 // Class already seen. Is it a forward declaration?
370 if (!IDecl->isForwardDecl()) {
371 IDecl->setInvalidDecl();
372 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
373 Diag(IDecl->getLocation(), diag::note_previous_definition);
375 // Return the previous class interface.
376 // FIXME: don't leak the objects passed in!
377 return ActOnObjCContainerStartDefinition(IDecl);
379 IDecl->setLocation(ClassLoc);
380 IDecl->setForwardDecl(false);
381 IDecl->setAtStartLoc(AtInterfaceLoc);
382 // If the forward decl was in a PCH, we need to write it again in a
383 // dependent AST file.
384 IDecl->setChangedSinceDeserialization(true);
386 // Since this ObjCInterfaceDecl was created by a forward declaration,
387 // we now add it to the DeclContext since it wasn't added before
388 // (see ActOnForwardClassDeclaration).
389 IDecl->setLexicalDeclContext(CurContext);
390 CurContext->addDecl(IDecl);
393 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
396 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
397 ClassName, ClassLoc);
399 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
401 PushOnScopeChains(IDecl, TUScope);
405 // Check if a different kind of symbol declared in this scope.
406 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
410 // Try to correct for a typo in the superclass name.
411 TypoCorrection Corrected = CorrectTypo(
412 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
413 NULL, NULL, false, CTC_NoKeywords);
414 if ((PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
415 Diag(SuperLoc, diag::err_undef_superclass_suggest)
416 << SuperName << ClassName << PrevDecl->getDeclName();
417 Diag(PrevDecl->getLocation(), diag::note_previous_decl)
418 << PrevDecl->getDeclName();
422 if (PrevDecl == IDecl) {
423 Diag(SuperLoc, diag::err_recursive_superclass)
424 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
425 IDecl->setLocEnd(ClassLoc);
427 ObjCInterfaceDecl *SuperClassDecl =
428 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
430 // Diagnose classes that inherit from deprecated classes.
432 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
434 if (PrevDecl && SuperClassDecl == 0) {
435 // The previous declaration was not a class decl. Check if we have a
436 // typedef. If we do, get the underlying class type.
437 if (const TypedefNameDecl *TDecl =
438 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
439 QualType T = TDecl->getUnderlyingType();
440 if (T->isObjCObjectType()) {
441 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
442 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
446 // This handles the following case:
448 // typedef int SuperClass;
449 // @interface MyClass : SuperClass {} @end
451 if (!SuperClassDecl) {
452 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
453 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
457 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
459 Diag(SuperLoc, diag::err_undef_superclass)
460 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
461 else if (SuperClassDecl->isForwardDecl()) {
462 Diag(SuperLoc, diag::err_forward_superclass)
463 << SuperClassDecl->getDeclName() << ClassName
464 << SourceRange(AtInterfaceLoc, ClassLoc);
465 Diag(SuperClassDecl->getLocation(), diag::note_forward_class);
469 IDecl->setSuperClass(SuperClassDecl);
470 IDecl->setSuperClassLoc(SuperLoc);
471 IDecl->setLocEnd(SuperLoc);
473 } else { // we have a root class.
474 IDecl->setLocEnd(ClassLoc);
477 // Check then save referenced protocols.
479 IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
481 IDecl->setLocEnd(EndProtoLoc);
484 CheckObjCDeclScope(IDecl);
485 return ActOnObjCContainerStartDefinition(IDecl);
488 /// ActOnCompatiblityAlias - this action is called after complete parsing of
489 /// @compatibility_alias declaration. It sets up the alias relationships.
490 Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
491 IdentifierInfo *AliasName,
492 SourceLocation AliasLocation,
493 IdentifierInfo *ClassName,
494 SourceLocation ClassLocation) {
495 // Look for previous declaration of alias name
496 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
497 LookupOrdinaryName, ForRedeclaration);
499 if (isa<ObjCCompatibleAliasDecl>(ADecl))
500 Diag(AliasLocation, diag::warn_previous_alias_decl);
502 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
503 Diag(ADecl->getLocation(), diag::note_previous_declaration);
506 // Check for class declaration
507 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
508 LookupOrdinaryName, ForRedeclaration);
509 if (const TypedefNameDecl *TDecl =
510 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
511 QualType T = TDecl->getUnderlyingType();
512 if (T->isObjCObjectType()) {
513 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
514 ClassName = IDecl->getIdentifier();
515 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
516 LookupOrdinaryName, ForRedeclaration);
520 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
522 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
524 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
528 // Everything checked out, instantiate a new alias declaration AST.
529 ObjCCompatibleAliasDecl *AliasDecl =
530 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
532 if (!CheckObjCDeclScope(AliasDecl))
533 PushOnScopeChains(AliasDecl, TUScope);
538 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
539 IdentifierInfo *PName,
540 SourceLocation &Ploc, SourceLocation PrevLoc,
541 const ObjCList<ObjCProtocolDecl> &PList) {
544 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
545 E = PList.end(); I != E; ++I) {
546 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
548 if (PDecl->getIdentifier() == PName) {
549 Diag(Ploc, diag::err_protocol_has_circular_dependency);
550 Diag(PrevLoc, diag::note_previous_definition);
553 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
554 PDecl->getLocation(), PDecl->getReferencedProtocols()))
562 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
563 IdentifierInfo *ProtocolName,
564 SourceLocation ProtocolLoc,
565 Decl * const *ProtoRefs,
566 unsigned NumProtoRefs,
567 const SourceLocation *ProtoLocs,
568 SourceLocation EndProtoLoc,
569 AttributeList *AttrList) {
571 // FIXME: Deal with AttrList.
572 assert(ProtocolName && "Missing protocol identifier");
573 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
575 // Protocol already seen. Better be a forward protocol declaration
576 if (!PDecl->isForwardDecl()) {
577 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
578 Diag(PDecl->getLocation(), diag::note_previous_definition);
579 // Just return the protocol we already had.
580 // FIXME: don't leak the objects passed in!
581 return ActOnObjCContainerStartDefinition(PDecl);
583 ObjCList<ObjCProtocolDecl> PList;
584 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
585 err = CheckForwardProtocolDeclarationForCircularDependency(
586 ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
588 // Make sure the cached decl gets a valid start location.
589 PDecl->setAtStartLoc(AtProtoInterfaceLoc);
590 PDecl->setLocation(ProtocolLoc);
591 PDecl->setForwardDecl(false);
592 // Since this ObjCProtocolDecl was created by a forward declaration,
593 // we now add it to the DeclContext since it wasn't added before
594 PDecl->setLexicalDeclContext(CurContext);
595 CurContext->addDecl(PDecl);
596 // Repeat in dependent AST files.
597 PDecl->setChangedSinceDeserialization(true);
599 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
600 ProtocolLoc, AtProtoInterfaceLoc);
601 PushOnScopeChains(PDecl, TUScope);
602 PDecl->setForwardDecl(false);
605 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
606 if (!err && NumProtoRefs ) {
607 /// Check then save referenced protocols.
608 PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
610 PDecl->setLocEnd(EndProtoLoc);
613 CheckObjCDeclScope(PDecl);
614 return ActOnObjCContainerStartDefinition(PDecl);
617 /// FindProtocolDeclaration - This routine looks up protocols and
618 /// issues an error if they are not declared. It returns list of
619 /// protocol declarations in its 'Protocols' argument.
621 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
622 const IdentifierLocPair *ProtocolId,
623 unsigned NumProtocols,
624 SmallVectorImpl<Decl *> &Protocols) {
625 for (unsigned i = 0; i != NumProtocols; ++i) {
626 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
627 ProtocolId[i].second);
629 TypoCorrection Corrected = CorrectTypo(
630 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
631 LookupObjCProtocolName, TUScope, NULL, NULL, false, CTC_NoKeywords);
632 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>())) {
633 Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
634 << ProtocolId[i].first << Corrected.getCorrection();
635 Diag(PDecl->getLocation(), diag::note_previous_decl)
636 << PDecl->getDeclName();
641 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
642 << ProtocolId[i].first;
646 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
648 // If this is a forward declaration and we are supposed to warn in this
650 if (WarnOnDeclarations && PDecl->isForwardDecl())
651 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
652 << ProtocolId[i].first;
653 Protocols.push_back(PDecl);
657 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
658 /// a class method in its extension.
660 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
661 ObjCInterfaceDecl *ID) {
663 return; // Possibly due to previous error
665 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
666 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
667 e = ID->meth_end(); i != e; ++i) {
668 ObjCMethodDecl *MD = *i;
669 MethodMap[MD->getSelector()] = MD;
672 if (MethodMap.empty())
674 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
675 e = CAT->meth_end(); i != e; ++i) {
676 ObjCMethodDecl *Method = *i;
677 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
678 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
679 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
680 << Method->getDeclName();
681 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
686 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
688 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
689 const IdentifierLocPair *IdentList,
691 AttributeList *attrList) {
692 SmallVector<ObjCProtocolDecl*, 32> Protocols;
693 SmallVector<SourceLocation, 8> ProtoLocs;
695 for (unsigned i = 0; i != NumElts; ++i) {
696 IdentifierInfo *Ident = IdentList[i].first;
697 ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
699 if (PDecl == 0) { // Not already seen?
700 PDecl = ObjCProtocolDecl::Create(Context, CurContext, Ident,
701 IdentList[i].second, AtProtocolLoc);
702 PushOnScopeChains(PDecl, TUScope, false);
706 ProcessDeclAttributeList(TUScope, PDecl, attrList);
708 PDecl->setChangedSinceDeserialization(true);
710 Protocols.push_back(PDecl);
711 ProtoLocs.push_back(IdentList[i].second);
714 ObjCForwardProtocolDecl *PDecl =
715 ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
716 Protocols.data(), Protocols.size(),
718 CurContext->addDecl(PDecl);
719 CheckObjCDeclScope(PDecl);
724 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
725 IdentifierInfo *ClassName, SourceLocation ClassLoc,
726 IdentifierInfo *CategoryName,
727 SourceLocation CategoryLoc,
728 Decl * const *ProtoRefs,
729 unsigned NumProtoRefs,
730 const SourceLocation *ProtoLocs,
731 SourceLocation EndProtoLoc) {
732 ObjCCategoryDecl *CDecl;
733 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
735 /// Check that class of this category is already completely declared.
736 if (!IDecl || IDecl->isForwardDecl()) {
737 // Create an invalid ObjCCategoryDecl to serve as context for
738 // the enclosing method declarations. We mark the decl invalid
739 // to make it clear that this isn't a valid AST.
740 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
741 ClassLoc, CategoryLoc, CategoryName,IDecl);
742 CDecl->setInvalidDecl();
743 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
744 return ActOnObjCContainerStartDefinition(CDecl);
747 if (!CategoryName && IDecl->getImplementation()) {
748 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
749 Diag(IDecl->getImplementation()->getLocation(),
750 diag::note_implementation_declared);
754 /// Check for duplicate interface declaration for this category
755 ObjCCategoryDecl *CDeclChain;
756 for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
757 CDeclChain = CDeclChain->getNextClassCategory()) {
758 if (CDeclChain->getIdentifier() == CategoryName) {
759 // Class extensions can be declared multiple times.
760 Diag(CategoryLoc, diag::warn_dup_category_def)
761 << ClassName << CategoryName;
762 Diag(CDeclChain->getLocation(), diag::note_previous_definition);
768 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
769 ClassLoc, CategoryLoc, CategoryName, IDecl);
770 // FIXME: PushOnScopeChains?
771 CurContext->addDecl(CDecl);
774 CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
776 // Protocols in the class extension belong to the class.
777 if (CDecl->IsClassExtension())
778 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
779 NumProtoRefs, Context);
782 CheckObjCDeclScope(CDecl);
783 return ActOnObjCContainerStartDefinition(CDecl);
786 /// ActOnStartCategoryImplementation - Perform semantic checks on the
787 /// category implementation declaration and build an ObjCCategoryImplDecl
789 Decl *Sema::ActOnStartCategoryImplementation(
790 SourceLocation AtCatImplLoc,
791 IdentifierInfo *ClassName, SourceLocation ClassLoc,
792 IdentifierInfo *CatName, SourceLocation CatLoc) {
793 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
794 ObjCCategoryDecl *CatIDecl = 0;
796 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
798 // Category @implementation with no corresponding @interface.
799 // Create and install one.
800 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
801 SourceLocation(), SourceLocation(),
806 ObjCCategoryImplDecl *CDecl =
807 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
808 ClassLoc, AtCatImplLoc);
809 /// Check that class of this category is already completely declared.
810 if (!IDecl || IDecl->isForwardDecl()) {
811 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
812 CDecl->setInvalidDecl();
815 // FIXME: PushOnScopeChains?
816 CurContext->addDecl(CDecl);
818 // If the interface is deprecated/unavailable, warn/error about it.
820 DiagnoseUseOfDecl(IDecl, ClassLoc);
822 /// Check that CatName, category name, is not used in another implementation.
824 if (CatIDecl->getImplementation()) {
825 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
827 Diag(CatIDecl->getImplementation()->getLocation(),
828 diag::note_previous_definition);
830 CatIDecl->setImplementation(CDecl);
831 // Warn on implementating category of deprecated class under
832 // -Wdeprecated-implementations flag.
833 DiagnoseObjCImplementedDeprecations(*this,
834 dyn_cast<NamedDecl>(IDecl),
835 CDecl->getLocation(), 2);
839 CheckObjCDeclScope(CDecl);
840 return ActOnObjCContainerStartDefinition(CDecl);
843 Decl *Sema::ActOnStartClassImplementation(
844 SourceLocation AtClassImplLoc,
845 IdentifierInfo *ClassName, SourceLocation ClassLoc,
846 IdentifierInfo *SuperClassname,
847 SourceLocation SuperClassLoc) {
848 ObjCInterfaceDecl* IDecl = 0;
849 // Check for another declaration kind with the same name.
851 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
853 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
854 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
855 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
856 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
857 // If this is a forward declaration of an interface, warn.
858 if (IDecl->isForwardDecl()) {
859 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
863 // We did not find anything with the name ClassName; try to correct for
864 // typos in the class name.
865 TypoCorrection Corrected = CorrectTypo(
866 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
867 NULL, NULL, false, CTC_NoKeywords);
868 if ((IDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>())) {
869 // Suggest the (potentially) correct interface name. However, put the
870 // fix-it hint itself in a separate note, since changing the name in
871 // the warning would make the fix-it change semantics.However, don't
872 // provide a code-modification hint or use the typo name for recovery,
873 // because this is just a warning. The program may actually be correct.
874 DeclarationName CorrectedName = Corrected.getCorrection();
875 Diag(ClassLoc, diag::warn_undef_interface_suggest)
876 << ClassName << CorrectedName;
877 Diag(IDecl->getLocation(), diag::note_previous_decl) << CorrectedName
878 << FixItHint::CreateReplacement(ClassLoc, CorrectedName.getAsString());
881 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
885 // Check that super class name is valid class name
886 ObjCInterfaceDecl* SDecl = 0;
887 if (SuperClassname) {
888 // Check if a different kind of symbol declared in this scope.
889 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
891 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
892 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
894 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
896 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
898 Diag(SuperClassLoc, diag::err_undef_superclass)
899 << SuperClassname << ClassName;
900 else if (IDecl && IDecl->getSuperClass() != SDecl) {
901 // This implementation and its interface do not have the same
903 Diag(SuperClassLoc, diag::err_conflicting_super_class)
904 << SDecl->getDeclName();
905 Diag(SDecl->getLocation(), diag::note_previous_definition);
911 // Legacy case of @implementation with no corresponding @interface.
912 // Build, chain & install the interface decl into the identifier.
914 // FIXME: Do we support attributes on the @implementation? If so we should
916 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
917 ClassName, ClassLoc, false, true);
918 IDecl->setSuperClass(SDecl);
919 IDecl->setLocEnd(ClassLoc);
921 PushOnScopeChains(IDecl, TUScope);
923 // Mark the interface as being completed, even if it was just as
925 // declaration; the user cannot reopen it.
926 IDecl->setForwardDecl(false);
929 ObjCImplementationDecl* IMPDecl =
930 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
931 ClassLoc, AtClassImplLoc);
933 if (CheckObjCDeclScope(IMPDecl))
934 return ActOnObjCContainerStartDefinition(IMPDecl);
936 // Check that there is no duplicate implementation of this class.
937 if (IDecl->getImplementation()) {
938 // FIXME: Don't leak everything!
939 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
940 Diag(IDecl->getImplementation()->getLocation(),
941 diag::note_previous_definition);
942 } else { // add it to the list.
943 IDecl->setImplementation(IMPDecl);
944 PushOnScopeChains(IMPDecl, TUScope);
945 // Warn on implementating deprecated class under
946 // -Wdeprecated-implementations flag.
947 DiagnoseObjCImplementedDeprecations(*this,
948 dyn_cast<NamedDecl>(IDecl),
949 IMPDecl->getLocation(), 1);
951 return ActOnObjCContainerStartDefinition(IMPDecl);
954 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
955 ObjCIvarDecl **ivars, unsigned numIvars,
956 SourceLocation RBrace) {
957 assert(ImpDecl && "missing implementation decl");
958 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
961 /// Check case of non-existing @interface decl.
962 /// (legacy objective-c @implementation decl without an @interface decl).
963 /// Add implementations's ivar to the synthesize class's ivar list.
964 if (IDecl->isImplicitInterfaceDecl()) {
965 IDecl->setLocEnd(RBrace);
966 // Add ivar's to class's DeclContext.
967 for (unsigned i = 0, e = numIvars; i != e; ++i) {
968 ivars[i]->setLexicalDeclContext(ImpDecl);
969 IDecl->makeDeclVisibleInContext(ivars[i], false);
970 ImpDecl->addDecl(ivars[i]);
975 // If implementation has empty ivar list, just return.
979 assert(ivars && "missing @implementation ivars");
980 if (LangOpts.ObjCNonFragileABI2) {
981 if (ImpDecl->getSuperClass())
982 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
983 for (unsigned i = 0; i < numIvars; i++) {
984 ObjCIvarDecl* ImplIvar = ivars[i];
985 if (const ObjCIvarDecl *ClsIvar =
986 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
987 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
988 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
991 // Instance ivar to Implementation's DeclContext.
992 ImplIvar->setLexicalDeclContext(ImpDecl);
993 IDecl->makeDeclVisibleInContext(ImplIvar, false);
994 ImpDecl->addDecl(ImplIvar);
998 // Check interface's Ivar list against those in the implementation.
999 // names and types must match.
1002 ObjCInterfaceDecl::ivar_iterator
1003 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1004 for (; numIvars > 0 && IVI != IVE; ++IVI) {
1005 ObjCIvarDecl* ImplIvar = ivars[j++];
1006 ObjCIvarDecl* ClsIvar = *IVI;
1007 assert (ImplIvar && "missing implementation ivar");
1008 assert (ClsIvar && "missing class ivar");
1010 // First, make sure the types match.
1011 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1012 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1013 << ImplIvar->getIdentifier()
1014 << ImplIvar->getType() << ClsIvar->getType();
1015 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1016 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1017 ImplIvar->getBitWidthValue(Context) !=
1018 ClsIvar->getBitWidthValue(Context)) {
1019 Diag(ImplIvar->getBitWidth()->getLocStart(),
1020 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1021 Diag(ClsIvar->getBitWidth()->getLocStart(),
1022 diag::note_previous_definition);
1024 // Make sure the names are identical.
1025 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1026 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1027 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1028 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1034 Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
1035 else if (IVI != IVE)
1036 Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
1039 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
1040 bool &IncompleteImpl, unsigned DiagID) {
1041 // No point warning no definition of method which is 'unavailable'.
1042 if (method->hasAttr<UnavailableAttr>())
1044 if (!IncompleteImpl) {
1045 Diag(ImpLoc, diag::warn_incomplete_impl);
1046 IncompleteImpl = true;
1048 if (DiagID == diag::warn_unimplemented_protocol_method)
1049 Diag(ImpLoc, DiagID) << method->getDeclName();
1051 Diag(method->getLocation(), DiagID) << method->getDeclName();
1054 /// Determines if type B can be substituted for type A. Returns true if we can
1055 /// guarantee that anything that the user will do to an object of type A can
1056 /// also be done to an object of type B. This is trivially true if the two
1057 /// types are the same, or if B is a subclass of A. It becomes more complex
1058 /// in cases where protocols are involved.
1060 /// Object types in Objective-C describe the minimum requirements for an
1061 /// object, rather than providing a complete description of a type. For
1062 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1063 /// The principle of substitutability means that we may use an instance of A
1064 /// anywhere that we may use an instance of B - it will implement all of the
1065 /// ivars of B and all of the methods of B.
1067 /// This substitutability is important when type checking methods, because
1068 /// the implementation may have stricter type definitions than the interface.
1069 /// The interface specifies minimum requirements, but the implementation may
1070 /// have more accurate ones. For example, a method may privately accept
1071 /// instances of B, but only publish that it accepts instances of A. Any
1072 /// object passed to it will be type checked against B, and so will implicitly
1073 /// by a valid A*. Similarly, a method may return a subclass of the class that
1074 /// it is declared as returning.
1076 /// This is most important when considering subclassing. A method in a
1077 /// subclass must accept any object as an argument that its superclass's
1078 /// implementation accepts. It may, however, accept a more general type
1079 /// without breaking substitutability (i.e. you can still use the subclass
1080 /// anywhere that you can use the superclass, but not vice versa). The
1081 /// converse requirement applies to return types: the return type for a
1082 /// subclass method must be a valid object of the kind that the superclass
1083 /// advertises, but it may be specified more accurately. This avoids the need
1084 /// for explicit down-casting by callers.
1086 /// Note: This is a stricter requirement than for assignment.
1087 static bool isObjCTypeSubstitutable(ASTContext &Context,
1088 const ObjCObjectPointerType *A,
1089 const ObjCObjectPointerType *B,
1091 // Reject a protocol-unqualified id.
1092 if (rejectId && B->isObjCIdType()) return false;
1094 // If B is a qualified id, then A must also be a qualified id and it must
1095 // implement all of the protocols in B. It may not be a qualified class.
1096 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1097 // stricter definition so it is not substitutable for id<A>.
1098 if (B->isObjCQualifiedIdType()) {
1099 return A->isObjCQualifiedIdType() &&
1100 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1106 // id is a special type that bypasses type checking completely. We want a
1107 // warning when it is used in one place but not another.
1108 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1111 // If B is a qualified id, then A must also be a qualified id (which it isn't
1112 // if we've got this far)
1113 if (B->isObjCQualifiedIdType()) return false;
1116 // Now we know that A and B are (potentially-qualified) class types. The
1117 // normal rules for assignment apply.
1118 return Context.canAssignObjCInterfaces(A, B);
1121 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1122 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1125 static bool CheckMethodOverrideReturn(Sema &S,
1126 ObjCMethodDecl *MethodImpl,
1127 ObjCMethodDecl *MethodDecl,
1128 bool IsProtocolMethodDecl,
1129 bool IsOverridingMode,
1131 if (IsProtocolMethodDecl &&
1132 (MethodDecl->getObjCDeclQualifier() !=
1133 MethodImpl->getObjCDeclQualifier())) {
1135 S.Diag(MethodImpl->getLocation(),
1137 diag::warn_conflicting_overriding_ret_type_modifiers
1138 : diag::warn_conflicting_ret_type_modifiers))
1139 << MethodImpl->getDeclName()
1140 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1141 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1142 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1148 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
1149 MethodDecl->getResultType()))
1155 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1156 : diag::warn_conflicting_ret_types;
1158 // Mismatches between ObjC pointers go into a different warning
1159 // category, and sometimes they're even completely whitelisted.
1160 if (const ObjCObjectPointerType *ImplPtrTy =
1161 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
1162 if (const ObjCObjectPointerType *IfacePtrTy =
1163 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
1164 // Allow non-matching return types as long as they don't violate
1165 // the principle of substitutability. Specifically, we permit
1166 // return types that are subclasses of the declared return type,
1167 // or that are more-qualified versions of the declared type.
1168 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1172 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1173 : diag::warn_non_covariant_ret_types;
1177 S.Diag(MethodImpl->getLocation(), DiagID)
1178 << MethodImpl->getDeclName()
1179 << MethodDecl->getResultType()
1180 << MethodImpl->getResultType()
1181 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
1182 S.Diag(MethodDecl->getLocation(),
1183 IsOverridingMode ? diag::note_previous_declaration
1184 : diag::note_previous_definition)
1185 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
1189 static bool CheckMethodOverrideParam(Sema &S,
1190 ObjCMethodDecl *MethodImpl,
1191 ObjCMethodDecl *MethodDecl,
1192 ParmVarDecl *ImplVar,
1193 ParmVarDecl *IfaceVar,
1194 bool IsProtocolMethodDecl,
1195 bool IsOverridingMode,
1197 if (IsProtocolMethodDecl &&
1198 (ImplVar->getObjCDeclQualifier() !=
1199 IfaceVar->getObjCDeclQualifier())) {
1201 if (IsOverridingMode)
1202 S.Diag(ImplVar->getLocation(),
1203 diag::warn_conflicting_overriding_param_modifiers)
1204 << getTypeRange(ImplVar->getTypeSourceInfo())
1205 << MethodImpl->getDeclName();
1206 else S.Diag(ImplVar->getLocation(),
1207 diag::warn_conflicting_param_modifiers)
1208 << getTypeRange(ImplVar->getTypeSourceInfo())
1209 << MethodImpl->getDeclName();
1210 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1211 << getTypeRange(IfaceVar->getTypeSourceInfo());
1217 QualType ImplTy = ImplVar->getType();
1218 QualType IfaceTy = IfaceVar->getType();
1220 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1226 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1227 : diag::warn_conflicting_param_types;
1229 // Mismatches between ObjC pointers go into a different warning
1230 // category, and sometimes they're even completely whitelisted.
1231 if (const ObjCObjectPointerType *ImplPtrTy =
1232 ImplTy->getAs<ObjCObjectPointerType>()) {
1233 if (const ObjCObjectPointerType *IfacePtrTy =
1234 IfaceTy->getAs<ObjCObjectPointerType>()) {
1235 // Allow non-matching argument types as long as they don't
1236 // violate the principle of substitutability. Specifically, the
1237 // implementation must accept any objects that the superclass
1238 // accepts, however it may also accept others.
1239 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1243 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1244 : diag::warn_non_contravariant_param_types;
1248 S.Diag(ImplVar->getLocation(), DiagID)
1249 << getTypeRange(ImplVar->getTypeSourceInfo())
1250 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1251 S.Diag(IfaceVar->getLocation(),
1252 (IsOverridingMode ? diag::note_previous_declaration
1253 : diag::note_previous_definition))
1254 << getTypeRange(IfaceVar->getTypeSourceInfo());
1258 /// In ARC, check whether the conventional meanings of the two methods
1259 /// match. If they don't, it's a hard error.
1260 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1261 ObjCMethodDecl *decl) {
1262 ObjCMethodFamily implFamily = impl->getMethodFamily();
1263 ObjCMethodFamily declFamily = decl->getMethodFamily();
1264 if (implFamily == declFamily) return false;
1266 // Since conventions are sorted by selector, the only possibility is
1267 // that the types differ enough to cause one selector or the other
1268 // to fall out of the family.
1269 assert(implFamily == OMF_None || declFamily == OMF_None);
1271 // No further diagnostics required on invalid declarations.
1272 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1274 const ObjCMethodDecl *unmatched = impl;
1275 ObjCMethodFamily family = declFamily;
1276 unsigned errorID = diag::err_arc_lost_method_convention;
1277 unsigned noteID = diag::note_arc_lost_method_convention;
1278 if (declFamily == OMF_None) {
1280 family = implFamily;
1281 errorID = diag::err_arc_gained_method_convention;
1282 noteID = diag::note_arc_gained_method_convention;
1285 // Indexes into a %select clause in the diagnostic.
1286 enum FamilySelector {
1287 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1289 FamilySelector familySelector = FamilySelector();
1292 case OMF_None: llvm_unreachable("logic error, no method convention");
1295 case OMF_autorelease:
1298 case OMF_retainCount:
1300 case OMF_performSelector:
1301 // Mismatches for these methods don't change ownership
1302 // conventions, so we don't care.
1305 case OMF_init: familySelector = F_init; break;
1306 case OMF_alloc: familySelector = F_alloc; break;
1307 case OMF_copy: familySelector = F_copy; break;
1308 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1309 case OMF_new: familySelector = F_new; break;
1312 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1313 ReasonSelector reasonSelector;
1315 // The only reason these methods don't fall within their families is
1316 // due to unusual result types.
1317 if (unmatched->getResultType()->isObjCObjectPointerType()) {
1318 reasonSelector = R_UnrelatedReturn;
1320 reasonSelector = R_NonObjectReturn;
1323 S.Diag(impl->getLocation(), errorID) << familySelector << reasonSelector;
1324 S.Diag(decl->getLocation(), noteID) << familySelector << reasonSelector;
1329 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1330 ObjCMethodDecl *MethodDecl,
1331 bool IsProtocolMethodDecl) {
1332 if (getLangOptions().ObjCAutoRefCount &&
1333 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1336 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1337 IsProtocolMethodDecl, false,
1340 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1341 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1342 IM != EM; ++IM, ++IF) {
1343 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1344 IsProtocolMethodDecl, false, true);
1347 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1348 Diag(ImpMethodDecl->getLocation(),
1349 diag::warn_conflicting_variadic);
1350 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1354 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1355 ObjCMethodDecl *Overridden,
1356 bool IsProtocolMethodDecl) {
1358 CheckMethodOverrideReturn(*this, Method, Overridden,
1359 IsProtocolMethodDecl, true,
1362 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1363 IF = Overridden->param_begin(), EM = Method->param_end();
1364 IM != EM; ++IM, ++IF) {
1365 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1366 IsProtocolMethodDecl, true, true);
1369 if (Method->isVariadic() != Overridden->isVariadic()) {
1370 Diag(Method->getLocation(),
1371 diag::warn_conflicting_overriding_variadic);
1372 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1376 /// WarnExactTypedMethods - This routine issues a warning if method
1377 /// implementation declaration matches exactly that of its declaration.
1378 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1379 ObjCMethodDecl *MethodDecl,
1380 bool IsProtocolMethodDecl) {
1381 // don't issue warning when protocol method is optional because primary
1382 // class is not required to implement it and it is safe for protocol
1384 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1386 // don't issue warning when primary class's method is
1387 // depecated/unavailable.
1388 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1389 MethodDecl->hasAttr<DeprecatedAttr>())
1392 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1393 IsProtocolMethodDecl, false, false);
1395 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1396 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
1397 IM != EM; ++IM, ++IF) {
1398 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1400 IsProtocolMethodDecl, false, false);
1405 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1407 match = !(MethodDecl->isClassMethod() &&
1408 MethodDecl->getSelector() == GetNullarySelector("load", Context));
1411 Diag(ImpMethodDecl->getLocation(),
1412 diag::warn_category_method_impl_match);
1413 Diag(MethodDecl->getLocation(), diag::note_method_declared_at);
1417 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1418 /// improve the efficiency of selector lookups and type checking by associating
1419 /// with each protocol / interface / category the flattened instance tables. If
1420 /// we used an immutable set to keep the table then it wouldn't add significant
1421 /// memory cost and it would be handy for lookups.
1423 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1424 /// Declared in protocol, and those referenced by it.
1425 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
1426 ObjCProtocolDecl *PDecl,
1427 bool& IncompleteImpl,
1428 const llvm::DenseSet<Selector> &InsMap,
1429 const llvm::DenseSet<Selector> &ClsMap,
1430 ObjCContainerDecl *CDecl) {
1431 ObjCInterfaceDecl *IDecl;
1432 if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
1433 IDecl = C->getClassInterface();
1435 IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
1436 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1438 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1439 ObjCInterfaceDecl *NSIDecl = 0;
1440 if (getLangOptions().NeXTRuntime) {
1441 // check to see if class implements forwardInvocation method and objects
1442 // of this class are derived from 'NSProxy' so that to forward requests
1443 // from one object to another.
1444 // Under such conditions, which means that every method possible is
1445 // implemented in the class, we should not issue "Method definition not
1447 // FIXME: Use a general GetUnarySelector method for this.
1448 IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1449 Selector fISelector = Context.Selectors.getSelector(1, &II);
1450 if (InsMap.count(fISelector))
1451 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1452 // need be implemented in the implementation.
1453 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1456 // If a method lookup fails locally we still need to look and see if
1457 // the method was implemented by a base class or an inherited
1458 // protocol. This lookup is slow, but occurs rarely in correct code
1459 // and otherwise would terminate in a warning.
1461 // check unimplemented instance methods.
1463 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1464 E = PDecl->instmeth_end(); I != E; ++I) {
1465 ObjCMethodDecl *method = *I;
1466 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1467 !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
1469 !Super->lookupInstanceMethod(method->getSelector()))) {
1470 // Ugly, but necessary. Method declared in protcol might have
1471 // have been synthesized due to a property declared in the class which
1472 // uses the protocol.
1473 ObjCMethodDecl *MethodInClass =
1474 IDecl->lookupInstanceMethod(method->getSelector());
1475 if (!MethodInClass || !MethodInClass->isSynthesized()) {
1476 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1477 if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1478 != DiagnosticsEngine::Ignored) {
1479 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1480 Diag(method->getLocation(), diag::note_method_declared_at);
1481 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1482 << PDecl->getDeclName();
1487 // check unimplemented class methods
1488 for (ObjCProtocolDecl::classmeth_iterator
1489 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1491 ObjCMethodDecl *method = *I;
1492 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1493 !ClsMap.count(method->getSelector()) &&
1494 (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1495 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1496 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
1497 DiagnosticsEngine::Ignored) {
1498 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1499 Diag(method->getLocation(), diag::note_method_declared_at);
1500 Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1501 PDecl->getDeclName();
1505 // Check on this protocols's referenced protocols, recursively.
1506 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1507 E = PDecl->protocol_end(); PI != E; ++PI)
1508 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
1511 /// MatchAllMethodDeclarations - Check methods declared in interface
1512 /// or protocol against those declared in their implementations.
1514 void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1515 const llvm::DenseSet<Selector> &ClsMap,
1516 llvm::DenseSet<Selector> &InsMapSeen,
1517 llvm::DenseSet<Selector> &ClsMapSeen,
1518 ObjCImplDecl* IMPDecl,
1519 ObjCContainerDecl* CDecl,
1520 bool &IncompleteImpl,
1521 bool ImmediateClass,
1522 bool WarnExactMatch) {
1523 // Check and see if instance methods in class interface have been
1524 // implemented in the implementation class. If so, their types match.
1525 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1526 E = CDecl->instmeth_end(); I != E; ++I) {
1527 if (InsMapSeen.count((*I)->getSelector()))
1529 InsMapSeen.insert((*I)->getSelector());
1530 if (!(*I)->isSynthesized() &&
1531 !InsMap.count((*I)->getSelector())) {
1533 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1534 diag::note_undef_method_impl);
1537 ObjCMethodDecl *ImpMethodDecl =
1538 IMPDecl->getInstanceMethod((*I)->getSelector());
1539 assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
1540 "Expected to find the method through lookup as well");
1541 ObjCMethodDecl *MethodDecl = *I;
1542 // ImpMethodDecl may be null as in a @dynamic property.
1543 if (ImpMethodDecl) {
1544 if (!WarnExactMatch)
1545 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1546 isa<ObjCProtocolDecl>(CDecl));
1547 else if (!MethodDecl->isSynthesized())
1548 WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1549 isa<ObjCProtocolDecl>(CDecl));
1554 // Check and see if class methods in class interface have been
1555 // implemented in the implementation class. If so, their types match.
1556 for (ObjCInterfaceDecl::classmeth_iterator
1557 I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1558 if (ClsMapSeen.count((*I)->getSelector()))
1560 ClsMapSeen.insert((*I)->getSelector());
1561 if (!ClsMap.count((*I)->getSelector())) {
1563 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1564 diag::note_undef_method_impl);
1566 ObjCMethodDecl *ImpMethodDecl =
1567 IMPDecl->getClassMethod((*I)->getSelector());
1568 assert(CDecl->getClassMethod((*I)->getSelector()) &&
1569 "Expected to find the method through lookup as well");
1570 ObjCMethodDecl *MethodDecl = *I;
1571 if (!WarnExactMatch)
1572 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1573 isa<ObjCProtocolDecl>(CDecl));
1575 WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1576 isa<ObjCProtocolDecl>(CDecl));
1580 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1581 // Also methods in class extensions need be looked at next.
1582 for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
1583 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1584 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1586 const_cast<ObjCCategoryDecl *>(ClsExtDecl),
1587 IncompleteImpl, false, WarnExactMatch);
1589 // Check for any implementation of a methods declared in protocol.
1590 for (ObjCInterfaceDecl::all_protocol_iterator
1591 PI = I->all_referenced_protocol_begin(),
1592 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1593 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1595 (*PI), IncompleteImpl, false, WarnExactMatch);
1597 // FIXME. For now, we are not checking for extact match of methods
1598 // in category implementation and its primary class's super class.
1599 if (!WarnExactMatch && I->getSuperClass())
1600 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1602 I->getSuperClass(), IncompleteImpl, false);
1606 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1607 /// category matches with those implemented in its primary class and
1608 /// warns each time an exact match is found.
1609 void Sema::CheckCategoryVsClassMethodMatches(
1610 ObjCCategoryImplDecl *CatIMPDecl) {
1611 llvm::DenseSet<Selector> InsMap, ClsMap;
1613 for (ObjCImplementationDecl::instmeth_iterator
1614 I = CatIMPDecl->instmeth_begin(),
1615 E = CatIMPDecl->instmeth_end(); I!=E; ++I)
1616 InsMap.insert((*I)->getSelector());
1618 for (ObjCImplementationDecl::classmeth_iterator
1619 I = CatIMPDecl->classmeth_begin(),
1620 E = CatIMPDecl->classmeth_end(); I != E; ++I)
1621 ClsMap.insert((*I)->getSelector());
1622 if (InsMap.empty() && ClsMap.empty())
1625 // Get category's primary class.
1626 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1629 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1632 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1633 bool IncompleteImpl = false;
1634 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1636 IncompleteImpl, false, true /*WarnExactMatch*/);
1639 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1640 ObjCContainerDecl* CDecl,
1641 bool IncompleteImpl) {
1642 llvm::DenseSet<Selector> InsMap;
1643 // Check and see if instance methods in class interface have been
1644 // implemented in the implementation class.
1645 for (ObjCImplementationDecl::instmeth_iterator
1646 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1647 InsMap.insert((*I)->getSelector());
1649 // Check and see if properties declared in the interface have either 1)
1650 // an implementation or 2) there is a @synthesize/@dynamic implementation
1651 // of the property in the @implementation.
1652 if (isa<ObjCInterfaceDecl>(CDecl) &&
1653 !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2))
1654 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1656 llvm::DenseSet<Selector> ClsMap;
1657 for (ObjCImplementationDecl::classmeth_iterator
1658 I = IMPDecl->classmeth_begin(),
1659 E = IMPDecl->classmeth_end(); I != E; ++I)
1660 ClsMap.insert((*I)->getSelector());
1662 // Check for type conflict of methods declared in a class/protocol and
1663 // its implementation; if any.
1664 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1665 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1667 IncompleteImpl, true);
1669 // check all methods implemented in category against those declared
1670 // in its primary class.
1671 if (ObjCCategoryImplDecl *CatDecl =
1672 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1673 CheckCategoryVsClassMethodMatches(CatDecl);
1675 // Check the protocol list for unimplemented methods in the @implementation
1677 // Check and see if class methods in class interface have been
1678 // implemented in the implementation class.
1680 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1681 for (ObjCInterfaceDecl::all_protocol_iterator
1682 PI = I->all_referenced_protocol_begin(),
1683 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1684 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1686 // Check class extensions (unnamed categories)
1687 for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
1688 Categories; Categories = Categories->getNextClassExtension())
1689 ImplMethodsVsClassMethods(S, IMPDecl,
1690 const_cast<ObjCCategoryDecl*>(Categories),
1692 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1693 // For extended class, unimplemented methods in its protocols will
1694 // be reported in the primary class.
1695 if (!C->IsClassExtension()) {
1696 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1697 E = C->protocol_end(); PI != E; ++PI)
1698 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1699 InsMap, ClsMap, CDecl);
1700 // Report unimplemented properties in the category as well.
1701 // When reporting on missing setter/getters, do not report when
1702 // setter/getter is implemented in category's primary class
1704 if (ObjCInterfaceDecl *ID = C->getClassInterface())
1705 if (ObjCImplDecl *IMP = ID->getImplementation()) {
1706 for (ObjCImplementationDecl::instmeth_iterator
1707 I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1708 InsMap.insert((*I)->getSelector());
1710 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1713 llvm_unreachable("invalid ObjCContainerDecl type.");
1716 /// ActOnForwardClassDeclaration -
1717 Sema::DeclGroupPtrTy
1718 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1719 IdentifierInfo **IdentList,
1720 SourceLocation *IdentLocs,
1722 SmallVector<Decl *, 8> DeclsInGroup;
1723 for (unsigned i = 0; i != NumElts; ++i) {
1724 // Check for another declaration kind with the same name.
1726 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1727 LookupOrdinaryName, ForRedeclaration);
1728 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1729 // Maybe we will complain about the shadowed template parameter.
1730 DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1731 // Just pretend that we didn't see the previous declaration.
1735 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1736 // GCC apparently allows the following idiom:
1738 // typedef NSObject < XCElementTogglerP > XCElementToggler;
1739 // @class XCElementToggler;
1741 // FIXME: Make an extension?
1742 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1743 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1744 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1745 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1747 // a forward class declaration matching a typedef name of a class refers
1748 // to the underlying class.
1749 if (const ObjCObjectType *OI =
1750 TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1751 PrevDecl = OI->getInterface();
1754 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1755 if (!IDecl) { // Not already seen? Make a forward decl.
1756 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1757 IdentList[i], IdentLocs[i], true);
1759 // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1760 // the current DeclContext. This prevents clients that walk DeclContext
1761 // from seeing the imaginary ObjCInterfaceDecl until it is actually
1762 // declared later (if at all). We also take care to explicitly make
1763 // sure this declaration is visible for name lookup.
1764 PushOnScopeChains(IDecl, TUScope, false);
1765 CurContext->makeDeclVisibleInContext(IDecl, true);
1767 ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1768 IDecl, IdentLocs[i]);
1769 CurContext->addDecl(CDecl);
1770 CheckObjCDeclScope(CDecl);
1771 DeclsInGroup.push_back(CDecl);
1774 return BuildDeclaratorGroup(DeclsInGroup.data(), DeclsInGroup.size(), false);
1777 static bool tryMatchRecordTypes(ASTContext &Context,
1778 Sema::MethodMatchStrategy strategy,
1779 const Type *left, const Type *right);
1781 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
1782 QualType leftQT, QualType rightQT) {
1784 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
1786 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
1788 if (left == right) return true;
1790 // If we're doing a strict match, the types have to match exactly.
1791 if (strategy == Sema::MMS_strict) return false;
1793 if (left->isIncompleteType() || right->isIncompleteType()) return false;
1795 // Otherwise, use this absurdly complicated algorithm to try to
1796 // validate the basic, low-level compatibility of the two types.
1798 // As a minimum, require the sizes and alignments to match.
1799 if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
1802 // Consider all the kinds of non-dependent canonical types:
1803 // - functions and arrays aren't possible as return and parameter types
1805 // - vector types of equal size can be arbitrarily mixed
1806 if (isa<VectorType>(left)) return isa<VectorType>(right);
1807 if (isa<VectorType>(right)) return false;
1809 // - references should only match references of identical type
1810 // - structs, unions, and Objective-C objects must match more-or-less
1812 // - everything else should be a scalar
1813 if (!left->isScalarType() || !right->isScalarType())
1814 return tryMatchRecordTypes(Context, strategy, left, right);
1816 // Make scalars agree in kind, except count bools as chars, and group
1817 // all non-member pointers together.
1818 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
1819 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
1820 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
1821 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
1822 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
1823 leftSK = Type::STK_ObjCObjectPointer;
1824 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
1825 rightSK = Type::STK_ObjCObjectPointer;
1827 // Note that data member pointers and function member pointers don't
1828 // intermix because of the size differences.
1830 return (leftSK == rightSK);
1833 static bool tryMatchRecordTypes(ASTContext &Context,
1834 Sema::MethodMatchStrategy strategy,
1835 const Type *lt, const Type *rt) {
1836 assert(lt && rt && lt != rt);
1838 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
1839 RecordDecl *left = cast<RecordType>(lt)->getDecl();
1840 RecordDecl *right = cast<RecordType>(rt)->getDecl();
1842 // Require union-hood to match.
1843 if (left->isUnion() != right->isUnion()) return false;
1845 // Require an exact match if either is non-POD.
1846 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
1847 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
1850 // Require size and alignment to match.
1851 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
1853 // Require fields to match.
1854 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
1855 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
1856 for (; li != le && ri != re; ++li, ++ri) {
1857 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
1860 return (li == le && ri == re);
1863 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1864 /// returns true, or false, accordingly.
1865 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1866 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
1867 const ObjCMethodDecl *right,
1868 MethodMatchStrategy strategy) {
1869 if (!matchTypes(Context, strategy,
1870 left->getResultType(), right->getResultType()))
1873 if (getLangOptions().ObjCAutoRefCount &&
1874 (left->hasAttr<NSReturnsRetainedAttr>()
1875 != right->hasAttr<NSReturnsRetainedAttr>() ||
1876 left->hasAttr<NSConsumesSelfAttr>()
1877 != right->hasAttr<NSConsumesSelfAttr>()))
1880 ObjCMethodDecl::param_const_iterator
1881 li = left->param_begin(), le = left->param_end(), ri = right->param_begin();
1883 for (; li != le; ++li, ++ri) {
1884 assert(ri != right->param_end() && "Param mismatch");
1885 const ParmVarDecl *lparm = *li, *rparm = *ri;
1887 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
1890 if (getLangOptions().ObjCAutoRefCount &&
1891 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
1897 /// \brief Read the contents of the method pool for a given selector from
1898 /// external storage.
1900 /// This routine should only be called once, when the method pool has no entry
1901 /// for this selector.
1902 Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
1903 assert(ExternalSource && "We need an external AST source");
1904 assert(MethodPool.find(Sel) == MethodPool.end() &&
1905 "Selector data already loaded into the method pool");
1907 // Read the method list from the external source.
1908 GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
1910 return MethodPool.insert(std::make_pair(Sel, Methods)).first;
1913 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
1915 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
1916 if (Pos == MethodPool.end()) {
1918 Pos = ReadMethodPool(Method->getSelector());
1920 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
1921 GlobalMethods())).first;
1923 Method->setDefined(impl);
1924 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
1925 if (Entry.Method == 0) {
1926 // Haven't seen a method with this selector name yet - add it.
1927 Entry.Method = Method;
1932 // We've seen a method with this name, see if we have already seen this type
1934 for (ObjCMethodList *List = &Entry; List; List = List->Next) {
1935 bool match = MatchTwoMethodDeclarations(Method, List->Method);
1938 ObjCMethodDecl *PrevObjCMethod = List->Method;
1939 PrevObjCMethod->setDefined(impl);
1940 // If a method is deprecated, push it in the global pool.
1941 // This is used for better diagnostics.
1942 if (Method->isDeprecated()) {
1943 if (!PrevObjCMethod->isDeprecated())
1944 List->Method = Method;
1946 // If new method is unavailable, push it into global pool
1947 // unless previous one is deprecated.
1948 if (Method->isUnavailable()) {
1949 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
1950 List->Method = Method;
1956 // We have a new signature for an existing method - add it.
1957 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1958 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1959 Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1962 /// Determines if this is an "acceptable" loose mismatch in the global
1963 /// method pool. This exists mostly as a hack to get around certain
1964 /// global mismatches which we can't afford to make warnings / errors.
1965 /// Really, what we want is a way to take a method out of the global
1967 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
1968 ObjCMethodDecl *other) {
1969 if (!chosen->isInstanceMethod())
1972 Selector sel = chosen->getSelector();
1973 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
1976 // Don't complain about mismatches for -length if the method we
1977 // chose has an integral result type.
1978 return (chosen->getResultType()->isIntegerType());
1981 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1982 bool receiverIdOrClass,
1983 bool warn, bool instance) {
1984 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1985 if (Pos == MethodPool.end()) {
1987 Pos = ReadMethodPool(Sel);
1992 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
1994 if (warn && MethList.Method && MethList.Next) {
1995 bool issueDiagnostic = false, issueError = false;
1997 // We support a warning which complains about *any* difference in
1998 // method signature.
1999 bool strictSelectorMatch =
2000 (receiverIdOrClass && warn &&
2001 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
2003 DiagnosticsEngine::Ignored));
2004 if (strictSelectorMatch)
2005 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2006 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2008 issueDiagnostic = true;
2013 // If we didn't see any strict differences, we won't see any loose
2014 // differences. In ARC, however, we also need to check for loose
2015 // mismatches, because most of them are errors.
2016 if (!strictSelectorMatch ||
2017 (issueDiagnostic && getLangOptions().ObjCAutoRefCount))
2018 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
2019 // This checks if the methods differ in type mismatch.
2020 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method,
2022 !isAcceptableMethodMismatch(MethList.Method, Next->Method)) {
2023 issueDiagnostic = true;
2024 if (getLangOptions().ObjCAutoRefCount)
2030 if (issueDiagnostic) {
2032 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2033 else if (strictSelectorMatch)
2034 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2036 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2038 Diag(MethList.Method->getLocStart(),
2039 issueError ? diag::note_possibility : diag::note_using)
2040 << MethList.Method->getSourceRange();
2041 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
2042 Diag(Next->Method->getLocStart(), diag::note_also_found)
2043 << Next->Method->getSourceRange();
2046 return MethList.Method;
2049 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2050 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2051 if (Pos == MethodPool.end())
2054 GlobalMethods &Methods = Pos->second;
2056 if (Methods.first.Method && Methods.first.Method->isDefined())
2057 return Methods.first.Method;
2058 if (Methods.second.Method && Methods.second.Method->isDefined())
2059 return Methods.second.Method;
2063 /// CompareMethodParamsInBaseAndSuper - This routine compares methods with
2064 /// identical selector names in current and its super classes and issues
2065 /// a warning if any of their argument types are incompatible.
2066 void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
2067 ObjCMethodDecl *Method,
2069 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2070 if (ID == 0) return;
2072 while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
2073 ObjCMethodDecl *SuperMethodDecl =
2074 SD->lookupMethod(Method->getSelector(), IsInstance);
2075 if (SuperMethodDecl == 0) {
2079 ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
2080 E = Method->param_end();
2081 ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
2082 for (; ParamI != E; ++ParamI, ++PrevI) {
2083 // Number of parameters are the same and is guaranteed by selector match.
2084 assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
2085 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
2086 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
2087 // If type of argument of method in this class does not match its
2088 // respective argument type in the super class method, issue warning;
2089 if (!Context.typesAreCompatible(T1, T2)) {
2090 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
2092 Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
2100 /// DiagnoseDuplicateIvars -
2101 /// Check for duplicate ivars in the entire class at the start of
2102 /// @implementation. This becomes necesssary because class extension can
2103 /// add ivars to a class in random order which will not be known until
2104 /// class's @implementation is seen.
2105 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2106 ObjCInterfaceDecl *SID) {
2107 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
2108 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
2109 ObjCIvarDecl* Ivar = (*IVI);
2110 if (Ivar->isInvalidDecl())
2112 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2113 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2115 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2116 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2117 Ivar->setInvalidDecl();
2123 // Note: For class/category implemenations, allMethods/allProperties is
2125 void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
2126 Decl **allMethods, unsigned allNum,
2127 Decl **allProperties, unsigned pNum,
2128 DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
2130 if (!CurContext->isObjCContainer())
2132 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2133 Decl *ClassDecl = cast<Decl>(OCD);
2135 bool isInterfaceDeclKind =
2136 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2137 || isa<ObjCProtocolDecl>(ClassDecl);
2138 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2140 if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
2141 // FIXME: This is wrong. We shouldn't be pretending that there is
2142 // an '@end' in the declaration.
2143 SourceLocation L = ClassDecl->getLocation();
2146 Diag(L, diag::err_missing_atend);
2149 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2150 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2151 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2153 for (unsigned i = 0; i < allNum; i++ ) {
2154 ObjCMethodDecl *Method =
2155 cast_or_null<ObjCMethodDecl>(allMethods[i]);
2157 if (!Method) continue; // Already issued a diagnostic.
2158 if (Method->isInstanceMethod()) {
2159 /// Check for instance method of the same name with incompatible types
2160 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2161 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2163 if ((isInterfaceDeclKind && PrevMethod && !match)
2164 || (checkIdenticalMethods && match)) {
2165 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2166 << Method->getDeclName();
2167 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2168 Method->setInvalidDecl();
2171 Method->setAsRedeclaration(PrevMethod);
2172 InsMap[Method->getSelector()] = Method;
2173 /// The following allows us to typecheck messages to "id".
2174 AddInstanceMethodToGlobalPool(Method);
2175 // verify that the instance method conforms to the same definition of
2176 // parent methods if it shadows one.
2177 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
2180 /// Check for class method of the same name with incompatible types
2181 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2182 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2184 if ((isInterfaceDeclKind && PrevMethod && !match)
2185 || (checkIdenticalMethods && match)) {
2186 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2187 << Method->getDeclName();
2188 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2189 Method->setInvalidDecl();
2192 Method->setAsRedeclaration(PrevMethod);
2193 ClsMap[Method->getSelector()] = Method;
2194 /// The following allows us to typecheck messages to "Class".
2195 AddFactoryMethodToGlobalPool(Method);
2196 // verify that the class method conforms to the same definition of
2197 // parent methods if it shadows one.
2198 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
2202 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
2203 // Compares properties declared in this class to those of its
2205 ComparePropertiesInBaseAndSuper(I);
2206 CompareProperties(I, I);
2207 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2208 // Categories are used to extend the class by declaring new methods.
2209 // By the same token, they are also used to add new properties. No
2210 // need to compare the added property to those in the class.
2212 // Compare protocol properties with those in category
2213 CompareProperties(C, C);
2214 if (C->IsClassExtension()) {
2215 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2216 DiagnoseClassExtensionDupMethods(C, CCPrimary);
2219 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2220 if (CDecl->getIdentifier())
2221 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2222 // user-defined setter/getter. It also synthesizes setter/getter methods
2223 // and adds them to the DeclContext and global method pools.
2224 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
2225 E = CDecl->prop_end();
2227 ProcessPropertyDecl(*I, CDecl);
2228 CDecl->setAtEndRange(AtEnd);
2230 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2231 IC->setAtEndRange(AtEnd);
2232 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2233 // Any property declared in a class extension might have user
2234 // declared setter or getter in current class extension or one
2235 // of the other class extensions. Mark them as synthesized as
2236 // property will be synthesized when property with same name is
2237 // seen in the @implementation.
2238 for (const ObjCCategoryDecl *ClsExtDecl =
2239 IDecl->getFirstClassExtension();
2240 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
2241 for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
2242 E = ClsExtDecl->prop_end(); I != E; ++I) {
2243 ObjCPropertyDecl *Property = (*I);
2244 // Skip over properties declared @dynamic
2245 if (const ObjCPropertyImplDecl *PIDecl
2246 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2247 if (PIDecl->getPropertyImplementation()
2248 == ObjCPropertyImplDecl::Dynamic)
2251 for (const ObjCCategoryDecl *CExtDecl =
2252 IDecl->getFirstClassExtension();
2253 CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
2254 if (ObjCMethodDecl *GetterMethod =
2255 CExtDecl->getInstanceMethod(Property->getGetterName()))
2256 GetterMethod->setSynthesized(true);
2257 if (!Property->isReadOnly())
2258 if (ObjCMethodDecl *SetterMethod =
2259 CExtDecl->getInstanceMethod(Property->getSetterName()))
2260 SetterMethod->setSynthesized(true);
2264 ImplMethodsVsClassMethods(S, IC, IDecl);
2265 AtomicPropertySetterGetterRules(IC, IDecl);
2266 DiagnoseOwningPropertyGetterSynthesis(IC);
2268 if (LangOpts.ObjCNonFragileABI2)
2269 while (IDecl->getSuperClass()) {
2270 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2271 IDecl = IDecl->getSuperClass();
2274 SetIvarInitializers(IC);
2275 } else if (ObjCCategoryImplDecl* CatImplClass =
2276 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2277 CatImplClass->setAtEndRange(AtEnd);
2279 // Find category interface decl and then check that all methods declared
2280 // in this interface are implemented in the category @implementation.
2281 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2282 for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
2283 Categories; Categories = Categories->getNextClassCategory()) {
2284 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
2285 ImplMethodsVsClassMethods(S, CatImplClass, Categories);
2291 if (isInterfaceDeclKind) {
2292 // Reject invalid vardecls.
2293 for (unsigned i = 0; i != tuvNum; i++) {
2294 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
2295 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2296 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2297 if (!VDecl->hasExternalStorage())
2298 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2302 ActOnObjCContainerFinishDefinition();
2306 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2307 /// objective-c's type qualifier from the parser version of the same info.
2308 static Decl::ObjCDeclQualifier
2309 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2310 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2314 bool containsInvalidMethodImplAttribute(const AttrVec &A) {
2315 // The 'ibaction' attribute is allowed on method definitions because of
2316 // how the IBAction macro is used on both method declarations and definitions.
2317 // If the method definitions contains any other attributes, return true.
2318 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
2319 if ((*i)->getKind() != attr::IBAction)
2325 /// \brief Describes the compatibility of a result type with its method.
2326 enum ResultTypeCompatibilityKind {
2333 /// \brief Check whether the declared result type of the given Objective-C
2334 /// method declaration is compatible with the method's class.
2336 static ResultTypeCompatibilityKind
2337 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2338 ObjCInterfaceDecl *CurrentClass) {
2339 QualType ResultType = Method->getResultType();
2341 // If an Objective-C method inherits its related result type, then its
2342 // declared result type must be compatible with its own class type. The
2343 // declared result type is compatible if:
2344 if (const ObjCObjectPointerType *ResultObjectType
2345 = ResultType->getAs<ObjCObjectPointerType>()) {
2346 // - it is id or qualified id, or
2347 if (ResultObjectType->isObjCIdType() ||
2348 ResultObjectType->isObjCQualifiedIdType())
2349 return RTC_Compatible;
2352 if (ObjCInterfaceDecl *ResultClass
2353 = ResultObjectType->getInterfaceDecl()) {
2354 // - it is the same as the method's class type, or
2355 if (CurrentClass == ResultClass)
2356 return RTC_Compatible;
2358 // - it is a superclass of the method's class type
2359 if (ResultClass->isSuperClassOf(CurrentClass))
2360 return RTC_Compatible;
2363 // Any Objective-C pointer type might be acceptable for a protocol
2364 // method; we just don't know.
2369 return RTC_Incompatible;
2373 /// A helper class for searching for methods which a particular method
2375 class OverrideSearch {
2377 ObjCMethodDecl *Method;
2378 llvm::SmallPtrSet<ObjCContainerDecl*, 8> Searched;
2379 llvm::SmallPtrSet<ObjCMethodDecl*, 8> Overridden;
2383 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2384 Selector selector = method->getSelector();
2386 // Bypass this search if we've never seen an instance/class method
2387 // with this selector before.
2388 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2389 if (it == S.MethodPool.end()) {
2390 if (!S.ExternalSource) return;
2391 it = S.ReadMethodPool(selector);
2393 ObjCMethodList &list =
2394 method->isInstanceMethod() ? it->second.first : it->second.second;
2395 if (!list.Method) return;
2397 ObjCContainerDecl *container
2398 = cast<ObjCContainerDecl>(method->getDeclContext());
2400 // Prevent the search from reaching this container again. This is
2401 // important with categories, which override methods from the
2402 // interface and each other.
2403 Searched.insert(container);
2404 searchFromContainer(container);
2407 typedef llvm::SmallPtrSet<ObjCMethodDecl*,8>::iterator iterator;
2408 iterator begin() const { return Overridden.begin(); }
2409 iterator end() const { return Overridden.end(); }
2412 void searchFromContainer(ObjCContainerDecl *container) {
2413 if (container->isInvalidDecl()) return;
2415 switch (container->getDeclKind()) {
2416 #define OBJCCONTAINER(type, base) \
2418 searchFrom(cast<type##Decl>(container)); \
2420 #define ABSTRACT_DECL(expansion)
2421 #define DECL(type, base) \
2423 #include "clang/AST/DeclNodes.inc"
2424 llvm_unreachable("not an ObjC container!");
2428 void searchFrom(ObjCProtocolDecl *protocol) {
2429 // A method in a protocol declaration overrides declarations from
2430 // referenced ("parent") protocols.
2431 search(protocol->getReferencedProtocols());
2434 void searchFrom(ObjCCategoryDecl *category) {
2435 // A method in a category declaration overrides declarations from
2436 // the main class and from protocols the category references.
2437 search(category->getClassInterface());
2438 search(category->getReferencedProtocols());
2441 void searchFrom(ObjCCategoryImplDecl *impl) {
2442 // A method in a category definition that has a category
2443 // declaration overrides declarations from the category
2445 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2448 // Otherwise it overrides declarations from the class.
2450 search(impl->getClassInterface());
2454 void searchFrom(ObjCInterfaceDecl *iface) {
2455 // A method in a class declaration overrides declarations from
2458 for (ObjCCategoryDecl *category = iface->getCategoryList();
2459 category; category = category->getNextClassCategory())
2462 // - the super class, and
2463 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2466 // - any referenced protocols.
2467 search(iface->getReferencedProtocols());
2470 void searchFrom(ObjCImplementationDecl *impl) {
2471 // A method in a class implementation overrides declarations from
2472 // the class interface.
2473 search(impl->getClassInterface());
2477 void search(const ObjCProtocolList &protocols) {
2478 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2483 void search(ObjCContainerDecl *container) {
2484 // Abort if we've already searched this container.
2485 if (!Searched.insert(container)) return;
2487 // Check for a method in this container which matches this selector.
2488 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2489 Method->isInstanceMethod());
2491 // If we find one, record it and bail out.
2493 Overridden.insert(meth);
2497 // Otherwise, search for methods that a hypothetical method here
2498 // would have overridden.
2500 // Note that we're now in a recursive case.
2503 searchFromContainer(container);
2508 Decl *Sema::ActOnMethodDeclaration(
2510 SourceLocation MethodLoc, SourceLocation EndLoc,
2511 tok::TokenKind MethodType,
2512 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
2513 ArrayRef<SourceLocation> SelectorLocs,
2515 // optional arguments. The number of types/arguments is obtained
2516 // from the Sel.getNumArgs().
2517 ObjCArgInfo *ArgInfo,
2518 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
2519 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
2520 bool isVariadic, bool MethodDefinition) {
2521 // Make sure we can establish a context for the method.
2522 if (!CurContext->isObjCContainer()) {
2523 Diag(MethodLoc, diag::error_missing_method_context);
2526 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2527 Decl *ClassDecl = cast<Decl>(OCD);
2528 QualType resultDeclType;
2530 bool HasRelatedResultType = false;
2531 TypeSourceInfo *ResultTInfo = 0;
2533 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
2535 // Methods cannot return interface types. All ObjC objects are
2536 // passed by reference.
2537 if (resultDeclType->isObjCObjectType()) {
2538 Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
2539 << 0 << resultDeclType;
2543 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
2544 } else { // get the type for "id".
2545 resultDeclType = Context.getObjCIdType();
2546 Diag(MethodLoc, diag::warn_missing_method_return_type)
2547 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
2550 ObjCMethodDecl* ObjCMethod =
2551 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel,
2555 MethodType == tok::minus, isVariadic,
2556 /*isSynthesized=*/false,
2557 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
2558 MethodDeclKind == tok::objc_optional
2559 ? ObjCMethodDecl::Optional
2560 : ObjCMethodDecl::Required,
2561 HasRelatedResultType);
2563 SmallVector<ParmVarDecl*, 16> Params;
2565 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
2569 if (ArgInfo[i].Type == 0) {
2570 ArgType = Context.getObjCIdType();
2573 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
2574 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2575 ArgType = Context.getAdjustedParameterType(ArgType);
2578 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
2579 LookupOrdinaryName, ForRedeclaration);
2581 if (R.isSingleResult()) {
2582 NamedDecl *PrevDecl = R.getFoundDecl();
2583 if (S->isDeclScope(PrevDecl)) {
2584 Diag(ArgInfo[i].NameLoc,
2585 (MethodDefinition ? diag::warn_method_param_redefinition
2586 : diag::warn_method_param_declaration))
2588 Diag(PrevDecl->getLocation(),
2589 diag::note_previous_declaration);
2593 SourceLocation StartLoc = DI
2594 ? DI->getTypeLoc().getBeginLoc()
2595 : ArgInfo[i].NameLoc;
2597 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
2598 ArgInfo[i].NameLoc, ArgInfo[i].Name,
2599 ArgType, DI, SC_None, SC_None);
2601 Param->setObjCMethodScopeInfo(i);
2603 Param->setObjCDeclQualifier(
2604 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
2606 // Apply the attributes to the parameter.
2607 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
2610 IdResolver.AddDecl(Param);
2612 Params.push_back(Param);
2615 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
2616 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
2617 QualType ArgType = Param->getType();
2618 if (ArgType.isNull())
2619 ArgType = Context.getObjCIdType();
2621 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
2622 ArgType = Context.getAdjustedParameterType(ArgType);
2623 if (ArgType->isObjCObjectType()) {
2624 Diag(Param->getLocation(),
2625 diag::err_object_cannot_be_passed_returned_by_value)
2627 Param->setInvalidDecl();
2629 Param->setDeclContext(ObjCMethod);
2631 Params.push_back(Param);
2634 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
2635 ObjCMethod->setObjCDeclQualifier(
2636 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
2639 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
2641 // Add the method now.
2642 const ObjCMethodDecl *PrevMethod = 0;
2643 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
2644 if (MethodType == tok::minus) {
2645 PrevMethod = ImpDecl->getInstanceMethod(Sel);
2646 ImpDecl->addInstanceMethod(ObjCMethod);
2648 PrevMethod = ImpDecl->getClassMethod(Sel);
2649 ImpDecl->addClassMethod(ObjCMethod);
2652 if (ObjCMethod->hasAttrs() &&
2653 containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
2654 Diag(EndLoc, diag::warn_attribute_method_def);
2656 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
2660 // You can never have two method definitions with the same name.
2661 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
2662 << ObjCMethod->getDeclName();
2663 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2666 // If this Objective-C method does not have a related result type, but we
2667 // are allowed to infer related result types, try to do so based on the
2669 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
2670 if (!CurrentClass) {
2671 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
2672 CurrentClass = Cat->getClassInterface();
2673 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
2674 CurrentClass = Impl->getClassInterface();
2675 else if (ObjCCategoryImplDecl *CatImpl
2676 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
2677 CurrentClass = CatImpl->getClassInterface();
2680 ResultTypeCompatibilityKind RTC
2681 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
2683 // Search for overridden methods and merge information down from them.
2684 OverrideSearch overrides(*this, ObjCMethod);
2685 for (OverrideSearch::iterator
2686 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2687 ObjCMethodDecl *overridden = *i;
2689 // Propagate down the 'related result type' bit from overridden methods.
2690 if (RTC != RTC_Incompatible && overridden->hasRelatedResultType())
2691 ObjCMethod->SetRelatedResultType();
2693 // Then merge the declarations.
2694 mergeObjCMethodDecls(ObjCMethod, overridden);
2696 // Check for overriding methods
2697 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
2698 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
2699 CheckConflictingOverridingMethod(ObjCMethod, overridden,
2700 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
2703 bool ARCError = false;
2704 if (getLangOptions().ObjCAutoRefCount)
2705 ARCError = CheckARCMethodDecl(*this, ObjCMethod);
2707 // Infer the related result type when possible.
2708 if (!ARCError && RTC == RTC_Compatible &&
2709 !ObjCMethod->hasRelatedResultType() &&
2710 LangOpts.ObjCInferRelatedResultType) {
2711 bool InferRelatedResultType = false;
2712 switch (ObjCMethod->getMethodFamily()) {
2717 case OMF_mutableCopy:
2719 case OMF_retainCount:
2720 case OMF_performSelector:
2725 InferRelatedResultType = ObjCMethod->isClassMethod();
2729 case OMF_autorelease:
2732 InferRelatedResultType = ObjCMethod->isInstanceMethod();
2736 if (InferRelatedResultType)
2737 ObjCMethod->SetRelatedResultType();
2743 bool Sema::CheckObjCDeclScope(Decl *D) {
2744 if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
2746 // Following is also an error. But it is caused by a missing @end
2747 // and diagnostic is issued elsewhere.
2748 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext())) {
2752 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
2753 D->setInvalidDecl();
2758 /// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2759 /// instance variables of ClassName into Decls.
2760 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
2761 IdentifierInfo *ClassName,
2762 SmallVectorImpl<Decl*> &Decls) {
2763 // Check that ClassName is a valid class
2764 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
2766 Diag(DeclStart, diag::err_undef_interface) << ClassName;
2769 if (LangOpts.ObjCNonFragileABI) {
2770 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
2774 // Collect the instance variables
2775 SmallVector<const ObjCIvarDecl*, 32> Ivars;
2776 Context.DeepCollectObjCIvars(Class, true, Ivars);
2777 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2778 for (unsigned i = 0; i < Ivars.size(); i++) {
2779 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
2780 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
2781 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
2782 /*FIXME: StartL=*/ID->getLocation(),
2784 ID->getIdentifier(), ID->getType(),
2786 Decls.push_back(FD);
2789 // Introduce all of these fields into the appropriate scope.
2790 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
2791 D != Decls.end(); ++D) {
2792 FieldDecl *FD = cast<FieldDecl>(*D);
2793 if (getLangOptions().CPlusPlus)
2794 PushOnScopeChains(cast<FieldDecl>(FD), S);
2795 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
2796 Record->addDecl(FD);
2800 /// \brief Build a type-check a new Objective-C exception variable declaration.
2801 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
2802 SourceLocation StartLoc,
2803 SourceLocation IdLoc,
2806 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
2807 // duration shall not be qualified by an address-space qualifier."
2808 // Since all parameters have automatic store duration, they can not have
2809 // an address space.
2810 if (T.getAddressSpace() != 0) {
2811 Diag(IdLoc, diag::err_arg_with_address_space);
2815 // An @catch parameter must be an unqualified object pointer type;
2816 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
2818 // Don't do any further checking.
2819 } else if (T->isDependentType()) {
2820 // Okay: we don't know what this type will instantiate to.
2821 } else if (!T->isObjCObjectPointerType()) {
2823 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
2824 } else if (T->isObjCQualifiedIdType()) {
2826 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
2829 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
2830 T, TInfo, SC_None, SC_None);
2831 New->setExceptionVariable(true);
2834 New->setInvalidDecl();
2838 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
2839 const DeclSpec &DS = D.getDeclSpec();
2841 // We allow the "register" storage class on exception variables because
2842 // GCC did, but we drop it completely. Any other storage class is an error.
2843 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2844 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
2845 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
2846 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
2847 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
2848 << DS.getStorageClassSpec();
2850 if (D.getDeclSpec().isThreadSpecified())
2851 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
2852 D.getMutableDeclSpec().ClearStorageClassSpecs();
2854 DiagnoseFunctionSpecifiers(D);
2856 // Check that there are no default arguments inside the type of this
2857 // exception object (C++ only).
2858 if (getLangOptions().CPlusPlus)
2859 CheckExtraCXXDefaultArguments(D);
2861 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
2862 QualType ExceptionType = TInfo->getType();
2864 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
2865 D.getSourceRange().getBegin(),
2866 D.getIdentifierLoc(),
2870 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2871 if (D.getCXXScopeSpec().isSet()) {
2872 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
2873 << D.getCXXScopeSpec().getRange();
2874 New->setInvalidDecl();
2877 // Add the parameter declaration into this scope.
2879 if (D.getIdentifier())
2880 IdResolver.AddDecl(New);
2882 ProcessDeclAttributes(S, New, D);
2884 if (New->hasAttr<BlocksAttr>())
2885 Diag(New->getLocation(), diag::err_block_on_nonlocal);
2889 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2891 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2892 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
2893 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
2894 Iv= Iv->getNextIvar()) {
2895 QualType QT = Context.getBaseElementType(Iv->getType());
2896 if (QT->isRecordType())
2897 Ivars.push_back(Iv);
2901 void Sema::DiagnoseUseOfUnimplementedSelectors() {
2902 // Load referenced selectors from the external source.
2903 if (ExternalSource) {
2904 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
2905 ExternalSource->ReadReferencedSelectors(Sels);
2906 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
2907 ReferencedSelectors[Sels[I].first] = Sels[I].second;
2910 // Warning will be issued only when selector table is
2911 // generated (which means there is at lease one implementation
2912 // in the TU). This is to match gcc's behavior.
2913 if (ReferencedSelectors.empty() ||
2914 !Context.AnyObjCImplementation())
2916 for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
2917 ReferencedSelectors.begin(),
2918 E = ReferencedSelectors.end(); S != E; ++S) {
2919 Selector Sel = (*S).first;
2920 if (!LookupImplementedMethodInGlobalPool(Sel))
2921 Diag((*S).second, diag::warn_unimplemented_selector) << Sel;