#include "TypeLocBuilder.h"
#include "clang/AST/ASTConsumer.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/ASTMutationListener.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/Expr.h"
#include "clang/AST/ExprObjC.h"
#include "clang/AST/RecursiveASTVisitor.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
#include "clang/Sema/DeclSpec.h"
#include "clang/Sema/Lookup.h"
#include "clang/Sema/Scope.h"
#include "clang/Sema/ScopeInfo.h"
#include "clang/Sema/SemaInternal.h"
#include "llvm/ADT/DenseMap.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 = nullptr;
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, "",
UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
return true;
}
Diag(loc, diag::err_arc_init_method_unrelated_result_type);
method->setInvalidDecl();
return true;
}
static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
Sema &S) {
if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
return false;
}
return true;
}
static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
const ObjCCategoryDecl *CD,
const ObjCProtocolDecl *PD, Sema &S) {
if (!diagnoseNoescape(NewD, OldD, S))
S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
<< CD->IsClassExtension() << PD
<< cast<ObjCMethodDecl>(NewD->getDeclContext());
}
void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
const ObjCMethodDecl *Overridden) {
if (Overridden->hasRelatedResultType() &&
!NewMethod->hasRelatedResultType()) {
QualType ResultType = NewMethod->getReturnType();
SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
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 ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
Overridden->hasAttr<NSReturnsRetainedAttr>())) {
Diag(NewMethod->getLocation(),
getLangOpts().ObjCAutoRefCount
? diag::err_nsreturns_retained_attribute_mismatch
: diag::warn_nsreturns_retained_attribute_mismatch)
<< 1;
Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
}
if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
Diag(NewMethod->getLocation(),
getLangOpts().ObjCAutoRefCount
? diag::err_nsreturns_retained_attribute_mismatch
: diag::warn_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(),
getLangOpts().ObjCAutoRefCount
? diag::err_nsconsumed_attribute_mismatch
: diag::warn_nsconsumed_attribute_mismatch);
Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
}
diagnoseNoescape(newDecl, oldDecl, *this);
}
}
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_initialize:
case OMF_performSelector:
return false;
case OMF_dealloc:
if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
if (ResultTypeRange.isInvalid())
Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
<< method->getReturnType()
<< FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
else
Diag(method->getLocation(), diag::err_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, const NamedDecl *ND,
SourceLocation ImplLoc) {
if (!ND)
return;
bool IsCategory = false;
StringRef RealizedPlatform;
AvailabilityResult Availability = ND->getAvailability(
nullptr, VersionTuple(),
&RealizedPlatform);
if (Availability != AR_Deprecated) {
if (isa<ObjCMethodDecl>(ND)) {
if (Availability != AR_Unavailable)
return;
if (RealizedPlatform.empty())
RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
if (RealizedPlatform.endswith("_app_extension"))
return;
S.Diag(ImplLoc, diag::warn_unavailable_def);
S.Diag(ND->getLocation(), diag::note_method_declared_at)
<< ND->getDeclName();
return;
}
if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
if (!CD->getClassInterface()->isDeprecated())
return;
ND = CD->getClassInterface();
IsCategory = true;
} else
return;
}
S.Diag(ImplLoc, diag::warn_deprecated_def)
<< (isa<ObjCMethodDecl>(ND)
? 0
: isa<ObjCCategoryDecl>(ND) || IsCategory ? 2
: 1);
if (isa<ObjCMethodDecl>(ND))
S.Diag(ND->getLocation(), diag::note_method_declared_at)
<< ND->getDeclName();
else
S.Diag(ND->getLocation(), diag::note_previous_decl)
<< (isa<ObjCCategoryDecl>(ND) ? "category" : "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) {
ImplicitlyRetainedSelfLocs.clear();
assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
if (!MDecl)
return;
QualType ResultType = MDecl->getReturnType();
if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
!MDecl->isInvalidDecl() &&
RequireCompleteType(MDecl->getLocation(), ResultType,
diag::err_func_def_incomplete_result))
MDecl->setInvalidDecl();
PushDeclContext(FnBodyScope, MDecl);
PushFunctionScope();
MDecl->createImplicitParams(Context, MDecl->getClassInterface());
PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
CheckParmsForFunctionDef(MDecl->parameters(),
false);
for (auto *Param : MDecl->parameters()) {
if (!Param->isInvalidDecl() &&
getLangOpts().ObjCAutoRefCount &&
!HasExplicitOwnershipAttr(*this, Param))
Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
Param->getType();
if (Param->getIdentifier())
PushOnScopeChains(Param, 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_initialize:
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 = nullptr;
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, IMD, MDecl->getLocation());
}
if (MDecl->getMethodFamily() == OMF_init) {
if (MDecl->isDesignatedInitializerForTheInterface()) {
getCurFunction()->ObjCIsDesignatedInit = true;
getCurFunction()->ObjCWarnForNoDesignatedInitChain =
IC->getSuperClass() != nullptr;
} 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 final : public CorrectionCandidateCallback {
public:
ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
: CurrentIDecl(IDecl) {}
bool ValidateCandidate(const TypoCorrection &candidate) override {
ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
return ID && !declaresSameEntity(ID, CurrentIDecl);
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
}
private:
ObjCInterfaceDecl *CurrentIDecl;
};
}
static void diagnoseUseOfProtocols(Sema &TheSema,
ObjCContainerDecl *CD,
ObjCProtocolDecl *const *ProtoRefs,
unsigned NumProtoRefs,
const SourceLocation *ProtoLocs) {
assert(ProtoRefs);
Sema::ContextRAII SavedContext(TheSema, CD);
for (unsigned i = 0; i < NumProtoRefs; ++i) {
(void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
nullptr,
false,
true);
}
}
void Sema::
ActOnSuperClassOfClassInterface(Scope *S,
SourceLocation AtInterfaceLoc,
ObjCInterfaceDecl *IDecl,
IdentifierInfo *ClassName,
SourceLocation ClassLoc,
IdentifierInfo *SuperName,
SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs,
SourceRange SuperTypeArgsRange) {
NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
LookupOrdinaryName);
if (!PrevDecl) {
ObjCInterfaceValidatorCCC CCC(IDecl);
if (TypoCorrection Corrected = CorrectTypo(
DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
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);
QualType SuperClassType;
if (SuperClassDecl) {
(void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
}
if (PrevDecl && !SuperClassDecl) {
if (const TypedefNameDecl *TDecl =
dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
QualType T = TDecl->getUnderlyingType();
if (T->isObjCObjectType()) {
if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
SuperClassType = Context.getTypeDeclType(TDecl);
(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 (!isa_and_nonnull<TypedefNameDecl>(PrevDecl)) {
if (!SuperClassDecl)
Diag(SuperLoc, diag::err_undef_superclass)
<< SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
else if (RequireCompleteType(SuperLoc,
SuperClassType,
diag::err_forward_superclass,
SuperClassDecl->getDeclName(),
ClassName,
SourceRange(AtInterfaceLoc, ClassLoc))) {
SuperClassDecl = nullptr;
SuperClassType = QualType();
}
}
if (SuperClassType.isNull()) {
assert(!SuperClassDecl && "Failed to set SuperClassType?");
return;
}
TypeSourceInfo *SuperClassTInfo = nullptr;
if (!SuperTypeArgs.empty()) {
TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
S,
SuperLoc,
CreateParsedType(SuperClassType,
nullptr),
SuperTypeArgsRange.getBegin(),
SuperTypeArgs,
SuperTypeArgsRange.getEnd(),
SourceLocation(),
{ },
{ },
SourceLocation());
if (!fullSuperClassType.isUsable())
return;
SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
&SuperClassTInfo);
}
if (!SuperClassTInfo) {
SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
SuperLoc);
}
IDecl->setSuperClass(SuperClassTInfo);
IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
}
}
DeclResult Sema::actOnObjCTypeParam(Scope *S,
ObjCTypeParamVariance variance,
SourceLocation varianceLoc,
unsigned index,
IdentifierInfo *paramName,
SourceLocation paramLoc,
SourceLocation colonLoc,
ParsedType parsedTypeBound) {
TypeSourceInfo *typeBoundInfo = nullptr;
if (parsedTypeBound) {
QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
if (typeBound->isObjCObjectPointerType()) {
} else if (typeBound->isObjCObjectType()) {
SourceLocation starLoc = getLocForEndOfToken(
typeBoundInfo->getTypeLoc().getEndLoc());
Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
diag::err_objc_type_param_bound_missing_pointer)
<< typeBound << paramName
<< FixItHint::CreateInsertion(starLoc, " *");
TypeLocBuilder builder;
builder.pushFullCopy(typeBoundInfo->getTypeLoc());
typeBound = Context.getObjCObjectPointerType(typeBound);
ObjCObjectPointerTypeLoc newT
= builder.push<ObjCObjectPointerTypeLoc>(typeBound);
newT.setStarLoc(starLoc);
typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
} else {
Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
diag::err_objc_type_param_bound_nonobject)
<< typeBound << paramName;
typeBoundInfo = nullptr;
}
if (typeBoundInfo) {
QualType typeBound = typeBoundInfo->getType();
TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
if (qual || typeBound.hasQualifiers()) {
bool diagnosed = false;
SourceRange rangeToRemove;
if (qual) {
if (auto attr = qual.getAs<AttributedTypeLoc>()) {
rangeToRemove = attr.getLocalSourceRange();
if (attr.getTypePtr()->getImmediateNullability()) {
Diag(attr.getBeginLoc(),
diag::err_objc_type_param_bound_explicit_nullability)
<< paramName << typeBound
<< FixItHint::CreateRemoval(rangeToRemove);
diagnosed = true;
}
}
}
if (!diagnosed) {
Diag(qual ? qual.getBeginLoc()
: typeBoundInfo->getTypeLoc().getBeginLoc(),
diag::err_objc_type_param_bound_qualified)
<< paramName << typeBound
<< typeBound.getQualifiers().getAsString()
<< FixItHint::CreateRemoval(rangeToRemove);
}
Qualifiers quals = typeBound.getQualifiers();
quals.removeCVRQualifiers();
if (!quals.empty()) {
typeBoundInfo =
Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
}
}
}
}
if (!typeBoundInfo) {
colonLoc = SourceLocation();
typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
}
return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
index, paramLoc, paramName, colonLoc,
typeBoundInfo);
}
ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
SourceLocation lAngleLoc,
ArrayRef<Decl *> typeParamsIn,
SourceLocation rAngleLoc) {
ArrayRef<ObjCTypeParamDecl *>
typeParams(
reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
typeParamsIn.size());
llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
for (auto typeParam : typeParams) {
auto known = knownParams.find(typeParam->getIdentifier());
if (known != knownParams.end()) {
Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
<< typeParam->getIdentifier()
<< SourceRange(known->second->getLocation());
typeParam->setInvalidDecl();
} else {
knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
PushOnScopeChains(typeParam, S, false);
}
}
return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
}
void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
for (auto typeParam : *typeParamList) {
if (!typeParam->isInvalidDecl()) {
S->RemoveDecl(typeParam);
IdResolver.RemoveDecl(typeParam);
}
}
}
namespace {
enum class TypeParamListContext {
ForwardDeclaration,
Definition,
Category,
Extension
};
}
static bool checkTypeParamListConsistency(Sema &S,
ObjCTypeParamList *prevTypeParams,
ObjCTypeParamList *newTypeParams,
TypeParamListContext newContext) {
if (prevTypeParams->size() != newTypeParams->size()) {
SourceLocation diagLoc;
if (newTypeParams->size() > prevTypeParams->size()) {
diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
} else {
diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
}
S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
<< static_cast<unsigned>(newContext)
<< (newTypeParams->size() > prevTypeParams->size())
<< prevTypeParams->size()
<< newTypeParams->size();
return true;
}
for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
newContext != TypeParamListContext::Definition) {
newTypeParam->setVariance(prevTypeParam->getVariance());
} else if (prevTypeParam->getVariance()
== ObjCTypeParamVariance::Invariant &&
!(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
->getDefinition() == prevTypeParam->getDeclContext())) {
} else {
{
SourceLocation diagLoc = newTypeParam->getVarianceLoc();
if (diagLoc.isInvalid())
diagLoc = newTypeParam->getBeginLoc();
auto diag = S.Diag(diagLoc,
diag::err_objc_type_param_variance_conflict)
<< static_cast<unsigned>(newTypeParam->getVariance())
<< newTypeParam->getDeclName()
<< static_cast<unsigned>(prevTypeParam->getVariance())
<< prevTypeParam->getDeclName();
switch (prevTypeParam->getVariance()) {
case ObjCTypeParamVariance::Invariant:
diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
break;
case ObjCTypeParamVariance::Covariant:
case ObjCTypeParamVariance::Contravariant: {
StringRef newVarianceStr
= prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
? "__covariant"
: "__contravariant";
if (newTypeParam->getVariance()
== ObjCTypeParamVariance::Invariant) {
diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
(newVarianceStr + " ").str());
} else {
diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
newVarianceStr);
}
}
}
}
S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
<< prevTypeParam->getDeclName();
newTypeParam->setVariance(prevTypeParam->getVariance());
}
}
if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
newTypeParam->getUnderlyingType()))
continue;
if (newTypeParam->hasExplicitBound()) {
SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
->getTypeLoc().getSourceRange();
S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
<< newTypeParam->getUnderlyingType()
<< newTypeParam->getDeclName()
<< prevTypeParam->hasExplicitBound()
<< prevTypeParam->getUnderlyingType()
<< (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
<< prevTypeParam->getDeclName()
<< FixItHint::CreateReplacement(
newBoundRange,
prevTypeParam->getUnderlyingType().getAsString(
S.Context.getPrintingPolicy()));
S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
<< prevTypeParam->getDeclName();
S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
continue;
}
if (newContext == TypeParamListContext::ForwardDeclaration ||
newContext == TypeParamListContext::Definition) {
SourceLocation insertionLoc
= S.getLocForEndOfToken(newTypeParam->getLocation());
std::string newCode
= " : " + prevTypeParam->getUnderlyingType().getAsString(
S.Context.getPrintingPolicy());
S.Diag(newTypeParam->getLocation(),
diag::err_objc_type_param_bound_missing)
<< prevTypeParam->getUnderlyingType()
<< newTypeParam->getDeclName()
<< (newContext == TypeParamListContext::ForwardDeclaration)
<< FixItHint::CreateInsertion(insertionLoc, newCode);
S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
<< prevTypeParam->getDeclName();
}
S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
}
return false;
}
ObjCInterfaceDecl *Sema::ActOnStartClassInterface(
Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *SuperName, SourceLocation SuperLoc,
ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList) {
assert(ClassName && "Missing class identifier");
NamedDecl *PrevDecl =
LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
forRedeclarationInCurContext());
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();
}
if (PrevIDecl) {
if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
if (typeParamList) {
if (checkTypeParamListConsistency(*this, prevTypeParamList,
typeParamList,
TypeParamListContext::Definition)) {
typeParamList = nullptr;
}
} else {
Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
<< ClassName;
Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
<< ClassName;
SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
for (auto typeParam : *prevTypeParamList) {
clonedTypeParams.push_back(
ObjCTypeParamDecl::Create(
Context,
CurContext,
typeParam->getVariance(),
SourceLocation(),
typeParam->getIndex(),
SourceLocation(),
typeParam->getIdentifier(),
SourceLocation(),
Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
}
typeParamList = ObjCTypeParamList::create(Context,
SourceLocation(),
clonedTypeParams,
SourceLocation());
}
}
}
ObjCInterfaceDecl *IDecl
= ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
typeParamList, 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();
}
}
ProcessDeclAttributeList(TUScope, IDecl, AttrList);
AddPragmaAttributes(TUScope, IDecl);
if (PrevIDecl)
mergeDeclAttributes(IDecl, PrevIDecl);
PushOnScopeChains(IDecl, TUScope);
if (!IDecl->hasDefinition())
IDecl->startDefinition();
if (SuperName) {
ContextRAII SavedContext(*this, IDecl);
ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
ClassName, ClassLoc,
SuperName, SuperLoc, SuperTypeArgs,
SuperTypeArgsRange);
} else { IDecl->setEndOfDefinitionLoc(ClassLoc);
}
if (NumProtoRefs) {
diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
NumProtoRefs, ProtoLocs);
IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
ProtoLocs, Context);
IDecl->setEndOfDefinitionLoc(EndProtoLoc);
}
CheckObjCDeclScope(IDecl);
ActOnObjCContainerStartDefinition(IDecl);
return IDecl;
}
void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
SmallVectorImpl<SourceLocation> &ProtocolLocs,
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>()) {
ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
}
}
}
Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
IdentifierInfo *AliasName,
SourceLocation AliasLocation,
IdentifierInfo *ClassName,
SourceLocation ClassLocation) {
NamedDecl *ADecl =
LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
forRedeclarationInCurContext());
if (ADecl) {
Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Diag(ADecl->getLocation(), diag::note_previous_declaration);
return nullptr;
}
NamedDecl *CDeclU =
LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
forRedeclarationInCurContext());
if (const TypedefNameDecl *TDecl =
dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
QualType T = TDecl->getUnderlyingType();
if (T->isObjCObjectType()) {
if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
ClassName = IDecl->getIdentifier();
CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
LookupOrdinaryName,
forRedeclarationInCurContext());
}
}
}
ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
if (!CDecl) {
Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
if (CDeclU)
Diag(CDeclU->getLocation(), diag::note_previous_declaration);
return nullptr;
}
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;
}
ObjCProtocolDecl *Sema::ActOnStartProtocolInterface(
SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList) {
bool err = false;
assert(ProtocolName && "Missing protocol identifier");
ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
forRedeclarationInCurContext());
ObjCProtocolDecl *PDecl = nullptr;
if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
Diag(Def->getLocation(), diag::note_previous_definition);
PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
ProtocolLoc, AtProtoInterfaceLoc,
nullptr);
if (getLangOpts().Modules)
PushOnScopeChains(PDecl, TUScope);
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();
}
ProcessDeclAttributeList(TUScope, PDecl, AttrList);
AddPragmaAttributes(TUScope, PDecl);
if (PrevDecl)
mergeDeclAttributes(PDecl, PrevDecl);
if (!err && NumProtoRefs ) {
diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
NumProtoRefs, ProtoLocs);
PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
ProtoLocs, Context);
}
CheckObjCDeclScope(PDecl);
ActOnObjCContainerStartDefinition(PDecl);
return PDecl;
}
static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
ObjCProtocolDecl *&UndefinedProtocol) {
if (!PDecl->hasDefinition() ||
!PDecl->getDefinition()->isUnconditionallyVisible()) {
UndefinedProtocol = PDecl;
return true;
}
for (auto *PI : PDecl->protocols())
if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
UndefinedProtocol = PI;
return true;
}
return false;
}
void
Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
ArrayRef<IdentifierLocPair> ProtocolId,
SmallVectorImpl<Decl *> &Protocols) {
for (const IdentifierLocPair &Pair : ProtocolId) {
ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
if (!PDecl) {
DeclFilterCCC<ObjCProtocolDecl> CCC{};
TypoCorrection Corrected = CorrectTypo(
DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
TUScope, nullptr, CCC, CTK_ErrorRecovery);
if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
<< Pair.first);
}
if (!PDecl) {
Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
continue;
}
if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
PDecl = PDecl->getDefinition();
if (!ForObjCContainer) {
(void)DiagnoseUseOfDecl(PDecl, Pair.second);
}
ObjCProtocolDecl *UndefinedProtocol;
if (WarnOnDeclarations &&
NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
<< UndefinedProtocol;
}
Protocols.push_back(PDecl);
}
}
namespace {
class ObjCTypeArgOrProtocolValidatorCCC final
: public CorrectionCandidateCallback {
ASTContext &Context;
Sema::LookupNameKind LookupKind;
public:
ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
Sema::LookupNameKind lookupKind)
: Context(context), LookupKind(lookupKind) { }
bool ValidateCandidate(const TypoCorrection &candidate) override {
if (LookupKind != Sema::LookupOrdinaryName) {
if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
return true;
}
if (LookupKind != Sema::LookupObjCProtocolName) {
if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
return false;
auto type = Context.getTypeDeclType(typeDecl);
if (type->isObjCObjectPointerType() ||
type->isBlockPointerType() ||
type->isDependentType() ||
type->isObjCObjectType())
return true;
return false;
}
if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
return true;
return false;
}
return false;
}
std::unique_ptr<CorrectionCandidateCallback> clone() override {
return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
}
};
}
void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
SourceLocation ProtocolLoc,
IdentifierInfo *TypeArgId,
SourceLocation TypeArgLoc,
bool SelectProtocolFirst) {
Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
<< SelectProtocolFirst << TypeArgId << ProtocolId
<< SourceRange(ProtocolLoc);
}
void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
Scope *S,
ParsedType baseType,
SourceLocation lAngleLoc,
ArrayRef<IdentifierInfo *> identifiers,
ArrayRef<SourceLocation> identifierLocs,
SourceLocation rAngleLoc,
SourceLocation &typeArgsLAngleLoc,
SmallVectorImpl<ParsedType> &typeArgs,
SourceLocation &typeArgsRAngleLoc,
SourceLocation &protocolLAngleLoc,
SmallVectorImpl<Decl *> &protocols,
SourceLocation &protocolRAngleLoc,
bool warnOnIncompleteProtocols) {
unsigned numProtocolsResolved = 0;
auto resolvedAsProtocols = [&] {
assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
ObjCInterfaceDecl *baseClass = nullptr;
QualType base = GetTypeFromParser(baseType, nullptr);
bool allAreTypeNames = false;
SourceLocation firstClassNameLoc;
if (!base.isNull()) {
if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
baseClass = objcObjectType->getInterface();
if (baseClass) {
if (auto typeParams = baseClass->getTypeParamList()) {
if (typeParams->size() == numProtocolsResolved) {
allAreTypeNames = true;
}
}
}
}
}
for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
ObjCProtocolDecl *&proto
= reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
if (!warnOnIncompleteProtocols) {
(void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
}
if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
proto = proto->getDefinition();
ObjCProtocolDecl *forwardDecl = nullptr;
if (warnOnIncompleteProtocols &&
NestedProtocolHasNoDefinition(proto, forwardDecl)) {
Diag(identifierLocs[i], diag::warn_undef_protocolref)
<< proto->getDeclName();
Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
<< forwardDecl;
}
if (allAreTypeNames) {
if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
LookupOrdinaryName)) {
if (isa<ObjCInterfaceDecl>(decl)) {
if (firstClassNameLoc.isInvalid())
firstClassNameLoc = identifierLocs[i];
} else if (!isa<TypeDecl>(decl)) {
allAreTypeNames = false;
}
} else {
allAreTypeNames = false;
}
}
}
if (allAreTypeNames && firstClassNameLoc.isValid()) {
llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
Context.CollectInheritedProtocols(baseClass, knownProtocols);
bool allProtocolsDeclared = true;
for (auto proto : protocols) {
if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
allProtocolsDeclared = false;
break;
}
}
if (allProtocolsDeclared) {
Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
<< baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
<< FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
" *");
}
}
protocolLAngleLoc = lAngleLoc;
protocolRAngleLoc = rAngleLoc;
assert(protocols.size() == identifierLocs.size());
};
for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
protocols.push_back(proto);
if (proto)
++numProtocolsResolved;
}
if (numProtocolsResolved == identifiers.size())
return resolvedAsProtocols();
typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
SmallVector<TypeOrClassDecl, 4> typeDecls;
unsigned numTypeDeclsResolved = 0;
for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
LookupOrdinaryName);
if (!decl) {
typeDecls.push_back(TypeOrClassDecl());
continue;
}
if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
typeDecls.push_back(typeDecl);
++numTypeDeclsResolved;
continue;
}
if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
typeDecls.push_back(objcClass);
++numTypeDeclsResolved;
continue;
}
typeDecls.push_back(TypeOrClassDecl());
}
AttributeFactory attrFactory;
auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
-> TypeResult {
DeclSpec DS(attrFactory);
const char* prevSpec; unsigned diagID; QualType type;
if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
type = Context.getTypeDeclType(actualTypeDecl);
else
type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
parsedType, Context.getPrintingPolicy());
DS.SetRangeStart(loc);
DS.SetRangeEnd(loc);
Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
if (type->getAs<ObjCInterfaceType>()) {
SourceLocation starLoc = getLocForEndOfToken(loc);
D.AddTypeInfo(DeclaratorChunk::getPointer(0, starLoc,
SourceLocation(),
SourceLocation(),
SourceLocation(),
SourceLocation(),
SourceLocation()),
starLoc);
Diag(loc, diag::err_objc_type_arg_missing_star)
<< type
<< FixItHint::CreateInsertion(starLoc, " *");
}
return ActOnTypeName(S, D);
};
auto resolvedAsTypeDecls = [&] {
protocols.clear();
assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
if (!type.isUsable()) {
typeArgs.clear();
return;
}
typeArgs.push_back(type.get());
}
typeArgsLAngleLoc = lAngleLoc;
typeArgsRAngleLoc = rAngleLoc;
};
if (numTypeDeclsResolved == identifiers.size())
return resolvedAsTypeDecls();
LookupNameKind lookupKind = LookupAnyName;
for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
if (protocols[i] || typeDecls[i]) {
if (lookupKind == LookupAnyName) {
if (protocols[i] && typeDecls[i])
continue;
lookupKind = protocols[i] ? LookupObjCProtocolName
: LookupOrdinaryName;
continue;
}
if (lookupKind == LookupObjCProtocolName && protocols[i])
continue;
if (lookupKind == LookupOrdinaryName && typeDecls[i])
continue;
DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
identifiers[i], identifierLocs[i],
protocols[i] != nullptr);
protocols.clear();
typeArgs.clear();
return;
}
ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
TypoCorrection corrected =
CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
if (corrected) {
if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
diagnoseTypo(corrected,
PDiag(diag::err_undeclared_protocol_suggest)
<< identifiers[i]);
lookupKind = LookupObjCProtocolName;
protocols[i] = proto;
++numProtocolsResolved;
continue;
}
if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
diagnoseTypo(corrected,
PDiag(diag::err_unknown_typename_suggest)
<< identifiers[i]);
lookupKind = LookupOrdinaryName;
typeDecls[i] = typeDecl;
++numTypeDeclsResolved;
continue;
}
if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
diagnoseTypo(corrected,
PDiag(diag::err_unknown_type_or_class_name_suggest)
<< identifiers[i] << true);
lookupKind = LookupOrdinaryName;
typeDecls[i] = objcClass;
++numTypeDeclsResolved;
continue;
}
}
Diag(identifierLocs[i],
(lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
: lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
: diag::err_unknown_typename))
<< identifiers[i];
protocols.clear();
typeArgs.clear();
return;
}
if (numProtocolsResolved == identifiers.size())
return resolvedAsProtocols();
assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
return resolvedAsTypeDecls();
}
void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
ObjCInterfaceDecl *ID) {
if (!ID)
return;
llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
for (auto *MD : ID->methods())
MethodMap[MD->getSelector()] = MD;
if (MethodMap.empty())
return;
for (const auto *Method : CAT->methods()) {
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,
ArrayRef<IdentifierLocPair> IdentList,
const ParsedAttributesView &attrList) {
SmallVector<Decl *, 8> DeclsInGroup;
for (const IdentifierLocPair &IdentPair : IdentList) {
IdentifierInfo *Ident = IdentPair.first;
ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
forRedeclarationInCurContext());
ObjCProtocolDecl *PDecl
= ObjCProtocolDecl::Create(Context, CurContext, Ident,
IdentPair.second, AtProtocolLoc,
PrevDecl);
PushOnScopeChains(PDecl, TUScope);
CheckObjCDeclScope(PDecl);
ProcessDeclAttributeList(TUScope, PDecl, attrList);
AddPragmaAttributes(TUScope, PDecl);
if (PrevDecl)
mergeDeclAttributes(PDecl, PrevDecl);
DeclsInGroup.push_back(PDecl);
}
return BuildDeclaratorGroup(DeclsInGroup);
}
ObjCCategoryDecl *Sema::ActOnStartCategoryInterface(
SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
Decl *const *ProtoRefs, unsigned NumProtoRefs,
const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
const ParsedAttributesView &AttrList) {
ObjCCategoryDecl *CDecl;
ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
if (!IDecl
|| RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
diag::err_category_forward_interface,
CategoryName == nullptr)) {
CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
ClassLoc, CategoryLoc, CategoryName,
IDecl, typeParamList);
CDecl->setInvalidDecl();
CurContext->addDecl(CDecl);
if (!IDecl)
Diag(ClassLoc, diag::err_undef_interface) << ClassName;
ActOnObjCContainerStartDefinition(CDecl);
return 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);
}
}
if (typeParamList) {
if (auto prevTypeParamList = IDecl->getTypeParamList()) {
if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
CategoryName
? TypeParamListContext::Category
: TypeParamListContext::Extension))
typeParamList = nullptr;
} else {
Diag(typeParamList->getLAngleLoc(),
diag::err_objc_parameterized_category_nonclass)
<< (CategoryName != nullptr)
<< ClassName
<< typeParamList->getSourceRange();
typeParamList = nullptr;
}
}
CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
ClassLoc, CategoryLoc, CategoryName, IDecl,
typeParamList);
CurContext->addDecl(CDecl);
ProcessDeclAttributeList(TUScope, CDecl, AttrList);
AddPragmaAttributes(TUScope, CDecl);
if (NumProtoRefs) {
diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
NumProtoRefs, ProtoLocs);
CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
ProtoLocs, Context);
if (CDecl->IsClassExtension())
IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
NumProtoRefs, Context);
}
CheckObjCDeclScope(CDecl);
ActOnObjCContainerStartDefinition(CDecl);
return CDecl;
}
ObjCCategoryImplDecl *Sema::ActOnStartCategoryImplementation(
SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
const ParsedAttributesView &Attrs) {
ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
ObjCCategoryDecl *CatIDecl = nullptr;
if (IDecl && IDecl->hasDefinition()) {
CatIDecl = IDecl->FindCategoryDeclaration(CatName);
if (!CatIDecl) {
CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
ClassLoc, CatLoc,
CatName, IDecl,
nullptr);
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();
}
ProcessDeclAttributeList(TUScope, CDecl, Attrs);
AddPragmaAttributes(TUScope, CDecl);
CurContext->addDecl(CDecl);
if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
Diag(ClassLoc, diag::err_objc_runtime_visible_category)
<< IDecl->getDeclName();
}
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, CatIDecl,
CDecl->getLocation());
}
}
CheckObjCDeclScope(CDecl);
ActOnObjCContainerStartDefinition(CDecl);
return CDecl;
}
ObjCImplementationDecl *Sema::ActOnStartClassImplementation(
SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
SourceLocation SuperClassLoc, const ParsedAttributesView &Attrs) {
ObjCInterfaceDecl *IDecl = nullptr;
NamedDecl *PrevDecl
= LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
forRedeclarationInCurContext());
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 CCC{};
TypoCorrection Corrected =
CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
diagnoseTypo(Corrected,
PDiag(diag::warn_undef_interface_suggest) << ClassName,
false);
} else {
Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
}
}
ObjCInterfaceDecl *SDecl = nullptr;
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 = nullptr;
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, nullptr,
nullptr, ClassLoc,
true);
AddPragmaAttributes(TUScope, IDecl);
IDecl->startDefinition();
if (SDecl) {
IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
Context.getObjCInterfaceType(SDecl),
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);
ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
AddPragmaAttributes(TUScope, IMPDecl);
if (CheckObjCDeclScope(IMPDecl)) {
ActOnObjCContainerStartDefinition(IMPDecl);
return 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, IDecl, IMPDecl->getLocation());
}
if (IDecl->getSuperClass() &&
IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
<< IDecl->getDeclName()
<< IDecl->getSuperClass()->getDeclName();
}
ActOnObjCContainerStartDefinition(IMPDecl);
return 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);
}
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);
if (!LangOpts.ObjCRuntime.isFragile())
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 (const auto *CDecl : IDecl->visible_extensions()) {
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()->getBeginLoc(),
diag::err_conflicting_ivar_bitwidth)
<< ImplIvar->getIdentifier();
Diag(ClsIvar->getBitWidth()->getBeginLoc(),
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, ObjCImplDecl *Impl,
ObjCMethodDecl *method, bool &IncompleteImpl,
unsigned DiagID,
NamedDecl *NeededFor = nullptr) {
if (method->getAvailability() == AR_Unavailable)
return;
{
const Sema::SemaDiagnosticBuilder &B = S.Diag(Impl->getLocation(), DiagID);
B << method;
if (NeededFor)
B << NeededFor;
std::string FixItStr;
llvm::raw_string_ostream Out(FixItStr);
method->print(Out, Impl->getASTContext().getPrintingPolicy());
Out << " {\n}\n\n";
SourceLocation Loc = Impl->getAtEndRange().getBegin();
B << FixItHint::CreateInsertion(Loc, FixItStr);
}
SourceLocation MethodLoc = method->getBeginLoc();
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(A, B, false);
}
return Context.canAssignObjCInterfaces(A, B);
}
static SourceRange getTypeRange(TypeSourceInfo *TSI) {
return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
}
static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
Decl::ObjCDeclQualifier y) {
return (x & ~Decl::OBJC_TQ_CSNullability) !=
(y & ~Decl::OBJC_TQ_CSNullability);
}
static bool CheckMethodOverrideReturn(Sema &S,
ObjCMethodDecl *MethodImpl,
ObjCMethodDecl *MethodDecl,
bool IsProtocolMethodDecl,
bool IsOverridingMode,
bool Warn) {
if (IsProtocolMethodDecl &&
objcModifiersConflict(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()
<< MethodImpl->getReturnTypeSourceRange();
S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
<< MethodDecl->getReturnTypeSourceRange();
}
else
return false;
}
if (Warn && IsOverridingMode &&
!isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
!S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
MethodDecl->getReturnType(),
false)) {
auto nullabilityMethodImpl =
*MethodImpl->getReturnType()->getNullability(S.Context);
auto nullabilityMethodDecl =
*MethodDecl->getReturnType()->getNullability(S.Context);
S.Diag(MethodImpl->getLocation(),
diag::warn_conflicting_nullability_attr_overriding_ret_types)
<< DiagNullabilityKind(
nullabilityMethodImpl,
((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0))
<< DiagNullabilityKind(
nullabilityMethodDecl,
((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0));
S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
}
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()
<< MethodImpl->getReturnTypeSourceRange();
S.Diag(MethodDecl->getLocation(), IsOverridingMode
? diag::note_previous_declaration
: diag::note_previous_definition)
<< MethodDecl->getReturnTypeSourceRange();
return false;
}
static bool CheckMethodOverrideParam(Sema &S,
ObjCMethodDecl *MethodImpl,
ObjCMethodDecl *MethodDecl,
ParmVarDecl *ImplVar,
ParmVarDecl *IfaceVar,
bool IsProtocolMethodDecl,
bool IsOverridingMode,
bool Warn) {
if (IsProtocolMethodDecl &&
objcModifiersConflict(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 (Warn && IsOverridingMode &&
!isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
!S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
S.Diag(ImplVar->getLocation(),
diag::warn_conflicting_nullability_attr_overriding_param_types)
<< DiagNullabilityKind(
*ImplTy->getNullability(S.Context),
((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0))
<< DiagNullabilityKind(
*IfaceTy->getNullability(S.Context),
((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
!= 0));
S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
}
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_initialize:
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 std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
ProtocolNameSet &PNS) {
if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
PNS.insert(PDecl->getIdentifier());
for (const auto *PI : PDecl->protocols())
findProtocolsWithExplicitImpls(PI, PNS);
}
static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
ProtocolNameSet &PNS) {
if (!Super)
return;
for (const auto *I : Super->all_referenced_protocols())
findProtocolsWithExplicitImpls(I, PNS);
findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
}
static void CheckProtocolMethodDefs(
Sema &S, ObjCImplDecl *Impl, 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 = nullptr;
if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
if (!ProtocolsExplictImpl) {
ProtocolsExplictImpl.reset(new ProtocolNameSet);
findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
}
if (ProtocolsExplictImpl->contains(PDecl->getIdentifier()))
return;
Super = nullptr;
}
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 (auto *method : PDecl->instance_methods()) {
if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
!method->isPropertyAccessor() &&
!InsMap.count(method->getSelector()) &&
(!Super || !Super->lookupMethod(method->getSelector(),
true ,
false ,
true ,
nullptr ))) {
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.isIgnored(DIAG, Impl->getLocation())) {
WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
}
}
}
for (auto *method : PDecl->class_methods()) {
if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
!ClsMap.count(method->getSelector()) &&
(!Super || !Super->lookupMethod(method->getSelector(),
false ,
false ,
true ,
nullptr ))) {
if (C && IDecl->lookupMethod(method->getSelector(),
false ,
true ,
false ))
continue;
unsigned DIAG = diag::warn_unimplemented_protocol_method;
if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
}
}
}
for (auto *PI : PDecl->protocols())
CheckProtocolMethodDefs(S, Impl, 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 (auto *I : CDecl->instance_methods()) {
if (!InsMapSeen.insert(I->getSelector()).second)
continue;
if (!I->isPropertyAccessor() &&
!InsMap.count(I->getSelector())) {
if (ImmediateClass)
WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
diag::warn_undef_method_impl);
continue;
} else {
ObjCMethodDecl *ImpMethodDecl =
IMPDecl->getInstanceMethod(I->getSelector());
assert(CDecl->getInstanceMethod(I->getSelector(), true) &&
"Expected to find the method through lookup as well");
if (ImpMethodDecl) {
if (ImpMethodDecl->isSynthesizedAccessorStub())
continue;
if (!WarnCategoryMethodImpl)
WarnConflictingTypedMethods(ImpMethodDecl, I,
isa<ObjCProtocolDecl>(CDecl));
else if (!I->isPropertyAccessor())
WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
}
}
}
for (auto *I : CDecl->class_methods()) {
if (!ClsMapSeen.insert(I->getSelector()).second)
continue;
if (!I->isPropertyAccessor() &&
!ClsMap.count(I->getSelector())) {
if (ImmediateClass)
WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
diag::warn_undef_method_impl);
} else {
ObjCMethodDecl *ImpMethodDecl =
IMPDecl->getClassMethod(I->getSelector());
assert(CDecl->getClassMethod(I->getSelector(), true) &&
"Expected to find the method through lookup as well");
if (ImpMethodDecl) {
if (ImpMethodDecl->isSynthesizedAccessorStub())
continue;
if (!WarnCategoryMethodImpl)
WarnConflictingTypedMethods(ImpMethodDecl, I,
isa<ObjCProtocolDecl>(CDecl));
else if (!I->isPropertyAccessor())
WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
}
}
}
if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
for (auto *PI : PD->protocols())
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl, PI, IncompleteImpl, false,
WarnCategoryMethodImpl);
}
if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
if (!WarnCategoryMethodImpl) {
for (auto *Cat : I->visible_categories())
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl, Cat, IncompleteImpl,
ImmediateClass && Cat->IsClassExtension(),
WarnCategoryMethodImpl);
} else {
for (auto *Ext : I->visible_extensions())
MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
IMPDecl, Ext, IncompleteImpl, false,
WarnCategoryMethodImpl);
}
for (auto *PI : I->all_referenced_protocols())
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 (const auto *I : CatIMPDecl->instance_methods()) {
Selector Sel = I->getSelector();
if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
continue;
InsMap.insert(Sel);
}
for (const auto *I : CatIMPDecl->class_methods()) {
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 (const auto *I : IMPDecl->instance_methods())
InsMap.insert(I->getSelector());
for (const auto *PImpl : IMPDecl->property_impls()) {
if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
continue;
const auto *P = PImpl->getPropertyDecl();
if (!P) continue;
InsMap.insert(P->getGetterName());
if (!P->getSetterName().isNull())
InsMap.insert(P->getSetterName());
}
if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
LangOpts.ObjCRuntime.isNonFragile() &&
!IDecl->isObjCRequiresPropertyDefs();
DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
}
diagnoseNullResettableSynthesizedSetters(IMPDecl);
SelectorSet ClsMap;
for (const auto *I : IMPDecl->class_methods())
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 (auto *PI : I->all_referenced_protocols())
CheckProtocolMethodDefs(*this, IMPDecl, PI, IncompleteImpl, InsMap,
ClsMap, I, ExplicitImplProtocols);
} else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
if (!C->IsClassExtension()) {
for (auto *P : C->protocols())
CheckProtocolMethodDefs(*this, IMPDecl, P, 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,
ArrayRef<ObjCTypeParamList *> TypeParamLists,
unsigned NumElts) {
SmallVector<Decl *, 8> DeclsInGroup;
for (unsigned i = 0; i != NumElts; ++i) {
NamedDecl *PrevDecl
= LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
LookupOrdinaryName, forRedeclarationInCurContext());
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();
}
ObjCTypeParamList *TypeParams = TypeParamLists[i];
if (PrevIDecl && TypeParams) {
if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
if (checkTypeParamListConsistency(
*this, PrevTypeParams, TypeParams,
TypeParamListContext::ForwardDeclaration)) {
TypeParams = nullptr;
}
} else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
<< ClassName
<< TypeParams->getSourceRange();
Diag(Def->getLocation(), diag::note_defined_here)
<< ClassName;
TypeParams = nullptr;
}
}
ObjCInterfaceDecl *IDecl
= ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
ClassName, TypeParams, PrevIDecl,
IdentLocs[i]);
IDecl->setAtEndRange(IdentLocs[i]);
if (PrevIDecl)
mergeDeclAttributes(IDecl, PrevIDecl);
PushOnScopeChains(IDecl, TUScope);
CheckObjCDeclScope(IDecl);
DeclsInGroup.push_back(IDecl);
}
return BuildDeclaratorGroup(DeclsInGroup);
}
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;
TypeInfo LeftTI = Context.getTypeInfo(left);
TypeInfo RightTI = Context.getTypeInfo(right);
if (LeftTI.Width != RightTI.Width)
return false;
if (LeftTI.Align != RightTI.Align)
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;
TypeInfo LeftTI = Context.getTypeInfo(lt);
TypeInfo RightTI = Context.getTypeInfo(rt);
if (LeftTI.Width != RightTI.Width)
return false;
if (LeftTI.Align != RightTI.Align)
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->isUnconditionallyVisible() || !right->isUnconditionallyVisible())
return false;
if (left->isDirectMethod() != right->isDirectMethod())
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;
}
static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
ObjCMethodDecl *MethodInList) {
auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
auto *MethodInListProtocol =
dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
if ((MethodProtocol && !MethodInListProtocol) ||
(!MethodProtocol && MethodInListProtocol))
return false;
if (MethodProtocol && MethodInListProtocol)
return true;
ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
ObjCInterfaceDecl *MethodInListInterface =
MethodInList->getClassInterface();
return MethodInterface == MethodInListInterface;
}
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->getMethod() == nullptr) {
List->setMethod(Method);
List->setNext(nullptr);
return;
}
ObjCMethodList *Previous = List;
ObjCMethodList *ListWithSameDeclaration = nullptr;
for (; List; Previous = List, List = List->getNext()) {
if (getLangOpts().isCompilingModule())
continue;
bool SameDeclaration = MatchTwoMethodDeclarations(Method,
List->getMethod());
if (!SameDeclaration ||
!isMethodContextSameForKindofLookup(Method, List->getMethod())) {
if (!Method->isDefined())
List->setHasMoreThanOneDecl(true);
if (Method->isDeprecated() && SameDeclaration &&
!ListWithSameDeclaration && !List->getMethod()->isDeprecated())
ListWithSameDeclaration = List;
if (Method->isUnavailable() && SameDeclaration &&
!ListWithSameDeclaration &&
List->getMethod()->getAvailability() < AR_Deprecated)
ListWithSameDeclaration = List;
continue;
}
ObjCMethodDecl *PrevObjCMethod = List->getMethod();
if (Method->isDefined())
PrevObjCMethod->setDefined(true);
else {
List->setHasMoreThanOneDecl(true);
}
if (Method->isDeprecated()) {
if (!PrevObjCMethod->isDeprecated())
List->setMethod(Method);
}
if (Method->isUnavailable()) {
if (PrevObjCMethod->getAvailability() < AR_Deprecated)
List->setMethod(Method);
}
return;
}
ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
if (ListWithSameDeclaration) {
auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
ListWithSameDeclaration->setMethod(Method);
ListWithSameDeclaration->setNext(List);
return;
}
Previous->setNext(new (Mem) ObjCMethodList(Method));
}
void Sema::ReadMethodPool(Selector Sel) {
assert(ExternalSource && "We need an external AST source");
ExternalSource->ReadMethodPool(Sel);
}
void Sema::updateOutOfDateSelector(Selector Sel) {
if (!ExternalSource)
return;
ExternalSource->updateOutOfDateSelector(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(),
GlobalMethodPool::Lists()))
.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;
if (chosen->isDirectMethod() != other->isDirectMethod())
return false;
Selector sel = chosen->getSelector();
if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
return false;
return (chosen->getReturnType()->isIntegerType());
}
static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
const ObjCObjectType *TypeBound) {
if (!TypeBound)
return true;
if (TypeBound->isObjCId())
return true;
auto *BoundInterface = TypeBound->getInterface();
assert(BoundInterface && "unexpected object type!");
auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
if (MethodProtocol) {
return true;
}
if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
return MethodInterface == BoundInterface ||
MethodInterface->isSuperClassOf(BoundInterface) ||
BoundInterface->isSuperClassOf(MethodInterface);
}
llvm_unreachable("unknown method context");
}
bool Sema::CollectMultipleMethodsInGlobalPool(
Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
bool InstanceFirst, bool CheckTheOther,
const ObjCObjectType *TypeBound) {
if (ExternalSource)
ReadMethodPool(Sel);
GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
if (Pos == MethodPool.end())
return false;
ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
Pos->second.second;
for (ObjCMethodList *M = &MethList; M; M = M->getNext())
if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
Methods.push_back(M->getMethod());
}
if (!Methods.empty())
return Methods.size() > 1;
if (!CheckTheOther)
return false;
ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
Pos->second.first;
for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
Methods.push_back(M->getMethod());
}
return Methods.size() > 1;
}
bool Sema::AreMultipleMethodsInGlobalPool(
Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
FilteredMethods.push_back(BestMethod);
for (auto *M : Methods)
if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
FilteredMethods.push_back(M);
if (FilteredMethods.size() > 1)
DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
receiverIdOrClass);
GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
if (Pos == MethodPool.end())
return true;
ObjCMethodList &MethList =
BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
return MethList.hasMoreThanOneDecl();
}
ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
bool receiverIdOrClass,
bool instance) {
if (ExternalSource)
ReadMethodPool(Sel);
GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
if (Pos == MethodPool.end())
return nullptr;
ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
SmallVector<ObjCMethodDecl *, 4> Methods;
for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
if (M->getMethod() && M->getMethod()->isUnconditionallyVisible())
return M->getMethod();
}
return nullptr;
}
void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
Selector Sel, SourceRange R,
bool receiverIdOrClass) {
bool issueDiagnostic = false, issueError = false;
bool strictSelectorMatch =
receiverIdOrClass &&
!Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
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]->getBeginLoc(),
issueError ? diag::note_possibility : diag::note_using)
<< Methods[0]->getSourceRange();
for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
<< Methods[I]->getSourceRange();
}
}
}
ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
if (Pos == MethodPool.end())
return nullptr;
GlobalMethodPool::Lists &Methods = Pos->second;
for (const ObjCMethodList *Method = &Methods.first; Method;
Method = Method->getNext())
if (Method->getMethod() &&
(Method->getMethod()->isDefined() ||
Method->getMethod()->isPropertyAccessor()))
return Method->getMethod();
for (const ObjCMethodList *Method = &Methods.second; Method;
Method = Method->getNext())
if (Method->getMethod() &&
(Method->getMethod()->isDefined() ||
Method->getMethod()->isPropertyAccessor()))
return Method->getMethod();
return nullptr;
}
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) !=
nullptr;
}
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 nullptr;
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 nullptr;
for (GlobalMethodPool::iterator b = MethodPool.begin(),
e = MethodPool.end(); b != e; b++) {
for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
if (M->getMethod() &&
(M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
(M->getMethod()->getSelector() != Sel)) {
if (ObjectIsId)
Methods.push_back(M->getMethod());
else if (!ObjectIsClass &&
HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
ObjectType))
Methods.push_back(M->getMethod());
}
for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
if (M->getMethod() &&
(M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
(M->getMethod()->getSelector() != Sel)) {
if (ObjectIsClass)
Methods.push_back(M->getMethod());
else if (!ObjectIsId &&
HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
ObjectType))
Methods.push_back(M->getMethod());
}
}
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] : nullptr;
}
void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
ObjCInterfaceDecl *SID) {
for (auto *Ivar : ID->ivars()) {
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();
}
}
}
}
static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
if (S.getLangOpts().ObjCWeak) return;
for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
ivar; ivar = ivar->getNextIvar()) {
if (ivar->isInvalidDecl()) continue;
if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
if (S.getLangOpts().ObjCWeakRuntime) {
S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
} else {
S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
}
}
}
}
static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
ObjCInterfaceDecl *ID) {
if (!S.getLangOpts().ObjCAutoRefCount)
return;
for (auto ivar = ID->all_declared_ivar_begin(); ivar;
ivar = ivar->getNextIvar()) {
if (ivar->isInvalidDecl())
continue;
QualType IvarTy = ivar->getType();
if (IvarTy->isIncompleteArrayType() &&
(IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
IvarTy->isObjCLifetimeType()) {
S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
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 (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
return Sema::OCK_ClassExtension;
return Sema::OCK_Category;
case Decl::ObjCImplementation:
return Sema::OCK_Implementation;
case Decl::ObjCCategoryImpl:
return Sema::OCK_CategoryImplementation;
default:
return Sema::OCK_None;
}
}
static bool IsVariableSizedType(QualType T) {
if (T->isIncompleteArrayType())
return true;
const auto *RecordTy = T->getAs<RecordType>();
return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
}
static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
ObjCInterfaceDecl *IntfDecl = nullptr;
ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
Ivars = IntfDecl->ivars();
} else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
IntfDecl = ImplDecl->getClassInterface();
Ivars = ImplDecl->ivars();
} else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
if (CategoryDecl->IsClassExtension()) {
IntfDecl = CategoryDecl->getClassInterface();
Ivars = CategoryDecl->ivars();
}
}
if (!isa<ObjCInterfaceDecl>(OCD)) {
for (auto ivar : Ivars) {
if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
<< ivar->getDeclName() << ivar->getType();
}
}
}
if (!IntfDecl)
return;
for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
ivar = ivar->getNextIvar()) {
if (ivar->isInvalidDecl() || !ivar->getNextIvar())
continue;
QualType IvarTy = ivar->getType();
bool IsInvalidIvar = false;
if (IvarTy->isIncompleteArrayType()) {
S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
<< ivar->getDeclName() << IvarTy
<< TTK_Class; IsInvalidIvar = true;
} else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
S.Diag(ivar->getLocation(),
diag::err_objc_variable_sized_type_not_at_end)
<< ivar->getDeclName() << IvarTy;
IsInvalidIvar = true;
}
}
if (IsInvalidIvar) {
S.Diag(ivar->getNextIvar()->getLocation(),
diag::note_next_ivar_declaration)
<< ivar->getNextIvar()->getSynthesize();
ivar->setInvalidDecl();
}
}
ObjCIvarDecl *FirstIvar =
(Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
while (SuperClass && SuperClass->ivar_empty())
SuperClass = SuperClass->getSuperClass();
if (SuperClass) {
auto IvarIter = SuperClass->ivar_begin();
std::advance(IvarIter, SuperClass->ivar_size() - 1);
const ObjCIvarDecl *LastIvar = *IvarIter;
if (IsVariableSizedType(LastIvar->getType())) {
S.Diag(FirstIvar->getLocation(),
diag::warn_superclass_variable_sized_type_not_at_end)
<< FirstIvar->getDeclName() << LastIvar->getDeclName()
<< LastIvar->getType() << SuperClass->getDeclName();
S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
<< LastIvar->getDeclName();
}
}
}
}
static void DiagnoseCategoryDirectMembersProtocolConformance(
Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
static void DiagnoseCategoryDirectMembersProtocolConformance(
Sema &S, ObjCCategoryDecl *CDecl,
const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
for (auto *PI : Protocols)
DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl);
}
static void DiagnoseCategoryDirectMembersProtocolConformance(
Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
PDecl = PDecl->getDefinition();
llvm::SmallVector<const Decl *, 4> DirectMembers;
const auto *IDecl = CDecl->getClassInterface();
for (auto *MD : PDecl->methods()) {
if (!MD->isPropertyAccessor()) {
if (const auto *CMD =
IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
if (CMD->isDirectMethod())
DirectMembers.push_back(CMD);
}
}
}
for (auto *PD : PDecl->properties()) {
if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
PD->getIdentifier(),
PD->isClassProperty()
? ObjCPropertyQueryKind::OBJC_PR_query_class
: ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
if (CPD->isDirectProperty())
DirectMembers.push_back(CPD);
}
}
if (!DirectMembers.empty()) {
S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
<< CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
for (const auto *MD : DirectMembers)
S.Diag(MD->getLocation(), diag::note_direct_member_here);
return;
}
DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl,
PDecl->protocols());
}
Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
ArrayRef<DeclGroupPtrTy> allTUVars) {
if (getObjCContainerKind() == Sema::OCK_None)
return nullptr;
assert(AtEnd.isValid() && "Invalid location for '@end'");
auto *OCD = cast<ObjCContainerDecl>(CurContext);
Decl *ClassDecl = OCD;
bool isInterfaceDeclKind =
isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
|| isa<ObjCProtocolDecl>(ClassDecl);
bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) {
for (auto PropImpl : OID->property_impls()) {
if (auto *Getter = PropImpl->getGetterMethodDecl())
if (Getter->isSynthesizedAccessorStub())
OID->addDecl(Getter);
if (auto *Setter = PropImpl->getSetterMethodDecl())
if (Setter->isSynthesizedAccessorStub())
OID->addDecl(Setter);
}
}
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);
}
DiagnoseCategoryDirectMembersProtocolConformance(*this, C, C->protocols());
}
if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
if (CDecl->getIdentifier())
for (auto *I : CDecl->properties())
ProcessPropertyDecl(I);
CDecl->setAtEndRange(AtEnd);
}
if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
IC->setAtEndRange(AtEnd);
if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
for (const auto *Ext : IDecl->visible_extensions()) {
for (const auto *Property : Ext->instance_properties()) {
if (const ObjCPropertyImplDecl *PIDecl
= IC->FindPropertyImplDecl(Property->getIdentifier(),
Property->getQueryKind()))
if (PIDecl->getPropertyImplementation()
== ObjCPropertyImplDecl::Dynamic)
continue;
for (const auto *Ext : IDecl->visible_extensions()) {
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);
DiagnoseWeakIvars(*this, IC);
DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
if (IDecl->getSuperClass() == nullptr) {
if (!HasRootClassAttr) {
SourceLocation DeclLoc(IDecl->getLocation());
SourceLocation SuperClassLoc(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 (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
Diag(Super->getLocation(), diag::note_class_declared);
}
}
if (IDecl->hasAttr<ObjCClassStubAttr>())
Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
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 auto *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 (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
}
DiagnoseVariableSizedIvars(*this, OCD);
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:
const ObjCMethodDecl *Method;
llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
bool Recursive;
public:
OverrideSearch(Sema &S, const ObjCMethodDecl *method) : 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;
}
const ObjCMethodList &list =
method->isInstanceMethod() ? it->second.first : it->second.second;
if (!list.getMethod()) return;
const ObjCContainerDecl *container
= cast<ObjCContainerDecl>(method->getDeclContext());
if (const ObjCCategoryDecl *Category =
dyn_cast<ObjCCategoryDecl>(container)) {
searchFromContainer(container);
if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
searchFromContainer(Interface);
} else {
searchFromContainer(container);
}
}
typedef decltype(Overridden)::iterator iterator;
iterator begin() const { return Overridden.begin(); }
iterator end() const { return Overridden.end(); }
private:
void searchFromContainer(const 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(const ObjCProtocolDecl *protocol) {
if (!protocol->hasDefinition())
return;
search(protocol->getReferencedProtocols());
}
void searchFrom(const ObjCCategoryDecl *category) {
search(category->getReferencedProtocols());
}
void searchFrom(const ObjCCategoryImplDecl *impl) {
if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
search(category);
if (ObjCInterfaceDecl *Interface = category->getClassInterface())
search(Interface);
} else if (const auto *Interface = impl->getClassInterface()) {
search(Interface);
}
}
void searchFrom(const ObjCInterfaceDecl *iface) {
if (!iface->hasDefinition())
return;
for (auto *Cat : iface->known_categories())
search(Cat);
if (ObjCInterfaceDecl *super = iface->getSuperClass())
search(super);
search(iface->getReferencedProtocols());
}
void searchFrom(const ObjCImplementationDecl *impl) {
if (const auto *Interface = impl->getClassInterface())
search(Interface);
}
void search(const ObjCProtocolList &protocols) {
for (const auto *Proto : protocols)
search(Proto);
}
void search(const ObjCContainerDecl *container) {
ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Method->isInstanceMethod(),
true);
if (meth) {
Overridden.insert(meth);
return;
}
Recursive = true;
searchFromContainer(container);
}
};
}
void Sema::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
ObjCMethodDecl *overridden) {
if (overridden->isDirectMethod()) {
const auto *attr = overridden->getAttr<ObjCDirectAttr>();
Diag(method->getLocation(), diag::err_objc_override_direct_method);
Diag(attr->getLocation(), diag::note_previous_declaration);
} else if (method->isDirectMethod()) {
const auto *attr = method->getAttr<ObjCDirectAttr>();
Diag(attr->getLocation(), diag::err_objc_direct_on_override)
<< isa<ObjCProtocolDecl>(overridden->getDeclContext());
Diag(overridden->getLocation(), diag::note_previous_declaration);
}
}
void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
ObjCInterfaceDecl *CurrentClass,
ResultTypeCompatibilityKind RTC) {
if (!ObjCMethod)
return;
OverrideSearch overrides(*this, ObjCMethod);
bool hasOverriddenMethodsInBaseOrProtocol = false;
for (ObjCMethodDecl *overridden : overrides) {
if (!hasOverriddenMethodsInBaseOrProtocol) {
if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
CurrentClass != overridden->getClassInterface() ||
overridden->isOverriding()) {
CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
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 (ObjCMethodDecl *SuperOverridden : overrides) {
if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
CurrentClass != SuperOverridden->getClassInterface()) {
CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
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);
}
static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
QualType type,
bool usesCSKeyword,
SourceLocation prevLoc,
QualType prevType,
bool prevUsesCSKeyword) {
auto nullability = type->getNullability(S.Context);
auto prevNullability = prevType->getNullability(S.Context);
if (nullability.has_value() == prevNullability.has_value()) {
if (!nullability)
return type;
if (*nullability == *prevNullability)
return type;
S.Diag(loc, diag::err_nullability_conflicting)
<< DiagNullabilityKind(*nullability, usesCSKeyword)
<< DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
return type;
}
if (nullability)
return type;
return S.Context.getAttributedType(
AttributedType::getNullabilityAttrKind(*prevNullability),
type, type);
}
static void mergeInterfaceMethodToImpl(Sema &S,
ObjCMethodDecl *method,
ObjCMethodDecl *prevMethod) {
if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
!method->hasAttr<ObjCRequiresSuperAttr>()) {
method->addAttr(
ObjCRequiresSuperAttr::CreateImplicit(S.Context,
method->getLocation()));
}
QualType newReturnType
= mergeTypeNullabilityForRedecl(
S, method->getReturnTypeSourceRange().getBegin(),
method->getReturnType(),
method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
prevMethod->getReturnTypeSourceRange().getBegin(),
prevMethod->getReturnType(),
prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
method->setReturnType(newReturnType);
unsigned numParams = method->param_size();
unsigned numPrevParams = prevMethod->param_size();
for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
ParmVarDecl *param = method->param_begin()[i];
ParmVarDecl *prevParam = prevMethod->param_begin()[i];
QualType newParamType
= mergeTypeNullabilityForRedecl(
S, param->getLocation(), param->getType(),
param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
prevParam->getLocation(), prevParam->getType(),
prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
param->setType(newParamType);
}
}
static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
const ObjCMethodDecl *Method) {
assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
llvm::Triple::x86 &&
"x86-specific check invoked for a different target");
SourceLocation Loc;
QualType T;
for (const ParmVarDecl *P : Method->parameters()) {
if (P->getType()->isVectorType()) {
Loc = P->getBeginLoc();
T = P->getType();
break;
}
}
if (Loc.isInvalid()) {
if (Method->getReturnType()->isVectorType()) {
Loc = Method->getReturnTypeSourceRange().getBegin();
T = Method->getReturnType();
} else
return;
}
const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
VersionTuple AcceptedInVersion;
if (Triple.getOS() == llvm::Triple::IOS)
AcceptedInVersion = VersionTuple(9);
else if (Triple.isMacOSX())
AcceptedInVersion = VersionTuple(10, 11);
else
return;
if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
AcceptedInVersion)
return;
SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
<< T << (Method->getReturnType()->isVectorType() ? 1
: 0)
<< (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
}
static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
CD->hasAttr<ObjCDirectMembersAttr>()) {
Method->addAttr(
ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
}
}
static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl,
ObjCMethodDecl *Method,
ObjCImplDecl *ImpDecl = nullptr) {
auto Sel = Method->getSelector();
bool isInstance = Method->isInstanceMethod();
bool diagnosed = false;
auto diagClash = [&](const ObjCMethodDecl *IMD) {
if (diagnosed || IMD->isImplicit())
return;
if (Method->isDirectMethod() || IMD->isDirectMethod()) {
S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
<< Method->isDirectMethod() << 0 << IMD->isDirectMethod()
<< Method->getDeclName();
S.Diag(IMD->getLocation(), diag::note_previous_declaration);
diagnosed = true;
}
};
if (auto *IMD = IDecl->getMethod(Sel, isInstance))
diagClash(IMD);
else if (auto *Impl = IDecl->getImplementation())
if (Impl != ImpDecl)
if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
diagClash(IMD);
for (const auto *Cat : IDecl->visible_categories())
if (auto *IMD = Cat->getMethod(Sel, isInstance))
diagClash(IMD);
else if (auto CatImpl = Cat->getImplementation())
if (CatImpl != ImpDecl)
if (auto *IMD = Cat->getMethod(Sel, isInstance))
diagClash(IMD);
}
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, const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
bool isVariadic, bool MethodDefinition) {
if (!CurContext->isObjCContainer()) {
Diag(MethodLoc, diag::err_missing_method_context);
return nullptr;
}
Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
QualType resultDeclType;
bool HasRelatedResultType = false;
TypeSourceInfo *ReturnTInfo = nullptr;
if (ReturnType) {
resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
if (CheckFunctionReturnType(resultDeclType, MethodLoc))
return nullptr;
QualType bareResultType = resultDeclType;
(void)AttributedType::stripOuterNullability(bareResultType);
HasRelatedResultType = (bareResultType == 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, 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 = nullptr;
} else {
ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
}
LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
LookupOrdinaryName, forRedeclarationInCurContext());
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);
AddPragmaAttributes(TUScope, Param);
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()));
ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
AddPragmaAttributes(TUScope, ObjCMethod);
const ObjCMethodDecl *PrevMethod = nullptr;
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);
}
for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
if (auto *Setter = PropertyImpl->getSetterMethodDecl())
if (Setter->getSelector() == Sel &&
Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
PropertyImpl->setSetterMethodDecl(ObjCMethod);
}
if (auto *Getter = PropertyImpl->getGetterMethodDecl())
if (Getter->getSelector() == Sel &&
Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
PropertyImpl->setGetterMethodDecl(ObjCMethod);
break;
}
}
if (!ObjCMethod->isDirectMethod()) {
const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
if (CanonicalMD->isDirectMethod()) {
const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
ObjCMethod->addAttr(
ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
}
}
if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
ObjCMethod->isInstanceMethod())) {
mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
if (IDecl == IMD->getClassInterface()) {
auto diagContainerMismatch = [&] {
int decl = 0, impl = 0;
if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
decl = Cat->IsClassExtension() ? 1 : 2;
if (isa<ObjCCategoryImplDecl>(ImpDecl))
impl = 1 + (decl != 0);
Diag(ObjCMethod->getLocation(),
diag::err_objc_direct_impl_decl_mismatch)
<< decl << impl;
Diag(IMD->getLocation(), diag::note_previous_declaration);
};
if (ObjCMethod->isDirectMethod()) {
const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
if (ObjCMethod->getCanonicalDecl() != IMD) {
diagContainerMismatch();
} else if (!IMD->isDirectMethod()) {
Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
Diag(IMD->getLocation(), diag::note_previous_declaration);
}
} else if (IMD->isDirectMethod()) {
const auto *attr = IMD->getAttr<ObjCDirectAttr>();
if (ObjCMethod->getCanonicalDecl() != IMD) {
diagContainerMismatch();
} else {
ObjCMethod->addAttr(
ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
}
}
}
if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
<< ObjCMethod->getDeclName();
}
} else {
mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl);
}
for (auto *C : IDecl->visible_categories())
for (auto &P : C->protocols())
if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
ObjCMethod->isInstanceMethod())) {
assert(ObjCMethod->parameters().size() ==
IMD->parameters().size() &&
"Methods have different number of parameters");
auto OI = IMD->param_begin(), OE = IMD->param_end();
auto NI = ObjCMethod->param_begin();
for (; OI != OE; ++OI, ++NI)
diagnoseNoescape(*NI, *OI, C, P, *this);
}
}
} else {
if (!isa<ObjCProtocolDecl>(ClassDecl)) {
mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
if (!IDecl)
IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
if (IDecl)
checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod);
}
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_initialize:
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->getReturnType()->isObjCIndependentClassType())
ObjCMethod->setRelatedResultType();
}
if (MethodDefinition &&
Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
checkObjCMethodX86VectorTypes(*this, ObjCMethod);
if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
if (ObjCMethod->isClassMethod() &&
ObjCMethod->getSelector().getAsString() == "load") {
Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
<< 0;
ObjCMethod->dropAttr<AvailabilityAttr>();
}
}
ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
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 = 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(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() != LangAS::Default) {
Diag(IdLoc, diag::err_arg_with_address_space);
Invalid = true;
}
if (Invalid) {
} else if (T->isDependentType()) {
} else if (T->isObjCQualifiedIdType()) {
Invalid = true;
Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
} else if (T->isObjCIdType()) {
} else if (!T->isObjCObjectPointerType()) {
Invalid = true;
Diag(IdLoc, diag::err_catch_param_not_objc_type);
} else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) {
Invalid = true;
Diag(IdLoc, diag::err_catch_param_not_objc_type);
}
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 (DS.isInlineSpecified())
Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
<< getLangOpts().CPlusPlus17;
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 (auto &SelectorAndLocation : ReferencedSelectors) {
Selector Sel = SelectorAndLocation.first;
SourceLocation Loc = SelectorAndLocation.second;
if (!LookupImplementedMethodInGlobalPool(Sel))
Diag(Loc, diag::warn_unimplemented_selector) << Sel;
}
}
ObjCIvarDecl *
Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
const ObjCPropertyDecl *&PDecl) const {
if (Method->isClassMethod())
return nullptr;
const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
if (!IDecl)
return nullptr;
Method = IDecl->lookupMethod(Method->getSelector(), true,
false,
false);
if (!Method || !Method->isPropertyAccessor())
return nullptr;
if ((PDecl = Method->findPropertyDecl()))
if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
IV->getIdentifier());
return IV;
}
return nullptr;
}
namespace {
class UnusedBackingIvarChecker :
public RecursiveASTVisitor<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 (const auto *CurMethod : ImplD->instance_methods()) {
unsigned DIAG = diag::warn_unused_property_backing_ivar;
SourceLocation Loc = CurMethod->getLocation();
if (Diags.isIgnored(DIAG, Loc))
continue;
const ObjCPropertyDecl *PDecl;
const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
if (!IV)
continue;
if (CurMethod->isSynthesizedAccessorStub())
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);
}
}
}