#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/DataRecursiveASTVisitor.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Preprocessor.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/ExternalSemaSource.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "llvm/ADT/DenseSet.h"
using namespace clang;
bool Sema::checkInitMethod(ObjCMethodDecl *method,
QualType receiverTypeIfCall) {
if (method->isInvalidDecl()) return true;
const ObjCObjectType *result =
method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
if (result->isObjCId()) {
return false;
} else if (result->isObjCClass()) {
} else {
ObjCInterfaceDecl *resultClass = result->getInterface();
assert(resultClass && "unexpected object type!");
if (!resultClass->hasDefinition()) {
if (receiverTypeIfCall.isNull() &&
!isa<ObjCImplementationDecl>(method->getDeclContext()))
return false;
} else {
const ObjCInterfaceDecl *receiverClass = 0;
if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
if (receiverTypeIfCall.isNull())
return false;
receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
->getInterfaceDecl();
if (!receiverClass) return false;
} else {
receiverClass = method->getClassInterface();
assert(receiverClass && "method not associated with a class!");
}
if (receiverClass->isSuperClassOf(resultClass) ||
resultClass->isSuperClassOf(receiverClass))
return false;
}
}
SourceLocation loc = method->getLocation();
if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
method->addAttr(UnavailableAttr::CreateImplicit(Context,
"init method returns a type unrelated to its receiver type",
loc));
return true;
}
Diag(loc, diag::err_arc_init_method_unrelated_result_type);
method->setInvalidDecl();
return true;
}
void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden) {
if (Overridden->hasRelatedResultType() &&
!NewMethod->hasRelatedResultType()) {
QualType ResultType = NewMethod->getReturnType();
SourceRange ResultTypeRange;
if (const TypeSourceInfo *ResultTypeInfo =
NewMethod->getReturnTypeSourceInfo())
ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
ObjCInterfaceDecl *CurrentClass
= dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
if (!CurrentClass) {
DeclContext *DC = NewMethod->getDeclContext();
if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
CurrentClass = Cat->getClassInterface();
else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
CurrentClass = Impl->getClassInterface();
else if (ObjCCategoryImplDecl *CatImpl
= dyn_cast<ObjCCategoryImplDecl>(DC))
CurrentClass = CatImpl->getClassInterface();
}
if (CurrentClass) {
Diag(NewMethod->getLocation(),
diag::warn_related_result_type_compatibility_class)
<< Context.getObjCInterfaceType(CurrentClass)
<< ResultType
<< ResultTypeRange;
} else {
Diag(NewMethod->getLocation(),
diag::warn_related_result_type_compatibility_protocol)
<< ResultType
<< ResultTypeRange;
}
if (ObjCMethodFamily Family = Overridden->getMethodFamily())
Diag(Overridden->getLocation(),
diag::note_related_result_type_family)
<< 0
<< Family;
else
Diag(Overridden->getLocation(),
diag::note_related_result_type_overridden);
}
if (getLangOpts().ObjCAutoRefCount) {
if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
Overridden->hasAttr<NSReturnsRetainedAttr>())) {
Diag(NewMethod->getLocation(),
diag::err_nsreturns_retained_attribute_mismatch) << 1;
Diag(Overridden->getLocation(), diag::note_previous_decl)
<< "method";
}
if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
Diag(NewMethod->getLocation(),
diag::err_nsreturns_retained_attribute_mismatch) << 0;
Diag(Overridden->getLocation(), diag::note_previous_decl)
<< "method";
}
ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
oe = Overridden->param_end();
for (ObjCMethodDecl::param_iterator
ni = NewMethod->param_begin(), ne = NewMethod->param_end();
ni != ne && oi != oe; ++ni, ++oi) {
const ParmVarDecl *oldDecl = (*oi);
ParmVarDecl *newDecl = (*ni);
if (newDecl->hasAttr<NSConsumedAttr>() !=
oldDecl->hasAttr<NSConsumedAttr>()) {
Diag(newDecl->getLocation(),
diag::err_nsconsumed_attribute_mismatch);
Diag(oldDecl->getLocation(), diag::note_previous_decl)
<< "parameter";
}
}
}
}
bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
ObjCMethodFamily family = method->getMethodFamily();
switch (family) {
case OMF_None:
case OMF_finalize:
case OMF_retain:
case OMF_release:
case OMF_autorelease:
case OMF_retainCount:
case OMF_self:
case OMF_performSelector:
return false;
case OMF_dealloc:
if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
SourceRange ResultTypeRange;
if (const TypeSourceInfo *ResultTypeInfo =
method->getReturnTypeSourceInfo())
ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
if (ResultTypeRange.isInvalid())
Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
<< method->getReturnType()
<< FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
else
Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
<< method->getReturnType()
<< FixItHint::CreateReplacement(ResultTypeRange, "void");
return true;
}
return false;
case OMF_init:
if (checkInitMethod(method, QualType()))
return true;
method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
if (method->hasAttr<NSReturnsRetainedAttr>())
return false;
break;
case OMF_alloc:
case OMF_copy:
case OMF_mutableCopy:
case OMF_new:
if (method->hasAttr<NSReturnsRetainedAttr>() ||
method->hasAttr<NSReturnsNotRetainedAttr>() ||
method->hasAttr<NSReturnsAutoreleasedAttr>())
return false;
break;
}
method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
return false;
}
static void DiagnoseObjCImplementedDeprecations(Sema &S,
NamedDecl *ND,
SourceLocation ImplLoc,
int select) {
if (ND && ND->isDeprecated()) {
S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
if (select == 0)
S.Diag(ND->getLocation(), diag::note_method_declared_at)
<< ND->getDeclName();
else
S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
}
}
void Sema::AddAnyMethodToGlobalPool(Decl *D) {
ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
if (!MDecl)
return;
if (MDecl->isInstanceMethod())
AddInstanceMethodToGlobalPool(MDecl, true);
else
AddFactoryMethodToGlobalPool(MDecl, true);
}
static bool
HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
QualType T = Param->getType();
if (const PointerType *PT = T->getAs<PointerType>()) {
T = PT->getPointeeType();
} else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
T = RT->getPointeeType();
} else {
return true;
}
return !T.getLocalQualifiers().hasObjCLifetime();
}
void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
assert((getCurMethodDecl() == 0) && "Methodparsing confused");
ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
if (!MDecl)
return;
PushDeclContext(FnBodyScope, MDecl);
PushFunctionScope();
MDecl->createImplicitParams(Context, MDecl->getClassInterface());
PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
false);
for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
E = MDecl->param_end(); PI != E; ++PI) {
ParmVarDecl *Param = (*PI);
if (!Param->isInvalidDecl() &&
getLangOpts().ObjCAutoRefCount &&
!HasExplicitOwnershipAttr(*this, Param))
Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
Param->getType();
if ((*PI)->getIdentifier())
PushOnScopeChains(*PI, FnBodyScope);
}
if (getLangOpts().ObjCAutoRefCount) {
switch (MDecl->getMethodFamily()) {
case OMF_retain:
case OMF_retainCount:
case OMF_release:
case OMF_autorelease:
Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
<< 0 << MDecl->getSelector();
break;
case OMF_None:
case OMF_dealloc:
case OMF_finalize:
case OMF_alloc:
case OMF_init:
case OMF_mutableCopy:
case OMF_copy:
case OMF_new:
case OMF_self:
case OMF_performSelector:
break;
}
}
if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
ObjCMethodDecl *IMD =
IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
if (IMD) {
ObjCImplDecl *ImplDeclOfMethodDef =
dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
ObjCContainerDecl *ContDeclOfMethodDecl =
dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
ObjCImplDecl *ImplDeclOfMethodDecl = 0;
if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
ImplDeclOfMethodDecl = OID->getImplementation();
else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
if (CD->IsClassExtension()) {
if (ObjCInterfaceDecl *OID = CD->getClassInterface())
ImplDeclOfMethodDecl = OID->getImplementation();
} else
ImplDeclOfMethodDecl = CD->getImplementation();
}
if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
DiagnoseObjCImplementedDeprecations(*this,
dyn_cast<NamedDecl>(IMD),
MDecl->getLocation(), 0);
}
if (MDecl->getMethodFamily() == OMF_init) {
if (MDecl->isDesignatedInitializerForTheInterface()) {
getCurFunction()->ObjCIsDesignatedInit = true;
getCurFunction()->ObjCWarnForNoDesignatedInitChain =
IC->getSuperClass() != 0;
} else if (IC->hasDesignatedInitializers()) {
getCurFunction()->ObjCIsSecondaryInit = true;
getCurFunction()->ObjCWarnForNoInitDelegation = true;
}
}
if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
ObjCMethodFamily Family = MDecl->getMethodFamily();
if (Family == OMF_dealloc) {
if (!(getLangOpts().ObjCAutoRefCount ||
getLangOpts().getGC() == LangOptions::GCOnly))
getCurFunction()->ObjCShouldCallSuper = true;
} else if (Family == OMF_finalize) {
if (Context.getLangOpts().getGC() != LangOptions::NonGC)
getCurFunction()->ObjCShouldCallSuper = true;
} else {
const ObjCMethodDecl *SuperMethod =
SuperClass->lookupMethod(MDecl->getSelector(),
MDecl->isInstanceMethod());
getCurFunction()->ObjCShouldCallSuper =
(SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
}
}
}
}
namespace {
class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
public:
ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {}
explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
: CurrentIDecl(IDecl) {}
virtual bool ValidateCandidate(const TypoCorrection &candidate) {
ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
return ID && !declaresSameEntity(ID, CurrentIDecl);
}
private:
ObjCInterfaceDecl *CurrentIDecl;
};
}
Decl *Sema::
ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *SuperName, SourceLocation SuperLoc,
Decl * const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc, AttributeList *AttrList) {
assert(ClassName && "Missing class identifier");
NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
LookupOrdinaryName, ForRedeclaration);
if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
}
ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
ClassName = PrevIDecl->getIdentifier();
}
ObjCInterfaceDecl *IDecl
= ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
PrevIDecl, ClassLoc);
if (PrevIDecl) {
if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
<< PrevIDecl->getDeclName();
Diag(Def->getLocation(), diag::note_previous_definition);
IDecl->setInvalidDecl();
}
}
if (AttrList)
ProcessDeclAttributeList(TUScope, IDecl, AttrList);
PushOnScopeChains(IDecl, TUScope);
if (!IDecl->hasDefinition())
IDecl->startDefinition();
if (SuperName) {
PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
LookupOrdinaryName);
if (!PrevDecl) {
ObjCInterfaceValidatorCCC Validator(IDecl);
if (TypoCorrection Corrected = CorrectTypo(
DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
NULL, Validator)) {
diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
<< SuperName << ClassName);
PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
}
}
if (declaresSameEntity(PrevDecl, IDecl)) {
Diag(SuperLoc, diag::err_recursive_superclass)
<< SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
IDecl->setEndOfDefinitionLoc(ClassLoc);
} else {
ObjCInterfaceDecl *SuperClassDecl =
dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
if (SuperClassDecl)
(void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
if (PrevDecl && SuperClassDecl == 0) {
if (const TypedefNameDecl *TDecl =
dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
QualType T = TDecl->getUnderlyingType();
if (T->isObjCObjectType()) {
if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
(void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
}
}
}
if (!SuperClassDecl) {
Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
}
}
if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
if (!SuperClassDecl)
Diag(SuperLoc, diag::err_undef_superclass)
<< SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
else if (RequireCompleteType(SuperLoc,
Context.getObjCInterfaceType(SuperClassDecl),
diag::err_forward_superclass,
SuperClassDecl->getDeclName(),
ClassName,
SourceRange(AtInterfaceLoc, ClassLoc))) {
SuperClassDecl = 0;
}
}
IDecl->setSuperClass(SuperClassDecl);
IDecl->setSuperClassLoc(SuperLoc);
IDecl->setEndOfDefinitionLoc(SuperLoc);
}
} else { IDecl->setEndOfDefinitionLoc(ClassLoc);
}
if (NumProtoRefs) {
IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
ProtoLocs, Context);
IDecl->setEndOfDefinitionLoc(EndProtoLoc);
}
CheckObjCDeclScope(IDecl);
return ActOnObjCContainerStartDefinition(IDecl);
}
void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
IdentifierInfo *SuperName,
SourceLocation SuperLoc) {
if (!SuperName)
return;
NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
LookupOrdinaryName);
if (!IDecl)
return;
if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
QualType T = TDecl->getUnderlyingType();
if (T->isObjCObjectType())
if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
for (ObjCObjectType::qual_iterator I = OPT->qual_begin(),
E = OPT->qual_end(); I != E; ++I)
ProtocolRefs.push_back(*I);
}
}
Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
IdentifierInfo *AliasName,
SourceLocation AliasLocation,
IdentifierInfo *ClassName,
SourceLocation ClassLocation) {
NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
LookupOrdinaryName, ForRedeclaration);
if (ADecl) {
Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Diag(ADecl->getLocation(), diag::note_previous_declaration);
return 0;
}
NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
LookupOrdinaryName, ForRedeclaration);
if (const TypedefNameDecl *TDecl =
dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
QualType T = TDecl->getUnderlyingType();
if (T->isObjCObjectType()) {
if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
ClassName = IDecl->getIdentifier();
CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
LookupOrdinaryName, ForRedeclaration);
}
}
}
ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
if (CDecl == 0) {
Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
if (CDeclU)
Diag(CDeclU->getLocation(), diag::note_previous_declaration);
return 0;
}
ObjCCompatibleAliasDecl *AliasDecl =
ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
if (!CheckObjCDeclScope(AliasDecl))
PushOnScopeChains(AliasDecl, TUScope);
return AliasDecl;
}
bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
IdentifierInfo *PName,
SourceLocation &Ploc, SourceLocation PrevLoc,
const ObjCList<ObjCProtocolDecl> &PList) {
bool res = false;
for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
E = PList.end(); I != E; ++I) {
if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
Ploc)) {
if (PDecl->getIdentifier() == PName) {
Diag(Ploc, diag::err_protocol_has_circular_dependency);
Diag(PrevLoc, diag::note_previous_definition);
res = true;
}
if (!PDecl->hasDefinition())
continue;
if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
PDecl->getLocation(), PDecl->getReferencedProtocols()))
res = true;
}
}
return res;
}
Decl *
Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
IdentifierInfo *ProtocolName,
SourceLocation ProtocolLoc,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc,
AttributeList *AttrList) {
bool err = false;
assert(ProtocolName && "Missing protocol identifier");
ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
ForRedeclaration);
ObjCProtocolDecl *PDecl = 0;
if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : 0) {
Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
Diag(Def->getLocation(), diag::note_previous_definition);
PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
ProtocolLoc, AtProtoInterfaceLoc,
0);
PDecl->startDefinition();
} else {
if (PrevDecl) {
ObjCList<ObjCProtocolDecl> PList;
PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
err = CheckForwardProtocolDeclarationForCircularDependency(
ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
}
PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
ProtocolLoc, AtProtoInterfaceLoc,
PrevDecl);
PushOnScopeChains(PDecl, TUScope);
PDecl->startDefinition();
}
if (AttrList)
ProcessDeclAttributeList(TUScope, PDecl, AttrList);
if (PrevDecl)
mergeDeclAttributes(PDecl, PrevDecl);
if (!err && NumProtoRefs ) {
PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
ProtoLocs, Context);
}
CheckObjCDeclScope(PDecl);
return ActOnObjCContainerStartDefinition(PDecl);
}
void
Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
const IdentifierLocPair *ProtocolId,
unsigned NumProtocols,
SmallVectorImpl<Decl *> &Protocols) {
for (unsigned i = 0; i != NumProtocols; ++i) {
ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
ProtocolId[i].second);
if (!PDecl) {
DeclFilterCCC<ObjCProtocolDecl> Validator;
TypoCorrection Corrected = CorrectTypo(
DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
LookupObjCProtocolName, TUScope, NULL, Validator);
if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
<< ProtocolId[i].first);
}
if (!PDecl) {
Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
<< ProtocolId[i].first;
continue;
}
if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
PDecl = PDecl->getDefinition();
(void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
if (WarnOnDeclarations &&
(!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()))
Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
<< ProtocolId[i].first;
Protocols.push_back(PDecl);
}
}
void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID) {
if (!ID)
return;
llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
e = ID->meth_end(); i != e; ++i) {
ObjCMethodDecl *MD = *i;
MethodMap[MD->getSelector()] = MD;
}
if (MethodMap.empty())
return;
for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
e = CAT->meth_end(); i != e; ++i) {
ObjCMethodDecl *Method = *i;
const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
if (PrevMethod &&
(PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
!MatchTwoMethodDeclarations(Method, PrevMethod)) {
Diag(Method->getLocation(), diag::err_duplicate_method_decl)
<< Method->getDeclName();
Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
}
}
}
Sema::DeclGroupPtrTy
Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
const IdentifierLocPair *IdentList,
unsigned NumElts,
AttributeList *attrList) {
SmallVector<Decl *, 8> DeclsInGroup;
for (unsigned i = 0; i != NumElts; ++i) {
IdentifierInfo *Ident = IdentList[i].first;
ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
ForRedeclaration);
ObjCProtocolDecl *PDecl
= ObjCProtocolDecl::Create(Context, CurContext, Ident,
IdentList[i].second, AtProtocolLoc,
PrevDecl);
PushOnScopeChains(PDecl, TUScope);
CheckObjCDeclScope(PDecl);
if (attrList)
ProcessDeclAttributeList(TUScope, PDecl, attrList);
if (PrevDecl)
mergeDeclAttributes(PDecl, PrevDecl);
DeclsInGroup.push_back(PDecl);
}
return BuildDeclaratorGroup(DeclsInGroup, false);
}
Decl *Sema::
ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *CategoryName,
SourceLocation CategoryLoc,
Decl * const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs,
SourceLocation EndProtoLoc) {
ObjCCategoryDecl *CDecl;
ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
if (!IDecl
|| RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
diag::err_category_forward_interface,
CategoryName == 0)) {
CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
ClassLoc, CategoryLoc, CategoryName,IDecl);
CDecl->setInvalidDecl();
CurContext->addDecl(CDecl);
if (!IDecl)
Diag(ClassLoc, diag::err_undef_interface) << ClassName;
return ActOnObjCContainerStartDefinition(CDecl);
}
if (!CategoryName && IDecl->getImplementation()) {
Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
Diag(IDecl->getImplementation()->getLocation(),
diag::note_implementation_declared);
}
if (CategoryName) {
if (ObjCCategoryDecl *Previous
= IDecl->FindCategoryDeclaration(CategoryName)) {
Diag(CategoryLoc, diag::warn_dup_category_def)
<< ClassName << CategoryName;
Diag(Previous->getLocation(), diag::note_previous_definition);
}
}
CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
ClassLoc, CategoryLoc, CategoryName, IDecl);
CurContext->addDecl(CDecl);
if (NumProtoRefs) {
CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
ProtoLocs, Context);
if (CDecl->IsClassExtension())
IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
NumProtoRefs, Context);
}
CheckObjCDeclScope(CDecl);
return ActOnObjCContainerStartDefinition(CDecl);
}
Decl *Sema::ActOnStartCategoryImplementation(
SourceLocation AtCatImplLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *CatName, SourceLocation CatLoc) {
ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
ObjCCategoryDecl *CatIDecl = 0;
if (IDecl && IDecl->hasDefinition()) {
CatIDecl = IDecl->FindCategoryDeclaration(CatName);
if (!CatIDecl) {
CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
ClassLoc, CatLoc,
CatName, IDecl);
CatIDecl->setImplicit();
}
}
ObjCCategoryImplDecl *CDecl =
ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
ClassLoc, AtCatImplLoc, CatLoc);
if (!IDecl) {
Diag(ClassLoc, diag::err_undef_interface) << ClassName;
CDecl->setInvalidDecl();
} else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
diag::err_undef_interface)) {
CDecl->setInvalidDecl();
}
CurContext->addDecl(CDecl);
if (IDecl)
DiagnoseUseOfDecl(IDecl, ClassLoc);
if (CatIDecl) {
if (CatIDecl->getImplementation()) {
Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
<< CatName;
Diag(CatIDecl->getImplementation()->getLocation(),
diag::note_previous_definition);
CDecl->setInvalidDecl();
} else {
CatIDecl->setImplementation(CDecl);
DiagnoseObjCImplementedDeprecations(*this,
dyn_cast<NamedDecl>(IDecl),
CDecl->getLocation(), 2);
}
}
CheckObjCDeclScope(CDecl);
return ActOnObjCContainerStartDefinition(CDecl);
}
Decl *Sema::ActOnStartClassImplementation(
SourceLocation AtClassImplLoc,
IdentifierInfo *ClassName, SourceLocation ClassLoc,
IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc) {
ObjCInterfaceDecl *IDecl = 0;
NamedDecl *PrevDecl
= LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
ForRedeclaration);
if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
} else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
diag::warn_undef_interface);
} else {
ObjCInterfaceValidatorCCC Validator;
TypoCorrection Corrected =
CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
LookupOrdinaryName, TUScope, NULL, Validator);
if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
diagnoseTypo(Corrected,
PDiag(diag::warn_undef_interface_suggest) << ClassName,
false);
} else {
Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
}
}
ObjCInterfaceDecl* SDecl = 0;
if (SuperClassname) {
PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
LookupOrdinaryName);
if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Diag(SuperClassLoc, diag::err_redefinition_different_kind)
<< SuperClassname;
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
} else {
SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
if (SDecl && !SDecl->hasDefinition())
SDecl = 0;
if (!SDecl)
Diag(SuperClassLoc, diag::err_undef_superclass)
<< SuperClassname << ClassName;
else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Diag(SuperClassLoc, diag::err_conflicting_super_class)
<< SDecl->getDeclName();
Diag(SDecl->getLocation(), diag::note_previous_definition);
}
}
}
if (!IDecl) {
IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
ClassName, 0, ClassLoc,
true);
IDecl->startDefinition();
if (SDecl) {
IDecl->setSuperClass(SDecl);
IDecl->setSuperClassLoc(SuperClassLoc);
IDecl->setEndOfDefinitionLoc(SuperClassLoc);
} else {
IDecl->setEndOfDefinitionLoc(ClassLoc);
}
PushOnScopeChains(IDecl, TUScope);
} else {
if (!IDecl->hasDefinition())
IDecl->startDefinition();
}
ObjCImplementationDecl* IMPDecl =
ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
ClassLoc, AtClassImplLoc, SuperClassLoc);
if (CheckObjCDeclScope(IMPDecl))
return ActOnObjCContainerStartDefinition(IMPDecl);
if (IDecl->getImplementation()) {
Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Diag(IDecl->getImplementation()->getLocation(),
diag::note_previous_definition);
IMPDecl->setInvalidDecl();
} else { IDecl->setImplementation(IMPDecl);
PushOnScopeChains(IMPDecl, TUScope);
DiagnoseObjCImplementedDeprecations(*this,
dyn_cast<NamedDecl>(IDecl),
IMPDecl->getLocation(), 1);
}
return ActOnObjCContainerStartDefinition(IMPDecl);
}
Sema::DeclGroupPtrTy
Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
SmallVector<Decl *, 64> DeclsInGroup;
DeclsInGroup.reserve(Decls.size() + 1);
for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
Decl *Dcl = Decls[i];
if (!Dcl)
continue;
if (Dcl->getDeclContext()->isFileContext())
Dcl->setTopLevelDeclInObjCContainer();
DeclsInGroup.push_back(Dcl);
}
DeclsInGroup.push_back(ObjCImpDecl);
return BuildDeclaratorGroup(DeclsInGroup, false);
}
void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
ObjCIvarDecl **ivars, unsigned numIvars,
SourceLocation RBrace) {
assert(ImpDecl && "missing implementation decl");
ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
if (!IDecl)
return;
if (IDecl->isImplicitInterfaceDecl()) {
IDecl->setEndOfDefinitionLoc(RBrace);
for (unsigned i = 0, e = numIvars; i != e; ++i) {
ivars[i]->setLexicalDeclContext(ImpDecl);
IDecl->makeDeclVisibleInContext(ivars[i]);
ImpDecl->addDecl(ivars[i]);
}
return;
}
if (numIvars == 0)
return;
assert(ivars && "missing @implementation ivars");
if (LangOpts.ObjCRuntime.isNonFragile()) {
if (ImpDecl->getSuperClass())
Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
for (unsigned i = 0; i < numIvars; i++) {
ObjCIvarDecl* ImplIvar = ivars[i];
if (const ObjCIvarDecl *ClsIvar =
IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Diag(ClsIvar->getLocation(), diag::note_previous_definition);
continue;
}
for (ObjCInterfaceDecl::visible_extensions_iterator
Ext = IDecl->visible_extensions_begin(),
ExtEnd = IDecl->visible_extensions_end();
Ext != ExtEnd; ++Ext) {
ObjCCategoryDecl *CDecl = *Ext;
if (const ObjCIvarDecl *ClsExtIvar =
CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
continue;
}
}
ImplIvar->setLexicalDeclContext(ImpDecl);
IDecl->makeDeclVisibleInContext(ImplIvar);
ImpDecl->addDecl(ImplIvar);
}
return;
}
unsigned j = 0;
ObjCInterfaceDecl::ivar_iterator
IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
for (; numIvars > 0 && IVI != IVE; ++IVI) {
ObjCIvarDecl* ImplIvar = ivars[j++];
ObjCIvarDecl* ClsIvar = *IVI;
assert (ImplIvar && "missing implementation ivar");
assert (ClsIvar && "missing class ivar");
if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
<< ImplIvar->getIdentifier()
<< ImplIvar->getType() << ClsIvar->getType();
Diag(ClsIvar->getLocation(), diag::note_previous_definition);
} else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
ImplIvar->getBitWidthValue(Context) !=
ClsIvar->getBitWidthValue(Context)) {
Diag(ImplIvar->getBitWidth()->getLocStart(),
diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
Diag(ClsIvar->getBitWidth()->getLocStart(),
diag::note_previous_definition);
}
if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
<< ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Diag(ClsIvar->getLocation(), diag::note_previous_definition);
}
--numIvars;
}
if (numIvars > 0)
Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
else if (IVI != IVE)
Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
}
static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
ObjCMethodDecl *method,
bool &IncompleteImpl,
unsigned DiagID,
NamedDecl *NeededFor = 0) {
switch (method->getAvailability()) {
case AR_Available:
case AR_Deprecated:
break;
case AR_NotYetIntroduced:
case AR_Unavailable:
return;
}
{
const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
B << method;
if (NeededFor)
B << NeededFor;
}
SourceLocation MethodLoc = method->getLocStart();
if (MethodLoc.isValid())
S.Diag(MethodLoc, diag::note_method_declared_at) << method;
}
static bool isObjCTypeSubstitutable(ASTContext &Context,
const ObjCObjectPointerType *A,
const ObjCObjectPointerType *B,
bool rejectId) {
if (rejectId && B->isObjCIdType()) return false;
if (B->isObjCQualifiedIdType()) {
return A->isObjCQualifiedIdType() &&
Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
QualType(B,0),
false);
}
return Context.canAssignObjCInterfaces(A, B);
}
static SourceRange getTypeRange(TypeSourceInfo *TSI) {
return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
}
static bool CheckMethodOverrideReturn(Sema &S,
ObjCMethodDecl *MethodImpl,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl,
bool IsOverridingMode,
bool Warn) {
if (IsProtocolMethodDecl &&
(MethodDecl->getObjCDeclQualifier() !=
MethodImpl->getObjCDeclQualifier())) {
if (Warn) {
S.Diag(MethodImpl->getLocation(),
(IsOverridingMode
? diag::warn_conflicting_overriding_ret_type_modifiers
: diag::warn_conflicting_ret_type_modifiers))
<< MethodImpl->getDeclName()
<< getTypeRange(MethodImpl->getReturnTypeSourceInfo());
S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
<< getTypeRange(MethodDecl->getReturnTypeSourceInfo());
}
else
return false;
}
if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
MethodDecl->getReturnType()))
return true;
if (!Warn)
return false;
unsigned DiagID =
IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
: diag::warn_conflicting_ret_types;
if (const ObjCObjectPointerType *ImplPtrTy =
MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
if (const ObjCObjectPointerType *IfacePtrTy =
MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
return false;
DiagID =
IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
: diag::warn_non_covariant_ret_types;
}
}
S.Diag(MethodImpl->getLocation(), DiagID)
<< MethodImpl->getDeclName() << MethodDecl->getReturnType()
<< MethodImpl->getReturnType()
<< getTypeRange(MethodImpl->getReturnTypeSourceInfo());
S.Diag(MethodDecl->getLocation(), IsOverridingMode
? diag::note_previous_declaration
: diag::note_previous_definition)
<< getTypeRange(MethodDecl->getReturnTypeSourceInfo());
return false;
}
static bool CheckMethodOverrideParam(Sema &S,
ObjCMethodDecl *MethodImpl,
ObjCMethodDecl *MethodDecl,
ParmVarDecl *ImplVar,
ParmVarDecl *IfaceVar,
bool IsProtocolMethodDecl,
bool IsOverridingMode,
bool Warn) {
if (IsProtocolMethodDecl &&
(ImplVar->getObjCDeclQualifier() !=
IfaceVar->getObjCDeclQualifier())) {
if (Warn) {
if (IsOverridingMode)
S.Diag(ImplVar->getLocation(),
diag::warn_conflicting_overriding_param_modifiers)
<< getTypeRange(ImplVar->getTypeSourceInfo())
<< MethodImpl->getDeclName();
else S.Diag(ImplVar->getLocation(),
diag::warn_conflicting_param_modifiers)
<< getTypeRange(ImplVar->getTypeSourceInfo())
<< MethodImpl->getDeclName();
S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
<< getTypeRange(IfaceVar->getTypeSourceInfo());
}
else
return false;
}
QualType ImplTy = ImplVar->getType();
QualType IfaceTy = IfaceVar->getType();
if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
return true;
if (!Warn)
return false;
unsigned DiagID =
IsOverridingMode ? diag::warn_conflicting_overriding_param_types
: diag::warn_conflicting_param_types;
if (const ObjCObjectPointerType *ImplPtrTy =
ImplTy->getAs<ObjCObjectPointerType>()) {
if (const ObjCObjectPointerType *IfacePtrTy =
IfaceTy->getAs<ObjCObjectPointerType>()) {
if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
return false;
DiagID =
IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
: diag::warn_non_contravariant_param_types;
}
}
S.Diag(ImplVar->getLocation(), DiagID)
<< getTypeRange(ImplVar->getTypeSourceInfo())
<< MethodImpl->getDeclName() << IfaceTy << ImplTy;
S.Diag(IfaceVar->getLocation(),
(IsOverridingMode ? diag::note_previous_declaration
: diag::note_previous_definition))
<< getTypeRange(IfaceVar->getTypeSourceInfo());
return false;
}
static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
ObjCMethodDecl *decl) {
ObjCMethodFamily implFamily = impl->getMethodFamily();
ObjCMethodFamily declFamily = decl->getMethodFamily();
if (implFamily == declFamily) return false;
assert(implFamily == OMF_None || declFamily == OMF_None);
if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
const ObjCMethodDecl *unmatched = impl;
ObjCMethodFamily family = declFamily;
unsigned errorID = diag::err_arc_lost_method_convention;
unsigned noteID = diag::note_arc_lost_method_convention;
if (declFamily == OMF_None) {
unmatched = decl;
family = implFamily;
errorID = diag::err_arc_gained_method_convention;
noteID = diag::note_arc_gained_method_convention;
}
enum FamilySelector {
F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
};
FamilySelector familySelector = FamilySelector();
switch (family) {
case OMF_None: llvm_unreachable("logic error, no method convention");
case OMF_retain:
case OMF_release:
case OMF_autorelease:
case OMF_dealloc:
case OMF_finalize:
case OMF_retainCount:
case OMF_self:
case OMF_performSelector:
return false;
case OMF_init: familySelector = F_init; break;
case OMF_alloc: familySelector = F_alloc; break;
case OMF_copy: familySelector = F_copy; break;
case OMF_mutableCopy: familySelector = F_mutableCopy; break;
case OMF_new: familySelector = F_new; break;
}
enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
ReasonSelector reasonSelector;
if (unmatched->getReturnType()->isObjCObjectPointerType()) {
reasonSelector = R_UnrelatedReturn;
} else {
reasonSelector = R_NonObjectReturn;
}
S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
return true;
}
void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl) {
if (getLangOpts().ObjCAutoRefCount &&
checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
return;
CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
IsProtocolMethodDecl, false,
true);
for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
EF = MethodDecl->param_end();
IM != EM && IF != EF; ++IM, ++IF) {
CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
IsProtocolMethodDecl, false, true);
}
if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Diag(ImpMethodDecl->getLocation(),
diag::warn_conflicting_variadic);
Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
}
}
void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
ObjCMethodDecl *Overridden,
bool IsProtocolMethodDecl) {
CheckMethodOverrideReturn(*this, Method, Overridden,
IsProtocolMethodDecl, true,
true);
for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
IF = Overridden->param_begin(), EM = Method->param_end(),
EF = Overridden->param_end();
IM != EM && IF != EF; ++IM, ++IF) {
CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
IsProtocolMethodDecl, true, true);
}
if (Method->isVariadic() != Overridden->isVariadic()) {
Diag(Method->getLocation(),
diag::warn_conflicting_overriding_variadic);
Diag(Overridden->getLocation(), diag::note_previous_declaration);
}
}
void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl) {
if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
return;
if (MethodDecl->hasAttr<UnavailableAttr>() ||
MethodDecl->hasAttr<DeprecatedAttr>())
return;
bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
IsProtocolMethodDecl, false, false);
if (match)
for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
EF = MethodDecl->param_end();
IM != EM && IF != EF; ++IM, ++IF) {
match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
*IM, *IF,
IsProtocolMethodDecl, false, false);
if (!match)
break;
}
if (match)
match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
if (match)
match = !(MethodDecl->isClassMethod() &&
MethodDecl->getSelector() == GetNullarySelector("load", Context));
if (match) {
Diag(ImpMethodDecl->getLocation(),
diag::warn_category_method_impl_match);
Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
<< MethodDecl->getDeclName();
}
}
typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
typedef llvm::OwningPtr<ProtocolNameSet> LazyProtocolNameSet;
static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
ProtocolNameSet &PNS) {
if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
PNS.insert(PDecl->getIdentifier());
for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
PE = PDecl->protocol_end(); PI != PE; ++PI)
findProtocolsWithExplicitImpls(*PI, PNS);
}
static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
ProtocolNameSet &PNS) {
if (!Super)
return;
for (ObjCInterfaceDecl::all_protocol_iterator
I = Super->all_referenced_protocol_begin(),
E = Super->all_referenced_protocol_end(); I != E; ++I) {
findProtocolsWithExplicitImpls(*I, PNS);
}
findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
}
static void CheckProtocolMethodDefs(Sema &S,
SourceLocation ImpLoc,
ObjCProtocolDecl *PDecl,
bool& IncompleteImpl,
const Sema::SelectorSet &InsMap,
const Sema::SelectorSet &ClsMap,
ObjCContainerDecl *CDecl,
LazyProtocolNameSet &ProtocolsExplictImpl) {
ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
: dyn_cast<ObjCInterfaceDecl>(CDecl);
assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
ObjCInterfaceDecl *Super = IDecl->getSuperClass();
ObjCInterfaceDecl *NSIDecl = 0;
if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
if (!ProtocolsExplictImpl.isValid()) {
ProtocolsExplictImpl.reset(new ProtocolNameSet);
findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
}
if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
ProtocolsExplictImpl->end())
return;
Super = NULL;
}
if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
Selector fISelector = S.Context.Selectors.getSelector(1, &II);
if (InsMap.count(fISelector))
NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
}
if (!PDecl->isThisDeclarationADefinition() &&
PDecl->getDefinition())
PDecl = PDecl->getDefinition();
if (!NSIDecl)
for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
E = PDecl->instmeth_end(); I != E; ++I) {
ObjCMethodDecl *method = *I;
if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
!method->isPropertyAccessor() &&
!InsMap.count(method->getSelector()) &&
(!Super || !Super->lookupMethod(method->getSelector(),
true ,
false ,
true ,
NULL ))) {
if (ObjCMethodDecl *MethodInClass =
IDecl->lookupMethod(method->getSelector(),
true ,
true ,
false ))
if (C || MethodInClass->isPropertyAccessor())
continue;
unsigned DIAG = diag::warn_unimplemented_protocol_method;
if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc)
!= DiagnosticsEngine::Ignored) {
WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
PDecl);
}
}
}
for (ObjCProtocolDecl::classmeth_iterator
I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
I != E; ++I) {
ObjCMethodDecl *method = *I;
if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
!ClsMap.count(method->getSelector()) &&
(!Super || !Super->lookupMethod(method->getSelector(),
false ,
false ,
true ,
NULL ))) {
if (C && IDecl->lookupMethod(method->getSelector(),
false ,
true ,
false ))
continue;
unsigned DIAG = diag::warn_unimplemented_protocol_method;
if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
DiagnosticsEngine::Ignored) {
WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
}
}
}
for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
E = PDecl->protocol_end(); PI != E; ++PI)
CheckProtocolMethodDefs(S, ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap,
CDecl, ProtocolsExplictImpl);
}
void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
const SelectorSet &ClsMap,
SelectorSet &InsMapSeen,
SelectorSet &ClsMapSeen,
ObjCImplDecl* IMPDecl,
ObjCContainerDecl* CDecl,
bool &IncompleteImpl,
bool ImmediateClass,
bool WarnCategoryMethodImpl) {
for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
E = CDecl->instmeth_end(); I != E; ++I) {
if (!InsMapSeen.insert((*I)->getSelector()))
continue;
if (!(*I)->isPropertyAccessor() &&
!InsMap.count((*I)->getSelector())) {
if (ImmediateClass)
WarnUndefinedMethod(*this, IMPDecl->getLocation(), *I, IncompleteImpl,
diag::warn_undef_method_impl);
continue;
} else {
ObjCMethodDecl *ImpMethodDecl =
IMPDecl->getInstanceMethod((*I)->getSelector());
assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
"Expected to find the method through lookup as well");
ObjCMethodDecl *MethodDecl = *I;
if (ImpMethodDecl) {
if (!WarnCategoryMethodImpl)
WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
isa<ObjCProtocolDecl>(CDecl));
else if (!MethodDecl->isPropertyAccessor())
WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
isa<ObjCProtocolDecl>(CDecl));
}
}
}
for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
E = CDecl->classmeth_end();
I != E; ++I) {
if (!ClsMapSeen.insert((*I)->getSelector()))
continue;
if (!ClsMap.count((*I)->getSelector())) {
if (ImmediateClass)
WarnUndefinedMethod(*this, IMPDecl->getLocation(), *I, IncompleteImpl,
diag::warn_undef_method_impl);
} else {
ObjCMethodDecl *ImpMethodDecl =
IMPDecl->getClassMethod((*I)->getSelector());
assert(CDecl->getClassMethod((*I)->getSelector()) &&
"Expected to find the method through lookup as well");
ObjCMethodDecl *MethodDecl = *I;
if (!WarnCategoryMethodImpl)
WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
isa<ObjCProtocolDecl>(CDecl));
else
WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
isa<ObjCProtocolDecl>(CDecl));
}
}
if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
for (ObjCProtocolDecl::protocol_iterator
PI = PD->protocol_begin(), E = PD->protocol_end(); PI != E; ++PI)
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl, (*PI), IncompleteImpl, false,
WarnCategoryMethodImpl);
}
if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
if (!WarnCategoryMethodImpl) {
for (ObjCInterfaceDecl::visible_categories_iterator
Cat = I->visible_categories_begin(),
CatEnd = I->visible_categories_end();
Cat != CatEnd; ++Cat) {
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl, *Cat, IncompleteImpl, false,
WarnCategoryMethodImpl);
}
} else {
for (ObjCInterfaceDecl::visible_extensions_iterator
Ext = I->visible_extensions_begin(),
ExtEnd = I->visible_extensions_end();
Ext != ExtEnd; ++Ext) {
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl, *Ext, IncompleteImpl, false,
WarnCategoryMethodImpl);
}
}
for (ObjCInterfaceDecl::all_protocol_iterator
PI = I->all_referenced_protocol_begin(),
E = I->all_referenced_protocol_end(); PI != E; ++PI)
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl,
(*PI), IncompleteImpl, false,
WarnCategoryMethodImpl);
if (!WarnCategoryMethodImpl && I->getSuperClass())
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl,
I->getSuperClass(), IncompleteImpl, false);
}
}
void Sema::CheckCategoryVsClassMethodMatches(
ObjCCategoryImplDecl *CatIMPDecl) {
ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
if (!CatDecl)
return;
ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
if (!IDecl)
return;
ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
SelectorSet InsMap, ClsMap;
for (ObjCImplementationDecl::instmeth_iterator
I = CatIMPDecl->instmeth_begin(),
E = CatIMPDecl->instmeth_end(); I!=E; ++I) {
Selector Sel = (*I)->getSelector();
if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
continue;
InsMap.insert(Sel);
}
for (ObjCImplementationDecl::classmeth_iterator
I = CatIMPDecl->classmeth_begin(),
E = CatIMPDecl->classmeth_end(); I != E; ++I) {
Selector Sel = (*I)->getSelector();
if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
continue;
ClsMap.insert(Sel);
}
if (InsMap.empty() && ClsMap.empty())
return;
SelectorSet InsMapSeen, ClsMapSeen;
bool IncompleteImpl = false;
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
CatIMPDecl, IDecl,
IncompleteImpl, false,
true );
}
void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
ObjCContainerDecl* CDecl,
bool IncompleteImpl) {
SelectorSet InsMap;
for (ObjCImplementationDecl::instmeth_iterator
I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
InsMap.insert((*I)->getSelector());
if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
LangOpts.ObjCRuntime.isNonFragile() &&
!IDecl->isObjCRequiresPropertyDefs();
DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
}
SelectorSet ClsMap;
for (ObjCImplementationDecl::classmeth_iterator
I = IMPDecl->classmeth_begin(),
E = IMPDecl->classmeth_end(); I != E; ++I)
ClsMap.insert((*I)->getSelector());
SelectorSet InsMapSeen, ClsMapSeen;
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl, CDecl,
IncompleteImpl, true);
if (ObjCCategoryImplDecl *CatDecl =
dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
CheckCategoryVsClassMethodMatches(CatDecl);
LazyProtocolNameSet ExplicitImplProtocols;
if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
for (ObjCInterfaceDecl::all_protocol_iterator
PI = I->all_referenced_protocol_begin(),
E = I->all_referenced_protocol_end(); PI != E; ++PI)
CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), *PI,
IncompleteImpl, InsMap, ClsMap, I,
ExplicitImplProtocols);
for (ObjCInterfaceDecl::visible_extensions_iterator
Ext = I->visible_extensions_begin(),
ExtEnd = I->visible_extensions_end();
Ext != ExtEnd; ++Ext) {
ImplMethodsVsClassMethods(S, IMPDecl, *Ext, IncompleteImpl);
}
} else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
if (!C->IsClassExtension()) {
for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
E = C->protocol_end(); PI != E; ++PI)
CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), *PI,
IncompleteImpl, InsMap, ClsMap, CDecl,
ExplicitImplProtocols);
DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
false);
}
} else
llvm_unreachable("invalid ObjCContainerDecl type.");
}
Sema::DeclGroupPtrTy
Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
IdentifierInfo **IdentList,
SourceLocation *IdentLocs,
unsigned NumElts) {
SmallVector<Decl *, 8> DeclsInGroup;
for (unsigned i = 0; i != NumElts; ++i) {
NamedDecl *PrevDecl
= LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
LookupOrdinaryName, ForRedeclaration);
if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
} else {
if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
Diag(PrevDecl->getLocation(), diag::note_previous_definition);
continue;
}
}
}
ObjCInterfaceDecl *PrevIDecl
= dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
IdentifierInfo *ClassName = IdentList[i];
if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
ClassName = PrevIDecl->getIdentifier();
}
ObjCInterfaceDecl *IDecl
= ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
ClassName, PrevIDecl, IdentLocs[i]);
IDecl->setAtEndRange(IdentLocs[i]);
PushOnScopeChains(IDecl, TUScope);
CheckObjCDeclScope(IDecl);
DeclsInGroup.push_back(IDecl);
}
return BuildDeclaratorGroup(DeclsInGroup, false);
}
static bool tryMatchRecordTypes(ASTContext &Context,
Sema::MethodMatchStrategy strategy,
const Type *left, const Type *right);
static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
QualType leftQT, QualType rightQT) {
const Type *left =
Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
const Type *right =
Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
if (left == right) return true;
if (strategy == Sema::MMS_strict) return false;
if (left->isIncompleteType() || right->isIncompleteType()) return false;
if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
return false;
if (isa<VectorType>(left)) return isa<VectorType>(right);
if (isa<VectorType>(right)) return false;
if (!left->isScalarType() || !right->isScalarType())
return tryMatchRecordTypes(Context, strategy, left, right);
Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
leftSK = Type::STK_ObjCObjectPointer;
if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
rightSK = Type::STK_ObjCObjectPointer;
return (leftSK == rightSK);
}
static bool tryMatchRecordTypes(ASTContext &Context,
Sema::MethodMatchStrategy strategy,
const Type *lt, const Type *rt) {
assert(lt && rt && lt != rt);
if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
RecordDecl *left = cast<RecordType>(lt)->getDecl();
RecordDecl *right = cast<RecordType>(rt)->getDecl();
if (left->isUnion() != right->isUnion()) return false;
if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
(isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
return false;
if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
for (; li != le && ri != re; ++li, ++ri) {
if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
return false;
}
return (li == le && ri == re);
}
bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
const ObjCMethodDecl *right,
MethodMatchStrategy strategy) {
if (!matchTypes(Context, strategy, left->getReturnType(),
right->getReturnType()))
return false;
if (left->isHidden() || right->isHidden())
return false;
if (getLangOpts().ObjCAutoRefCount &&
(left->hasAttr<NSReturnsRetainedAttr>()
!= right->hasAttr<NSReturnsRetainedAttr>() ||
left->hasAttr<NSConsumesSelfAttr>()
!= right->hasAttr<NSConsumesSelfAttr>()))
return false;
ObjCMethodDecl::param_const_iterator
li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
re = right->param_end();
for (; li != le && ri != re; ++li, ++ri) {
assert(ri != right->param_end() && "Param mismatch");
const ParmVarDecl *lparm = *li, *rparm = *ri;
if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
return false;
if (getLangOpts().ObjCAutoRefCount &&
lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
return false;
}
return true;
}
void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
if (ObjCCategoryDecl *
CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
if (!CD->IsClassExtension() && List->getBits() < 2)
List->setBits(List->getBits()+1);
if (List->Method == 0) {
List->Method = Method;
List->setNext(0);
return;
}
ObjCMethodList *Previous = List;
for (; List; Previous = List, List = List->getNext()) {
if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
continue;
if (!MatchTwoMethodDeclarations(Method, List->Method))
continue;
ObjCMethodDecl *PrevObjCMethod = List->Method;
if (Method->isDefined())
PrevObjCMethod->setDefined(true);
if (Method->isDeprecated()) {
if (!PrevObjCMethod->isDeprecated())
List->Method = Method;
}
if (Method->isUnavailable()) {
if (PrevObjCMethod->getAvailability() < AR_Deprecated)
List->Method = Method;
}
return;
}
ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Previous->setNext(new (Mem) ObjCMethodList(Method, 0));
}
void Sema::ReadMethodPool(Selector Sel) {
assert(ExternalSource && "We need an external AST source");
ExternalSource->ReadMethodPool(Sel);
}
void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
bool instance) {
if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
return;
if (ExternalSource)
ReadMethodPool(Method->getSelector());
GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
if (Pos == MethodPool.end())
Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
GlobalMethods())).first;
Method->setDefined(impl);
ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
addMethodToGlobalList(&Entry, Method);
}
static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
ObjCMethodDecl *other) {
if (!chosen->isInstanceMethod())
return false;
Selector sel = chosen->getSelector();
if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
return false;
return (chosen->getReturnType()->isIntegerType());
}
ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool warn, bool instance) {
if (ExternalSource)
ReadMethodPool(Sel);
GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
if (Pos == MethodPool.end())
return 0;
ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
SmallVector<ObjCMethodDecl *, 4> Methods;
for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
if (M->Method && !M->Method->isHidden()) {
if (!warn)
return M->Method;
Methods.push_back(M->Method);
}
}
if (Methods.empty())
return 0;
if (Methods.size() == 1)
return Methods[0];
bool issueDiagnostic = false, issueError = false;
bool strictSelectorMatch =
(receiverIdOrClass && warn &&
(Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
R.getBegin())
!= DiagnosticsEngine::Ignored));
if (strictSelectorMatch) {
for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
issueDiagnostic = true;
break;
}
}
}
if (!strictSelectorMatch ||
(issueDiagnostic && getLangOpts().ObjCAutoRefCount))
for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
!isAcceptableMethodMismatch(Methods[0], Methods[I])) {
issueDiagnostic = true;
if (getLangOpts().ObjCAutoRefCount)
issueError = true;
break;
}
}
if (issueDiagnostic) {
if (issueError)
Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
else if (strictSelectorMatch)
Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
else
Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Diag(Methods[0]->getLocStart(),
issueError ? diag::note_possibility : diag::note_using)
<< Methods[0]->getSourceRange();
for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
Diag(Methods[I]->getLocStart(), diag::note_also_found)
<< Methods[I]->getSourceRange();
}
}
return Methods[0];
}
ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
if (Pos == MethodPool.end())
return 0;
GlobalMethods &Methods = Pos->second;
for (const ObjCMethodList *Method = &Methods.first; Method;
Method = Method->getNext())
if (Method->Method && Method->Method->isDefined())
return Method->Method;
for (const ObjCMethodList *Method = &Methods.second; Method;
Method = Method->getNext())
if (Method->Method && Method->Method->isDefined())
return Method->Method;
return 0;
}
static void
HelperSelectorsForTypoCorrection(
SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
StringRef Typo, const ObjCMethodDecl * Method) {
const unsigned MaxEditDistance = 1;
unsigned BestEditDistance = MaxEditDistance + 1;
std::string MethodName = Method->getSelector().getAsString();
unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
if (MinPossibleEditDistance > 0 &&
Typo.size() / MinPossibleEditDistance < 1)
return;
unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
if (EditDistance > MaxEditDistance)
return;
if (EditDistance == BestEditDistance)
BestMethod.push_back(Method);
else if (EditDistance < BestEditDistance) {
BestMethod.clear();
BestMethod.push_back(Method);
}
}
static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
QualType ObjectType) {
if (ObjectType.isNull())
return true;
if (S.LookupMethodInObjectType(Sel, ObjectType, true))
return true;
return S.LookupMethodInObjectType(Sel, ObjectType, false) != 0;
}
const ObjCMethodDecl *
Sema::SelectorsForTypoCorrection(Selector Sel,
QualType ObjectType) {
unsigned NumArgs = Sel.getNumArgs();
SmallVector<const ObjCMethodDecl *, 8> Methods;
bool ObjectIsId = true, ObjectIsClass = true;
if (ObjectType.isNull())
ObjectIsId = ObjectIsClass = false;
else if (!ObjectType->isObjCObjectPointerType())
return 0;
else if (const ObjCObjectPointerType *ObjCPtr =
ObjectType->getAsObjCInterfacePointerType()) {
ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
ObjectIsId = ObjectIsClass = false;
}
else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
ObjectIsClass = false;
else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
ObjectIsId = false;
else
return 0;
for (GlobalMethodPool::iterator b = MethodPool.begin(),
e = MethodPool.end(); b != e; b++) {
for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
if (M->Method &&
(M->Method->getSelector().getNumArgs() == NumArgs) &&
(M->Method->getSelector() != Sel)) {
if (ObjectIsId)
Methods.push_back(M->Method);
else if (!ObjectIsClass &&
HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
Methods.push_back(M->Method);
}
for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
if (M->Method &&
(M->Method->getSelector().getNumArgs() == NumArgs) &&
(M->Method->getSelector() != Sel)) {
if (ObjectIsClass)
Methods.push_back(M->Method);
else if (!ObjectIsId &&
HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
Methods.push_back(M->Method);
}
}
SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
for (unsigned i = 0, e = Methods.size(); i < e; i++) {
HelperSelectorsForTypoCorrection(SelectedMethods,
Sel.getAsString(), Methods[i]);
}
return (SelectedMethods.size() == 1) ? SelectedMethods[0] : NULL;
}
void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
ObjCInterfaceDecl *SID) {
for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
ObjCIvarDecl* Ivar = *IVI;
if (Ivar->isInvalidDecl())
continue;
if (IdentifierInfo *II = Ivar->getIdentifier()) {
ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
if (prevIvar) {
Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Ivar->setInvalidDecl();
}
}
}
}
Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
switch (CurContext->getDeclKind()) {
case Decl::ObjCInterface:
return Sema::OCK_Interface;
case Decl::ObjCProtocol:
return Sema::OCK_Protocol;
case Decl::ObjCCategory:
if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
return Sema::OCK_ClassExtension;
else
return Sema::OCK_Category;
case Decl::ObjCImplementation:
return Sema::OCK_Implementation;
case Decl::ObjCCategoryImpl:
return Sema::OCK_CategoryImplementation;
default:
return Sema::OCK_None;
}
}
Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
ArrayRef<DeclGroupPtrTy> allTUVars) {
if (getObjCContainerKind() == Sema::OCK_None)
return 0;
assert(AtEnd.isValid() && "Invalid location for '@end'");
ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
Decl *ClassDecl = cast<Decl>(OCD);
bool isInterfaceDeclKind =
isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
|| isa<ObjCProtocolDecl>(ClassDecl);
bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
ObjCMethodDecl *Method =
cast_or_null<ObjCMethodDecl>(allMethods[i]);
if (!Method) continue; if (Method->isInstanceMethod()) {
const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
: false;
if ((isInterfaceDeclKind && PrevMethod && !match)
|| (checkIdenticalMethods && match)) {
Diag(Method->getLocation(), diag::err_duplicate_method_decl)
<< Method->getDeclName();
Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Method->setInvalidDecl();
} else {
if (PrevMethod) {
Method->setAsRedeclaration(PrevMethod);
if (!Context.getSourceManager().isInSystemHeader(
Method->getLocation()))
Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
<< Method->getDeclName();
Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
}
InsMap[Method->getSelector()] = Method;
AddInstanceMethodToGlobalPool(Method);
}
} else {
const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
: false;
if ((isInterfaceDeclKind && PrevMethod && !match)
|| (checkIdenticalMethods && match)) {
Diag(Method->getLocation(), diag::err_duplicate_method_decl)
<< Method->getDeclName();
Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Method->setInvalidDecl();
} else {
if (PrevMethod) {
Method->setAsRedeclaration(PrevMethod);
if (!Context.getSourceManager().isInSystemHeader(
Method->getLocation()))
Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
<< Method->getDeclName();
Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
}
ClsMap[Method->getSelector()] = Method;
AddFactoryMethodToGlobalPool(Method);
}
}
}
if (isa<ObjCInterfaceDecl>(ClassDecl)) {
} else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
if (C->IsClassExtension()) {
ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
DiagnoseClassExtensionDupMethods(C, CCPrimary);
}
}
if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
if (CDecl->getIdentifier())
for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
E = CDecl->prop_end();
I != E; ++I)
ProcessPropertyDecl(*I, CDecl);
CDecl->setAtEndRange(AtEnd);
}
if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
IC->setAtEndRange(AtEnd);
if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
for (ObjCInterfaceDecl::visible_extensions_iterator
Ext = IDecl->visible_extensions_begin(),
ExtEnd = IDecl->visible_extensions_end();
Ext != ExtEnd; ++Ext) {
for (ObjCContainerDecl::prop_iterator I = Ext->prop_begin(),
E = Ext->prop_end(); I != E; ++I) {
ObjCPropertyDecl *Property = *I;
if (const ObjCPropertyImplDecl *PIDecl
= IC->FindPropertyImplDecl(Property->getIdentifier()))
if (PIDecl->getPropertyImplementation()
== ObjCPropertyImplDecl::Dynamic)
continue;
for (ObjCInterfaceDecl::visible_extensions_iterator
Ext = IDecl->visible_extensions_begin(),
ExtEnd = IDecl->visible_extensions_end();
Ext != ExtEnd; ++Ext) {
if (ObjCMethodDecl *GetterMethod
= Ext->getInstanceMethod(Property->getGetterName()))
GetterMethod->setPropertyAccessor(true);
if (!Property->isReadOnly())
if (ObjCMethodDecl *SetterMethod
= Ext->getInstanceMethod(Property->getSetterName()))
SetterMethod->setPropertyAccessor(true);
}
}
}
ImplMethodsVsClassMethods(S, IC, IDecl);
AtomicPropertySetterGetterRules(IC, IDecl);
DiagnoseOwningPropertyGetterSynthesis(IC);
DiagnoseUnusedBackingIvarInAccessor(S, IC);
if (IDecl->hasDesignatedInitializers())
DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
if (IDecl->getSuperClass() == NULL) {
if (!HasRootClassAttr) {
SourceLocation DeclLoc(IDecl->getLocation());
SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc));
Diag(DeclLoc, diag::warn_objc_root_class_missing)
<< IDecl->getIdentifier();
NamedDecl *IF = LookupSingleName(TUScope,
NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
DeclLoc, LookupOrdinaryName);
ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
if (NSObjectDecl && NSObjectDecl->getDefinition()) {
Diag(SuperClassLoc, diag::note_objc_needs_superclass)
<< FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
} else {
Diag(SuperClassLoc, diag::note_objc_needs_superclass);
}
}
} else if (HasRootClassAttr) {
Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
}
if (LangOpts.ObjCRuntime.isNonFragile()) {
while (IDecl->getSuperClass()) {
DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
IDecl = IDecl->getSuperClass();
}
}
}
SetIvarInitializers(IC);
} else if (ObjCCategoryImplDecl* CatImplClass =
dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
CatImplClass->setAtEndRange(AtEnd);
if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
if (ObjCCategoryDecl *Cat
= IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
ImplMethodsVsClassMethods(S, CatImplClass, Cat);
}
}
} else if (const ObjCInterfaceDecl *IntfDecl =
dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
Diag(Super->getLocation(), diag::note_class_declared);
}
}
}
if (isInterfaceDeclKind) {
for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
DeclGroupRef DG = allTUVars[i].get();
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
if (!VDecl->hasExternalStorage())
Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
}
}
}
ActOnObjCContainerFinishDefinition();
for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
DeclGroupRef DG = allTUVars[i].get();
for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
(*I)->setTopLevelDeclInObjCContainer();
Consumer.HandleTopLevelDeclInObjCContainer(DG);
}
ActOnDocumentableDecl(ClassDecl);
return ClassDecl;
}
static Decl::ObjCDeclQualifier
CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
}
static Sema::ResultTypeCompatibilityKind
CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
ObjCInterfaceDecl *CurrentClass) {
QualType ResultType = Method->getReturnType();
if (const ObjCObjectPointerType *ResultObjectType
= ResultType->getAs<ObjCObjectPointerType>()) {
if (ResultObjectType->isObjCIdType() ||
ResultObjectType->isObjCQualifiedIdType())
return Sema::RTC_Compatible;
if (CurrentClass) {
if (ObjCInterfaceDecl *ResultClass
= ResultObjectType->getInterfaceDecl()) {
if (declaresSameEntity(CurrentClass, ResultClass))
return Sema::RTC_Compatible;
if (ResultClass->isSuperClassOf(CurrentClass))
return Sema::RTC_Compatible;
}
} else {
return Sema::RTC_Unknown;
}
}
return Sema::RTC_Incompatible;
}
namespace {
class OverrideSearch {
public:
Sema &S;
ObjCMethodDecl *Method;
llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
bool Recursive;
public:
OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
Selector selector = method->getSelector();
Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
if (it == S.MethodPool.end()) {
if (!S.getExternalSource()) return;
S.ReadMethodPool(selector);
it = S.MethodPool.find(selector);
if (it == S.MethodPool.end())
return;
}
ObjCMethodList &list =
method->isInstanceMethod() ? it->second.first : it->second.second;
if (!list.Method) return;
ObjCContainerDecl *container
= cast<ObjCContainerDecl>(method->getDeclContext());
if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
searchFromContainer(container);
if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
searchFromContainer(Interface);
} else {
searchFromContainer(container);
}
}
typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
iterator begin() const { return Overridden.begin(); }
iterator end() const { return Overridden.end(); }
private:
void searchFromContainer(ObjCContainerDecl *container) {
if (container->isInvalidDecl()) return;
switch (container->getDeclKind()) {
#define OBJCCONTAINER(type, base) \
case Decl::type: \
searchFrom(cast<type##Decl>(container)); \
break;
#define ABSTRACT_DECL(expansion)
#define DECL(type, base) \
case Decl::type:
#include "clang/AST/DeclNodes.inc"
llvm_unreachable("not an ObjC container!");
}
}
void searchFrom(ObjCProtocolDecl *protocol) {
if (!protocol->hasDefinition())
return;
search(protocol->getReferencedProtocols());
}
void searchFrom(ObjCCategoryDecl *category) {
search(category->getReferencedProtocols());
}
void searchFrom(ObjCCategoryImplDecl *impl) {
if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
search(category);
if (ObjCInterfaceDecl *Interface = category->getClassInterface())
search(Interface);
} else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
search(Interface);
}
}
void searchFrom(ObjCInterfaceDecl *iface) {
if (!iface->hasDefinition())
return;
for (ObjCInterfaceDecl::known_categories_iterator
cat = iface->known_categories_begin(),
catEnd = iface->known_categories_end();
cat != catEnd; ++cat) {
search(*cat);
}
if (ObjCInterfaceDecl *super = iface->getSuperClass())
search(super);
search(iface->getReferencedProtocols());
}
void searchFrom(ObjCImplementationDecl *impl) {
if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
search(Interface);
}
void search(const ObjCProtocolList &protocols) {
for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
i != e; ++i)
search(*i);
}
void search(ObjCContainerDecl *container) {
ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Method->isInstanceMethod(),
true);
if (meth) {
Overridden.insert(meth);
return;
}
Recursive = true;
searchFromContainer(container);
}
};
}
void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC) {
OverrideSearch overrides(*this, ObjCMethod);
bool hasOverriddenMethodsInBaseOrProtocol = false;
for (OverrideSearch::iterator
i = overrides.begin(), e = overrides.end(); i != e; ++i) {
ObjCMethodDecl *overridden = *i;
if (!hasOverriddenMethodsInBaseOrProtocol) {
if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
CurrentClass != overridden->getClassInterface() ||
overridden->isOverriding()) {
hasOverriddenMethodsInBaseOrProtocol = true;
} else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
GlobalMethodPool::iterator It =
MethodPool.find(ObjCMethod->getSelector());
if (It != MethodPool.end()) {
ObjCMethodList &List =
ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
unsigned CategCount = List.getBits();
if (CategCount > 0) {
if (CategCount > 1 ||
!isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
OverrideSearch overrides(*this, overridden);
for (OverrideSearch::iterator
OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
ObjCMethodDecl *SuperOverridden = *OI;
if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
CurrentClass != SuperOverridden->getClassInterface()) {
hasOverriddenMethodsInBaseOrProtocol = true;
overridden->setOverriding(true);
break;
}
}
}
}
}
}
}
if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
ObjCMethod->SetRelatedResultType();
mergeObjCMethodDecls(ObjCMethod, overridden);
if (ObjCMethod->isImplicit() && overridden->isImplicit())
continue;
if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
CheckConflictingOverridingMethod(ObjCMethod, overridden,
isa<ObjCProtocolDecl>(overridden->getDeclContext()));
if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
!overridden->isImplicit() ) {
ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
E = ObjCMethod->param_end();
ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
PrevE = overridden->param_end();
for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
assert(PrevI != overridden->param_end() && "Param mismatch");
QualType T1 = Context.getCanonicalType((*ParamI)->getType());
QualType T2 = Context.getCanonicalType((*PrevI)->getType());
if (!Context.typesAreCompatible(T1, T2)) {
Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
<< T1 << T2;
Diag(overridden->getLocation(), diag::note_previous_declaration);
break;
}
}
}
}
ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
}
Decl *Sema::ActOnMethodDeclaration(
Scope *S,
SourceLocation MethodLoc, SourceLocation EndLoc,
tok::TokenKind MethodType,
ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
ArrayRef<SourceLocation> SelectorLocs,
Selector Sel,
ObjCArgInfo *ArgInfo,
DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
bool isVariadic, bool MethodDefinition) {
if (!CurContext->isObjCContainer()) {
Diag(MethodLoc, diag::error_missing_method_context);
return 0;
}
ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
Decl *ClassDecl = cast<Decl>(OCD);
QualType resultDeclType;
bool HasRelatedResultType = false;
TypeSourceInfo *ReturnTInfo = 0;
if (ReturnType) {
resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
if (CheckFunctionReturnType(resultDeclType, MethodLoc))
return 0;
HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
} else { resultDeclType = Context.getObjCIdType();
Diag(MethodLoc, diag::warn_missing_method_return_type)
<< FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
}
ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
MethodType == tok::minus, isVariadic,
false,
false, false,
MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
: ObjCMethodDecl::Required,
HasRelatedResultType);
SmallVector<ParmVarDecl*, 16> Params;
for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
QualType ArgType;
TypeSourceInfo *DI;
if (!ArgInfo[i].Type) {
ArgType = Context.getObjCIdType();
DI = 0;
} else {
ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
}
LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
LookupOrdinaryName, ForRedeclaration);
LookupName(R, S);
if (R.isSingleResult()) {
NamedDecl *PrevDecl = R.getFoundDecl();
if (S->isDeclScope(PrevDecl)) {
Diag(ArgInfo[i].NameLoc,
(MethodDefinition ? diag::warn_method_param_redefinition
: diag::warn_method_param_declaration))
<< ArgInfo[i].Name;
Diag(PrevDecl->getLocation(),
diag::note_previous_declaration);
}
}
SourceLocation StartLoc = DI
? DI->getTypeLoc().getBeginLoc()
: ArgInfo[i].NameLoc;
ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
ArgInfo[i].NameLoc, ArgInfo[i].Name,
ArgType, DI, SC_None);
Param->setObjCMethodScopeInfo(i);
Param->setObjCDeclQualifier(
CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
if (Param->hasAttr<BlocksAttr>()) {
Diag(Param->getLocation(), diag::err_block_on_nonlocal);
Param->setInvalidDecl();
}
S->AddDecl(Param);
IdResolver.AddDecl(Param);
Params.push_back(Param);
}
for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
QualType ArgType = Param->getType();
if (ArgType.isNull())
ArgType = Context.getObjCIdType();
else
ArgType = Context.getAdjustedParameterType(ArgType);
Param->setDeclContext(ObjCMethod);
Params.push_back(Param);
}
ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
ObjCMethod->setObjCDeclQualifier(
CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
if (AttrList)
ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
const ObjCMethodDecl *PrevMethod = 0;
if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
if (MethodType == tok::minus) {
PrevMethod = ImpDecl->getInstanceMethod(Sel);
ImpDecl->addInstanceMethod(ObjCMethod);
} else {
PrevMethod = ImpDecl->getClassMethod(Sel);
ImpDecl->addClassMethod(ObjCMethod);
}
ObjCMethodDecl *IMD = 0;
if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
ObjCMethod->isInstanceMethod());
if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
!ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
ObjCMethod->getLocation()));
}
if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
ObjCMethodFamily family =
ObjCMethod->getSelector().getMethodFamily();
if (family == OMF_dealloc && IMD && IMD->isOverriding())
Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
<< ObjCMethod->getDeclName();
}
} else {
cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
}
if (PrevMethod) {
Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
<< ObjCMethod->getDeclName();
Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
ObjCMethod->setInvalidDecl();
return ObjCMethod;
}
ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
if (!CurrentClass) {
if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
CurrentClass = Cat->getClassInterface();
else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
CurrentClass = Impl->getClassInterface();
else if (ObjCCategoryImplDecl *CatImpl
= dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
CurrentClass = CatImpl->getClassInterface();
}
ResultTypeCompatibilityKind RTC
= CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
bool ARCError = false;
if (getLangOpts().ObjCAutoRefCount)
ARCError = CheckARCMethodDecl(ObjCMethod);
if (!ARCError && RTC == Sema::RTC_Compatible &&
!ObjCMethod->hasRelatedResultType() &&
LangOpts.ObjCInferRelatedResultType) {
bool InferRelatedResultType = false;
switch (ObjCMethod->getMethodFamily()) {
case OMF_None:
case OMF_copy:
case OMF_dealloc:
case OMF_finalize:
case OMF_mutableCopy:
case OMF_release:
case OMF_retainCount:
case OMF_performSelector:
break;
case OMF_alloc:
case OMF_new:
InferRelatedResultType = ObjCMethod->isClassMethod();
break;
case OMF_init:
case OMF_autorelease:
case OMF_retain:
case OMF_self:
InferRelatedResultType = ObjCMethod->isInstanceMethod();
break;
}
if (InferRelatedResultType)
ObjCMethod->SetRelatedResultType();
}
ActOnDocumentableDecl(ObjCMethod);
return ObjCMethod;
}
bool Sema::CheckObjCDeclScope(Decl *D) {
if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
return false;
if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
return false;
Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
D->setInvalidDecl();
return true;
}
void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
IdentifierInfo *ClassName,
SmallVectorImpl<Decl*> &Decls) {
ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
if (!Class) {
Diag(DeclStart, diag::err_undef_interface) << ClassName;
return;
}
if (LangOpts.ObjCRuntime.isNonFragile()) {
Diag(DeclStart, diag::err_atdef_nonfragile_interface);
return;
}
SmallVector<const ObjCIvarDecl*, 32> Ivars;
Context.DeepCollectObjCIvars(Class, true, Ivars);
for (unsigned i = 0; i < Ivars.size(); i++) {
const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
ID->getLocation(),
ID->getLocation(),
ID->getIdentifier(), ID->getType(),
ID->getBitWidth());
Decls.push_back(FD);
}
for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
D != Decls.end(); ++D) {
FieldDecl *FD = cast<FieldDecl>(*D);
if (getLangOpts().CPlusPlus)
PushOnScopeChains(cast<FieldDecl>(FD), S);
else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Record->addDecl(FD);
}
}
VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
SourceLocation StartLoc,
SourceLocation IdLoc,
IdentifierInfo *Id,
bool Invalid) {
if (T.getAddressSpace() != 0) {
Diag(IdLoc, diag::err_arg_with_address_space);
Invalid = true;
}
if (Invalid) {
} else if (T->isDependentType()) {
} else if (!T->isObjCObjectPointerType()) {
Invalid = true;
Diag(IdLoc ,diag::err_catch_param_not_objc_type);
} else if (T->isObjCQualifiedIdType()) {
Invalid = true;
Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
}
VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
T, TInfo, SC_None);
New->setExceptionVariable(true);
if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Invalid = true;
if (Invalid)
New->setInvalidDecl();
return New;
}
Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
const DeclSpec &DS = D.getDeclSpec();
if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
<< FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
} else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
<< DeclSpec::getSpecifierName(SCS);
}
if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
diag::err_invalid_thread)
<< DeclSpec::getSpecifierName(TSCS);
D.getMutableDeclSpec().ClearStorageClassSpecs();
DiagnoseFunctionSpecifiers(D.getDeclSpec());
if (getLangOpts().CPlusPlus)
CheckExtraCXXDefaultArguments(D);
TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
QualType ExceptionType = TInfo->getType();
VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
D.getSourceRange().getBegin(),
D.getIdentifierLoc(),
D.getIdentifier(),
D.isInvalidType());
if (D.getCXXScopeSpec().isSet()) {
Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
<< D.getCXXScopeSpec().getRange();
New->setInvalidDecl();
}
S->AddDecl(New);
if (D.getIdentifier())
IdResolver.AddDecl(New);
ProcessDeclAttributes(S, New, D);
if (New->hasAttr<BlocksAttr>())
Diag(New->getLocation(), diag::err_block_on_nonlocal);
return New;
}
void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
Iv= Iv->getNextIvar()) {
QualType QT = Context.getBaseElementType(Iv->getType());
if (QT->isRecordType())
Ivars.push_back(Iv);
}
}
void Sema::DiagnoseUseOfUnimplementedSelectors() {
if (ExternalSource) {
SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
ExternalSource->ReadReferencedSelectors(Sels);
for (unsigned I = 0, N = Sels.size(); I != N; ++I)
ReferencedSelectors[Sels[I].first] = Sels[I].second;
}
if (ReferencedSelectors.empty() ||
!Context.AnyObjCImplementation())
return;
for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
ReferencedSelectors.begin(),
E = ReferencedSelectors.end(); S != E; ++S) {
Selector Sel = (*S).first;
if (!LookupImplementedMethodInGlobalPool(Sel))
Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
}
return;
}
ObjCIvarDecl *
Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const {
if (Method->isClassMethod())
return 0;
const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
if (!IDecl)
return 0;
Method = IDecl->lookupMethod(Method->getSelector(), true,
false,
false);
if (!Method || !Method->isPropertyAccessor())
return 0;
if ((PDecl = Method->findPropertyDecl()))
if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
IV->getIdentifier());
return IV;
}
return 0;
}
namespace {
class UnusedBackingIvarChecker :
public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
public:
Sema &S;
const ObjCMethodDecl *Method;
const ObjCIvarDecl *IvarD;
bool AccessedIvar;
bool InvokedSelfMethod;
UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
const ObjCIvarDecl *IvarD)
: S(S), Method(Method), IvarD(IvarD),
AccessedIvar(false), InvokedSelfMethod(false) {
assert(IvarD);
}
bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
if (E->getDecl() == IvarD) {
AccessedIvar = true;
return false;
}
return true;
}
bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
S.isSelfExpr(E->getInstanceReceiver(), Method)) {
InvokedSelfMethod = true;
}
return true;
}
};
}
void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
const ObjCImplementationDecl *ImplD) {
if (S->hasUnrecoverableErrorOccurred())
return;
for (ObjCImplementationDecl::instmeth_iterator
MI = ImplD->instmeth_begin(),
ME = ImplD->instmeth_end(); MI != ME; ++MI) {
const ObjCMethodDecl *CurMethod = *MI;
unsigned DIAG = diag::warn_unused_property_backing_ivar;
SourceLocation Loc = CurMethod->getLocation();
if (Diags.getDiagnosticLevel(DIAG, Loc) == DiagnosticsEngine::Ignored)
continue;
const ObjCPropertyDecl *PDecl;
const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
if (!IV)
continue;
UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
Checker.TraverseStmt(CurMethod->getBody());
if (Checker.AccessedIvar)
continue;
if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Diag(Loc, DIAG) << IV;
Diag(PDecl->getLocation(), diag::note_property_declare);
}
}
}