1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective C declarations.
12 //===----------------------------------------------------------------------===//
14 #include "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/RecursiveASTVisitor.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
31 using namespace clang;
33 /// Check whether the given method, which must be in the 'init'
34 /// family, is a valid member of that family.
36 /// \param receiverTypeIfCall - if null, check this as if declaring it;
37 /// if non-null, check this as if making a call to it with the given
40 /// \return true to indicate that there was an error and appropriate
41 /// actions were taken
42 bool Sema::checkInitMethod(ObjCMethodDecl *method,
43 QualType receiverTypeIfCall) {
44 if (method->isInvalidDecl()) return true;
46 // This castAs is safe: methods that don't return an object
47 // pointer won't be inferred as inits and will reject an explicit
48 // objc_method_family(init).
50 // We ignore protocols here. Should we? What about Class?
52 const ObjCObjectType *result =
53 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
55 if (result->isObjCId()) {
57 } else if (result->isObjCClass()) {
58 // fall through: always an error
60 ObjCInterfaceDecl *resultClass = result->getInterface();
61 assert(resultClass && "unexpected object type!");
63 // It's okay for the result type to still be a forward declaration
64 // if we're checking an interface declaration.
65 if (!resultClass->hasDefinition()) {
66 if (receiverTypeIfCall.isNull() &&
67 !isa<ObjCImplementationDecl>(method->getDeclContext()))
70 // Otherwise, we try to compare class types.
72 // If this method was declared in a protocol, we can't check
73 // anything unless we have a receiver type that's an interface.
74 const ObjCInterfaceDecl *receiverClass = nullptr;
75 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76 if (receiverTypeIfCall.isNull())
79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
82 // This can be null for calls to e.g. id<Foo>.
83 if (!receiverClass) return false;
85 receiverClass = method->getClassInterface();
86 assert(receiverClass && "method not associated with a class!");
89 // If either class is a subclass of the other, it's fine.
90 if (receiverClass->isSuperClassOf(resultClass) ||
91 resultClass->isSuperClassOf(receiverClass))
96 SourceLocation loc = method->getLocation();
98 // If we're in a system header, and this is not a call, just make
99 // the method unusable.
100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
112 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
113 const ObjCMethodDecl *Overridden) {
114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
120 QualType ResultType = NewMethod->getReturnType();
121 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
123 // Figure out which class this method is part of, if any.
124 ObjCInterfaceDecl *CurrentClass
125 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
127 DeclContext *DC = NewMethod->getDeclContext();
128 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
129 CurrentClass = Cat->getClassInterface();
130 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
131 CurrentClass = Impl->getClassInterface();
132 else if (ObjCCategoryImplDecl *CatImpl
133 = dyn_cast<ObjCCategoryImplDecl>(DC))
134 CurrentClass = CatImpl->getClassInterface();
138 Diag(NewMethod->getLocation(),
139 diag::warn_related_result_type_compatibility_class)
140 << Context.getObjCInterfaceType(CurrentClass)
144 Diag(NewMethod->getLocation(),
145 diag::warn_related_result_type_compatibility_protocol)
150 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151 Diag(Overridden->getLocation(),
152 diag::note_related_result_type_family)
153 << /*overridden method*/ 0
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
159 if (getLangOpts().ObjCAutoRefCount) {
160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
163 diag::err_nsreturns_retained_attribute_mismatch) << 1;
164 Diag(Overridden->getLocation(), diag::note_previous_decl)
167 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
168 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
169 Diag(NewMethod->getLocation(),
170 diag::err_nsreturns_retained_attribute_mismatch) << 0;
171 Diag(Overridden->getLocation(), diag::note_previous_decl)
174 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
175 oe = Overridden->param_end();
176 for (ObjCMethodDecl::param_iterator
177 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
178 ni != ne && oi != oe; ++ni, ++oi) {
179 const ParmVarDecl *oldDecl = (*oi);
180 ParmVarDecl *newDecl = (*ni);
181 if (newDecl->hasAttr<NSConsumedAttr>() !=
182 oldDecl->hasAttr<NSConsumedAttr>()) {
183 Diag(newDecl->getLocation(),
184 diag::err_nsconsumed_attribute_mismatch);
185 Diag(oldDecl->getLocation(), diag::note_previous_decl)
192 /// \brief Check a method declaration for compatibility with the Objective-C
194 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
195 ObjCMethodFamily family = method->getMethodFamily();
201 case OMF_autorelease:
202 case OMF_retainCount:
205 case OMF_performSelector:
209 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
210 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
211 if (ResultTypeRange.isInvalid())
212 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
213 << method->getReturnType()
214 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
216 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
217 << method->getReturnType()
218 << FixItHint::CreateReplacement(ResultTypeRange, "void");
224 // If the method doesn't obey the init rules, don't bother annotating it.
225 if (checkInitMethod(method, QualType()))
228 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
230 // Don't add a second copy of this attribute, but otherwise don't
231 // let it be suppressed.
232 if (method->hasAttr<NSReturnsRetainedAttr>())
238 case OMF_mutableCopy:
240 if (method->hasAttr<NSReturnsRetainedAttr>() ||
241 method->hasAttr<NSReturnsNotRetainedAttr>() ||
242 method->hasAttr<NSReturnsAutoreleasedAttr>())
247 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
251 static void DiagnoseObjCImplementedDeprecations(Sema &S,
253 SourceLocation ImplLoc,
255 if (ND && ND->isDeprecated()) {
256 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
258 S.Diag(ND->getLocation(), diag::note_method_declared_at)
259 << ND->getDeclName();
261 S.Diag(ND->getLocation(), diag::note_previous_decl)
262 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
266 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
268 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
269 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
271 // If we don't have a valid method decl, simply return.
274 if (MDecl->isInstanceMethod())
275 AddInstanceMethodToGlobalPool(MDecl, true);
277 AddFactoryMethodToGlobalPool(MDecl, true);
280 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
281 /// has explicit ownership attribute; false otherwise.
283 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
284 QualType T = Param->getType();
286 if (const PointerType *PT = T->getAs<PointerType>()) {
287 T = PT->getPointeeType();
288 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
289 T = RT->getPointeeType();
294 // If we have a lifetime qualifier, but it's local, we must have
295 // inferred it. So, it is implicit.
296 return !T.getLocalQualifiers().hasObjCLifetime();
299 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
300 /// and user declared, in the method definition's AST.
301 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
302 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
303 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
305 // If we don't have a valid method decl, simply return.
309 // Allow all of Sema to see that we are entering a method definition.
310 PushDeclContext(FnBodyScope, MDecl);
313 // Create Decl objects for each parameter, entrring them in the scope for
314 // binding to their use.
316 // Insert the invisible arguments, self and _cmd!
317 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
319 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
320 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
322 // The ObjC parser requires parameter names so there's no need to check.
323 CheckParmsForFunctionDef(MDecl->parameters(),
324 /*CheckParameterNames=*/false);
326 // Introduce all of the other parameters into this scope.
327 for (auto *Param : MDecl->parameters()) {
328 if (!Param->isInvalidDecl() &&
329 getLangOpts().ObjCAutoRefCount &&
330 !HasExplicitOwnershipAttr(*this, Param))
331 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
334 if (Param->getIdentifier())
335 PushOnScopeChains(Param, FnBodyScope);
338 // In ARC, disallow definition of retain/release/autorelease/retainCount
339 if (getLangOpts().ObjCAutoRefCount) {
340 switch (MDecl->getMethodFamily()) {
342 case OMF_retainCount:
344 case OMF_autorelease:
345 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
346 << 0 << MDecl->getSelector();
354 case OMF_mutableCopy:
359 case OMF_performSelector:
364 // Warn on deprecated methods under -Wdeprecated-implementations,
365 // and prepare for warning on missing super calls.
366 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
367 ObjCMethodDecl *IMD =
368 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
371 ObjCImplDecl *ImplDeclOfMethodDef =
372 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
373 ObjCContainerDecl *ContDeclOfMethodDecl =
374 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
375 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
376 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
377 ImplDeclOfMethodDecl = OID->getImplementation();
378 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
379 if (CD->IsClassExtension()) {
380 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
381 ImplDeclOfMethodDecl = OID->getImplementation();
383 ImplDeclOfMethodDecl = CD->getImplementation();
385 // No need to issue deprecated warning if deprecated mehod in class/category
386 // is being implemented in its own implementation (no overriding is involved).
387 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
388 DiagnoseObjCImplementedDeprecations(*this,
389 dyn_cast<NamedDecl>(IMD),
390 MDecl->getLocation(), 0);
393 if (MDecl->getMethodFamily() == OMF_init) {
394 if (MDecl->isDesignatedInitializerForTheInterface()) {
395 getCurFunction()->ObjCIsDesignatedInit = true;
396 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
397 IC->getSuperClass() != nullptr;
398 } else if (IC->hasDesignatedInitializers()) {
399 getCurFunction()->ObjCIsSecondaryInit = true;
400 getCurFunction()->ObjCWarnForNoInitDelegation = true;
404 // If this is "dealloc" or "finalize", set some bit here.
405 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
406 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
407 // Only do this if the current class actually has a superclass.
408 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
409 ObjCMethodFamily Family = MDecl->getMethodFamily();
410 if (Family == OMF_dealloc) {
411 if (!(getLangOpts().ObjCAutoRefCount ||
412 getLangOpts().getGC() == LangOptions::GCOnly))
413 getCurFunction()->ObjCShouldCallSuper = true;
415 } else if (Family == OMF_finalize) {
416 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
417 getCurFunction()->ObjCShouldCallSuper = true;
420 const ObjCMethodDecl *SuperMethod =
421 SuperClass->lookupMethod(MDecl->getSelector(),
422 MDecl->isInstanceMethod());
423 getCurFunction()->ObjCShouldCallSuper =
424 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
432 // Callback to only accept typo corrections that are Objective-C classes.
433 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
434 // function will reject corrections to that class.
435 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
437 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
438 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
439 : CurrentIDecl(IDecl) {}
441 bool ValidateCandidate(const TypoCorrection &candidate) override {
442 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
443 return ID && !declaresSameEntity(ID, CurrentIDecl);
447 ObjCInterfaceDecl *CurrentIDecl;
450 } // end anonymous namespace
452 static void diagnoseUseOfProtocols(Sema &TheSema,
453 ObjCContainerDecl *CD,
454 ObjCProtocolDecl *const *ProtoRefs,
455 unsigned NumProtoRefs,
456 const SourceLocation *ProtoLocs) {
458 // Diagnose availability in the context of the ObjC container.
459 Sema::ContextRAII SavedContext(TheSema, CD);
460 for (unsigned i = 0; i < NumProtoRefs; ++i) {
461 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]);
466 ActOnSuperClassOfClassInterface(Scope *S,
467 SourceLocation AtInterfaceLoc,
468 ObjCInterfaceDecl *IDecl,
469 IdentifierInfo *ClassName,
470 SourceLocation ClassLoc,
471 IdentifierInfo *SuperName,
472 SourceLocation SuperLoc,
473 ArrayRef<ParsedType> SuperTypeArgs,
474 SourceRange SuperTypeArgsRange) {
475 // Check if a different kind of symbol declared in this scope.
476 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
480 // Try to correct for a typo in the superclass name without correcting
481 // to the class we're defining.
482 if (TypoCorrection Corrected = CorrectTypo(
483 DeclarationNameInfo(SuperName, SuperLoc),
484 LookupOrdinaryName, TUScope,
485 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
486 CTK_ErrorRecovery)) {
487 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
488 << SuperName << ClassName);
489 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
493 if (declaresSameEntity(PrevDecl, IDecl)) {
494 Diag(SuperLoc, diag::err_recursive_superclass)
495 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
496 IDecl->setEndOfDefinitionLoc(ClassLoc);
498 ObjCInterfaceDecl *SuperClassDecl =
499 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
500 QualType SuperClassType;
502 // Diagnose classes that inherit from deprecated classes.
503 if (SuperClassDecl) {
504 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
505 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
508 if (PrevDecl && !SuperClassDecl) {
509 // The previous declaration was not a class decl. Check if we have a
510 // typedef. If we do, get the underlying class type.
511 if (const TypedefNameDecl *TDecl =
512 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
513 QualType T = TDecl->getUnderlyingType();
514 if (T->isObjCObjectType()) {
515 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
516 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
517 SuperClassType = Context.getTypeDeclType(TDecl);
519 // This handles the following case:
520 // @interface NewI @end
521 // typedef NewI DeprI __attribute__((deprecated("blah")))
522 // @interface SI : DeprI /* warn here */ @end
523 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
528 // This handles the following case:
530 // typedef int SuperClass;
531 // @interface MyClass : SuperClass {} @end
533 if (!SuperClassDecl) {
534 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
535 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
539 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
541 Diag(SuperLoc, diag::err_undef_superclass)
542 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
543 else if (RequireCompleteType(SuperLoc,
545 diag::err_forward_superclass,
546 SuperClassDecl->getDeclName(),
548 SourceRange(AtInterfaceLoc, ClassLoc))) {
549 SuperClassDecl = nullptr;
550 SuperClassType = QualType();
554 if (SuperClassType.isNull()) {
555 assert(!SuperClassDecl && "Failed to set SuperClassType?");
559 // Handle type arguments on the superclass.
560 TypeSourceInfo *SuperClassTInfo = nullptr;
561 if (!SuperTypeArgs.empty()) {
562 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
565 CreateParsedType(SuperClassType,
567 SuperTypeArgsRange.getBegin(),
569 SuperTypeArgsRange.getEnd(),
574 if (!fullSuperClassType.isUsable())
577 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
581 if (!SuperClassTInfo) {
582 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
586 IDecl->setSuperClass(SuperClassTInfo);
587 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
591 DeclResult Sema::actOnObjCTypeParam(Scope *S,
592 ObjCTypeParamVariance variance,
593 SourceLocation varianceLoc,
595 IdentifierInfo *paramName,
596 SourceLocation paramLoc,
597 SourceLocation colonLoc,
598 ParsedType parsedTypeBound) {
599 // If there was an explicitly-provided type bound, check it.
600 TypeSourceInfo *typeBoundInfo = nullptr;
601 if (parsedTypeBound) {
602 // The type bound can be any Objective-C pointer type.
603 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
604 if (typeBound->isObjCObjectPointerType()) {
606 } else if (typeBound->isObjCObjectType()) {
607 // The user forgot the * on an Objective-C pointer type, e.g.,
609 SourceLocation starLoc = getLocForEndOfToken(
610 typeBoundInfo->getTypeLoc().getEndLoc());
611 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
612 diag::err_objc_type_param_bound_missing_pointer)
613 << typeBound << paramName
614 << FixItHint::CreateInsertion(starLoc, " *");
616 // Create a new type location builder so we can update the type
617 // location information we have.
618 TypeLocBuilder builder;
619 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
621 // Create the Objective-C pointer type.
622 typeBound = Context.getObjCObjectPointerType(typeBound);
623 ObjCObjectPointerTypeLoc newT
624 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
625 newT.setStarLoc(starLoc);
627 // Form the new type source information.
628 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
630 // Not a valid type bound.
631 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
632 diag::err_objc_type_param_bound_nonobject)
633 << typeBound << paramName;
635 // Forget the bound; we'll default to id later.
636 typeBoundInfo = nullptr;
639 // Type bounds cannot have qualifiers (even indirectly) or explicit
642 QualType typeBound = typeBoundInfo->getType();
643 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
644 if (qual || typeBound.hasQualifiers()) {
645 bool diagnosed = false;
646 SourceRange rangeToRemove;
648 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
649 rangeToRemove = attr.getLocalSourceRange();
650 if (attr.getTypePtr()->getImmediateNullability()) {
651 Diag(attr.getLocStart(),
652 diag::err_objc_type_param_bound_explicit_nullability)
653 << paramName << typeBound
654 << FixItHint::CreateRemoval(rangeToRemove);
661 Diag(qual ? qual.getLocStart()
662 : typeBoundInfo->getTypeLoc().getLocStart(),
663 diag::err_objc_type_param_bound_qualified)
664 << paramName << typeBound << typeBound.getQualifiers().getAsString()
665 << FixItHint::CreateRemoval(rangeToRemove);
668 // If the type bound has qualifiers other than CVR, we need to strip
669 // them or we'll probably assert later when trying to apply new
671 Qualifiers quals = typeBound.getQualifiers();
672 quals.removeCVRQualifiers();
673 if (!quals.empty()) {
675 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
681 // If there was no explicit type bound (or we removed it due to an error),
683 if (!typeBoundInfo) {
684 colonLoc = SourceLocation();
685 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
688 // Create the type parameter.
689 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
690 index, paramLoc, paramName, colonLoc,
694 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
695 SourceLocation lAngleLoc,
696 ArrayRef<Decl *> typeParamsIn,
697 SourceLocation rAngleLoc) {
698 // We know that the array only contains Objective-C type parameters.
699 ArrayRef<ObjCTypeParamDecl *>
701 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
702 typeParamsIn.size());
704 // Diagnose redeclarations of type parameters.
705 // We do this now because Objective-C type parameters aren't pushed into
706 // scope until later (after the instance variable block), but we want the
707 // diagnostics to occur right after we parse the type parameter list.
708 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
709 for (auto typeParam : typeParams) {
710 auto known = knownParams.find(typeParam->getIdentifier());
711 if (known != knownParams.end()) {
712 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
713 << typeParam->getIdentifier()
714 << SourceRange(known->second->getLocation());
716 typeParam->setInvalidDecl();
718 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
720 // Push the type parameter into scope.
721 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
725 // Create the parameter list.
726 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
729 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
730 for (auto typeParam : *typeParamList) {
731 if (!typeParam->isInvalidDecl()) {
732 S->RemoveDecl(typeParam);
733 IdResolver.RemoveDecl(typeParam);
739 /// The context in which an Objective-C type parameter list occurs, for use
741 enum class TypeParamListContext {
747 } // end anonymous namespace
749 /// Check consistency between two Objective-C type parameter lists, e.g.,
750 /// between a category/extension and an \@interface or between an \@class and an
752 static bool checkTypeParamListConsistency(Sema &S,
753 ObjCTypeParamList *prevTypeParams,
754 ObjCTypeParamList *newTypeParams,
755 TypeParamListContext newContext) {
756 // If the sizes don't match, complain about that.
757 if (prevTypeParams->size() != newTypeParams->size()) {
758 SourceLocation diagLoc;
759 if (newTypeParams->size() > prevTypeParams->size()) {
760 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
762 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
765 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
766 << static_cast<unsigned>(newContext)
767 << (newTypeParams->size() > prevTypeParams->size())
768 << prevTypeParams->size()
769 << newTypeParams->size();
774 // Match up the type parameters.
775 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
776 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
777 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
779 // Check for consistency of the variance.
780 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
781 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
782 newContext != TypeParamListContext::Definition) {
783 // When the new type parameter is invariant and is not part
784 // of the definition, just propagate the variance.
785 newTypeParam->setVariance(prevTypeParam->getVariance());
786 } else if (prevTypeParam->getVariance()
787 == ObjCTypeParamVariance::Invariant &&
788 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
789 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
790 ->getDefinition() == prevTypeParam->getDeclContext())) {
791 // When the old parameter is invariant and was not part of the
792 // definition, just ignore the difference because it doesn't
796 // Diagnose the conflict and update the second declaration.
797 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
798 if (diagLoc.isInvalid())
799 diagLoc = newTypeParam->getLocStart();
801 auto diag = S.Diag(diagLoc,
802 diag::err_objc_type_param_variance_conflict)
803 << static_cast<unsigned>(newTypeParam->getVariance())
804 << newTypeParam->getDeclName()
805 << static_cast<unsigned>(prevTypeParam->getVariance())
806 << prevTypeParam->getDeclName();
807 switch (prevTypeParam->getVariance()) {
808 case ObjCTypeParamVariance::Invariant:
809 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
812 case ObjCTypeParamVariance::Covariant:
813 case ObjCTypeParamVariance::Contravariant: {
814 StringRef newVarianceStr
815 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
818 if (newTypeParam->getVariance()
819 == ObjCTypeParamVariance::Invariant) {
820 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
821 (newVarianceStr + " ").str());
823 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
830 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
831 << prevTypeParam->getDeclName();
833 // Override the variance.
834 newTypeParam->setVariance(prevTypeParam->getVariance());
838 // If the bound types match, there's nothing to do.
839 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
840 newTypeParam->getUnderlyingType()))
843 // If the new type parameter's bound was explicit, complain about it being
844 // different from the original.
845 if (newTypeParam->hasExplicitBound()) {
846 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
847 ->getTypeLoc().getSourceRange();
848 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
849 << newTypeParam->getUnderlyingType()
850 << newTypeParam->getDeclName()
851 << prevTypeParam->hasExplicitBound()
852 << prevTypeParam->getUnderlyingType()
853 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
854 << prevTypeParam->getDeclName()
855 << FixItHint::CreateReplacement(
857 prevTypeParam->getUnderlyingType().getAsString(
858 S.Context.getPrintingPolicy()));
860 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
861 << prevTypeParam->getDeclName();
863 // Override the new type parameter's bound type with the previous type,
864 // so that it's consistent.
865 newTypeParam->setTypeSourceInfo(
866 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
870 // The new type parameter got the implicit bound of 'id'. That's okay for
871 // categories and extensions (overwrite it later), but not for forward
872 // declarations and @interfaces, because those must be standalone.
873 if (newContext == TypeParamListContext::ForwardDeclaration ||
874 newContext == TypeParamListContext::Definition) {
875 // Diagnose this problem for forward declarations and definitions.
876 SourceLocation insertionLoc
877 = S.getLocForEndOfToken(newTypeParam->getLocation());
879 = " : " + prevTypeParam->getUnderlyingType().getAsString(
880 S.Context.getPrintingPolicy());
881 S.Diag(newTypeParam->getLocation(),
882 diag::err_objc_type_param_bound_missing)
883 << prevTypeParam->getUnderlyingType()
884 << newTypeParam->getDeclName()
885 << (newContext == TypeParamListContext::ForwardDeclaration)
886 << FixItHint::CreateInsertion(insertionLoc, newCode);
888 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
889 << prevTypeParam->getDeclName();
892 // Update the new type parameter's bound to match the previous one.
893 newTypeParam->setTypeSourceInfo(
894 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
901 ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
902 IdentifierInfo *ClassName, SourceLocation ClassLoc,
903 ObjCTypeParamList *typeParamList,
904 IdentifierInfo *SuperName, SourceLocation SuperLoc,
905 ArrayRef<ParsedType> SuperTypeArgs,
906 SourceRange SuperTypeArgsRange,
907 Decl * const *ProtoRefs, unsigned NumProtoRefs,
908 const SourceLocation *ProtoLocs,
909 SourceLocation EndProtoLoc, AttributeList *AttrList) {
910 assert(ClassName && "Missing class identifier");
912 // Check for another declaration kind with the same name.
913 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
914 LookupOrdinaryName, ForRedeclaration);
916 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
917 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
918 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
921 // Create a declaration to describe this @interface.
922 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
924 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
925 // A previous decl with a different name is because of
926 // @compatibility_alias, for example:
929 // @compatibility_alias OldImage NewImage;
931 // A lookup for 'OldImage' will return the 'NewImage' decl.
933 // In such a case use the real declaration name, instead of the alias one,
934 // otherwise we will break IdentifierResolver and redecls-chain invariants.
935 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
937 ClassName = PrevIDecl->getIdentifier();
940 // If there was a forward declaration with type parameters, check
943 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
945 // Both have type parameter lists; check for consistency.
946 if (checkTypeParamListConsistency(*this, prevTypeParamList,
948 TypeParamListContext::Definition)) {
949 typeParamList = nullptr;
952 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
954 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
957 // Clone the type parameter list.
958 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
959 for (auto typeParam : *prevTypeParamList) {
960 clonedTypeParams.push_back(
961 ObjCTypeParamDecl::Create(
964 typeParam->getVariance(),
966 typeParam->getIndex(),
968 typeParam->getIdentifier(),
970 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
973 typeParamList = ObjCTypeParamList::create(Context,
981 ObjCInterfaceDecl *IDecl
982 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
983 typeParamList, PrevIDecl, ClassLoc);
985 // Class already seen. Was it a definition?
986 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
987 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
988 << PrevIDecl->getDeclName();
989 Diag(Def->getLocation(), diag::note_previous_definition);
990 IDecl->setInvalidDecl();
995 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
996 AddPragmaAttributes(TUScope, IDecl);
997 PushOnScopeChains(IDecl, TUScope);
999 // Start the definition of this class. If we're in a redefinition case, there
1000 // may already be a definition, so we'll end up adding to it.
1001 if (!IDecl->hasDefinition())
1002 IDecl->startDefinition();
1005 // Diagnose availability in the context of the @interface.
1006 ContextRAII SavedContext(*this, IDecl);
1008 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1009 ClassName, ClassLoc,
1010 SuperName, SuperLoc, SuperTypeArgs,
1011 SuperTypeArgsRange);
1012 } else { // we have a root class.
1013 IDecl->setEndOfDefinitionLoc(ClassLoc);
1016 // Check then save referenced protocols.
1018 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1019 NumProtoRefs, ProtoLocs);
1020 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1021 ProtoLocs, Context);
1022 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1025 CheckObjCDeclScope(IDecl);
1026 return ActOnObjCContainerStartDefinition(IDecl);
1029 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
1030 /// typedef'ed use for a qualified super class and adds them to the list
1031 /// of the protocols.
1032 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1033 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1034 IdentifierInfo *SuperName,
1035 SourceLocation SuperLoc) {
1038 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1039 LookupOrdinaryName);
1043 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1044 QualType T = TDecl->getUnderlyingType();
1045 if (T->isObjCObjectType())
1046 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1047 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1048 // FIXME: Consider whether this should be an invalid loc since the loc
1049 // is not actually pointing to a protocol name reference but to the
1050 // typedef reference. Note that the base class name loc is also pointing
1052 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1057 /// ActOnCompatibilityAlias - this action is called after complete parsing of
1058 /// a \@compatibility_alias declaration. It sets up the alias relationships.
1059 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1060 IdentifierInfo *AliasName,
1061 SourceLocation AliasLocation,
1062 IdentifierInfo *ClassName,
1063 SourceLocation ClassLocation) {
1064 // Look for previous declaration of alias name
1065 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
1066 LookupOrdinaryName, ForRedeclaration);
1068 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1069 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1072 // Check for class declaration
1073 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1074 LookupOrdinaryName, ForRedeclaration);
1075 if (const TypedefNameDecl *TDecl =
1076 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1077 QualType T = TDecl->getUnderlyingType();
1078 if (T->isObjCObjectType()) {
1079 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
1080 ClassName = IDecl->getIdentifier();
1081 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1082 LookupOrdinaryName, ForRedeclaration);
1086 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1088 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1090 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1094 // Everything checked out, instantiate a new alias declaration AST.
1095 ObjCCompatibleAliasDecl *AliasDecl =
1096 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1098 if (!CheckObjCDeclScope(AliasDecl))
1099 PushOnScopeChains(AliasDecl, TUScope);
1104 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
1105 IdentifierInfo *PName,
1106 SourceLocation &Ploc, SourceLocation PrevLoc,
1107 const ObjCList<ObjCProtocolDecl> &PList) {
1110 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1111 E = PList.end(); I != E; ++I) {
1112 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1114 if (PDecl->getIdentifier() == PName) {
1115 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1116 Diag(PrevLoc, diag::note_previous_definition);
1120 if (!PDecl->hasDefinition())
1123 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1124 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1132 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1133 IdentifierInfo *ProtocolName,
1134 SourceLocation ProtocolLoc,
1135 Decl * const *ProtoRefs,
1136 unsigned NumProtoRefs,
1137 const SourceLocation *ProtoLocs,
1138 SourceLocation EndProtoLoc,
1139 AttributeList *AttrList) {
1141 // FIXME: Deal with AttrList.
1142 assert(ProtocolName && "Missing protocol identifier");
1143 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1145 ObjCProtocolDecl *PDecl = nullptr;
1146 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1147 // If we already have a definition, complain.
1148 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1149 Diag(Def->getLocation(), diag::note_previous_definition);
1151 // Create a new protocol that is completely distinct from previous
1152 // declarations, and do not make this protocol available for name lookup.
1153 // That way, we'll end up completely ignoring the duplicate.
1154 // FIXME: Can we turn this into an error?
1155 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1156 ProtocolLoc, AtProtoInterfaceLoc,
1157 /*PrevDecl=*/nullptr);
1158 PDecl->startDefinition();
1161 // Check for circular dependencies among protocol declarations. This can
1162 // only happen if this protocol was forward-declared.
1163 ObjCList<ObjCProtocolDecl> PList;
1164 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1165 err = CheckForwardProtocolDeclarationForCircularDependency(
1166 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1169 // Create the new declaration.
1170 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1171 ProtocolLoc, AtProtoInterfaceLoc,
1172 /*PrevDecl=*/PrevDecl);
1174 PushOnScopeChains(PDecl, TUScope);
1175 PDecl->startDefinition();
1179 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1180 AddPragmaAttributes(TUScope, PDecl);
1182 // Merge attributes from previous declarations.
1184 mergeDeclAttributes(PDecl, PrevDecl);
1186 if (!err && NumProtoRefs ) {
1187 /// Check then save referenced protocols.
1188 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1189 NumProtoRefs, ProtoLocs);
1190 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1191 ProtoLocs, Context);
1194 CheckObjCDeclScope(PDecl);
1195 return ActOnObjCContainerStartDefinition(PDecl);
1198 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1199 ObjCProtocolDecl *&UndefinedProtocol) {
1200 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1201 UndefinedProtocol = PDecl;
1205 for (auto *PI : PDecl->protocols())
1206 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1207 UndefinedProtocol = PI;
1213 /// FindProtocolDeclaration - This routine looks up protocols and
1214 /// issues an error if they are not declared. It returns list of
1215 /// protocol declarations in its 'Protocols' argument.
1217 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1218 ArrayRef<IdentifierLocPair> ProtocolId,
1219 SmallVectorImpl<Decl *> &Protocols) {
1220 for (const IdentifierLocPair &Pair : ProtocolId) {
1221 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1223 TypoCorrection Corrected = CorrectTypo(
1224 DeclarationNameInfo(Pair.first, Pair.second),
1225 LookupObjCProtocolName, TUScope, nullptr,
1226 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
1228 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1229 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1234 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1237 // If this is a forward protocol declaration, get its definition.
1238 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1239 PDecl = PDecl->getDefinition();
1241 // For an objc container, delay protocol reference checking until after we
1242 // can set the objc decl as the availability context, otherwise check now.
1243 if (!ForObjCContainer) {
1244 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1247 // If this is a forward declaration and we are supposed to warn in this
1249 // FIXME: Recover nicely in the hidden case.
1250 ObjCProtocolDecl *UndefinedProtocol;
1252 if (WarnOnDeclarations &&
1253 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1254 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1255 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1256 << UndefinedProtocol;
1258 Protocols.push_back(PDecl);
1263 // Callback to only accept typo corrections that are either
1264 // Objective-C protocols or valid Objective-C type arguments.
1265 class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1266 ASTContext &Context;
1267 Sema::LookupNameKind LookupKind;
1269 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1270 Sema::LookupNameKind lookupKind)
1271 : Context(context), LookupKind(lookupKind) { }
1273 bool ValidateCandidate(const TypoCorrection &candidate) override {
1274 // If we're allowed to find protocols and we have a protocol, accept it.
1275 if (LookupKind != Sema::LookupOrdinaryName) {
1276 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1280 // If we're allowed to find type names and we have one, accept it.
1281 if (LookupKind != Sema::LookupObjCProtocolName) {
1282 // If we have a type declaration, we might accept this result.
1283 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1284 // If we found a tag declaration outside of C++, skip it. This
1285 // can happy because we look for any name when there is no
1286 // bias to protocol or type names.
1287 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1290 // Make sure the type is something we would accept as a type
1292 auto type = Context.getTypeDeclType(typeDecl);
1293 if (type->isObjCObjectPointerType() ||
1294 type->isBlockPointerType() ||
1295 type->isDependentType() ||
1296 type->isObjCObjectType())
1302 // If we have an Objective-C class type, accept it; there will
1303 // be another fix to add the '*'.
1304 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1313 } // end anonymous namespace
1315 void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1316 SourceLocation ProtocolLoc,
1317 IdentifierInfo *TypeArgId,
1318 SourceLocation TypeArgLoc,
1319 bool SelectProtocolFirst) {
1320 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1321 << SelectProtocolFirst << TypeArgId << ProtocolId
1322 << SourceRange(ProtocolLoc);
1325 void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1327 ParsedType baseType,
1328 SourceLocation lAngleLoc,
1329 ArrayRef<IdentifierInfo *> identifiers,
1330 ArrayRef<SourceLocation> identifierLocs,
1331 SourceLocation rAngleLoc,
1332 SourceLocation &typeArgsLAngleLoc,
1333 SmallVectorImpl<ParsedType> &typeArgs,
1334 SourceLocation &typeArgsRAngleLoc,
1335 SourceLocation &protocolLAngleLoc,
1336 SmallVectorImpl<Decl *> &protocols,
1337 SourceLocation &protocolRAngleLoc,
1338 bool warnOnIncompleteProtocols) {
1339 // Local function that updates the declaration specifiers with
1340 // protocol information.
1341 unsigned numProtocolsResolved = 0;
1342 auto resolvedAsProtocols = [&] {
1343 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1345 // Determine whether the base type is a parameterized class, in
1346 // which case we want to warn about typos such as
1347 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1348 ObjCInterfaceDecl *baseClass = nullptr;
1349 QualType base = GetTypeFromParser(baseType, nullptr);
1350 bool allAreTypeNames = false;
1351 SourceLocation firstClassNameLoc;
1352 if (!base.isNull()) {
1353 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1354 baseClass = objcObjectType->getInterface();
1356 if (auto typeParams = baseClass->getTypeParamList()) {
1357 if (typeParams->size() == numProtocolsResolved) {
1358 // Note that we should be looking for type names, too.
1359 allAreTypeNames = true;
1366 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1367 ObjCProtocolDecl *&proto
1368 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1369 // For an objc container, delay protocol reference checking until after we
1370 // can set the objc decl as the availability context, otherwise check now.
1371 if (!warnOnIncompleteProtocols) {
1372 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1375 // If this is a forward protocol declaration, get its definition.
1376 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1377 proto = proto->getDefinition();
1379 // If this is a forward declaration and we are supposed to warn in this
1381 // FIXME: Recover nicely in the hidden case.
1382 ObjCProtocolDecl *forwardDecl = nullptr;
1383 if (warnOnIncompleteProtocols &&
1384 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1385 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1386 << proto->getDeclName();
1387 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1391 // If everything this far has been a type name (and we care
1392 // about such things), check whether this name refers to a type
1394 if (allAreTypeNames) {
1395 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1396 LookupOrdinaryName)) {
1397 if (isa<ObjCInterfaceDecl>(decl)) {
1398 if (firstClassNameLoc.isInvalid())
1399 firstClassNameLoc = identifierLocs[i];
1400 } else if (!isa<TypeDecl>(decl)) {
1402 allAreTypeNames = false;
1405 allAreTypeNames = false;
1410 // All of the protocols listed also have type names, and at least
1411 // one is an Objective-C class name. Check whether all of the
1412 // protocol conformances are declared by the base class itself, in
1413 // which case we warn.
1414 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1415 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1416 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1417 bool allProtocolsDeclared = true;
1418 for (auto proto : protocols) {
1419 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1420 allProtocolsDeclared = false;
1425 if (allProtocolsDeclared) {
1426 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1427 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1428 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1433 protocolLAngleLoc = lAngleLoc;
1434 protocolRAngleLoc = rAngleLoc;
1435 assert(protocols.size() == identifierLocs.size());
1438 // Attempt to resolve all of the identifiers as protocols.
1439 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1440 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1441 protocols.push_back(proto);
1443 ++numProtocolsResolved;
1446 // If all of the names were protocols, these were protocol qualifiers.
1447 if (numProtocolsResolved == identifiers.size())
1448 return resolvedAsProtocols();
1450 // Attempt to resolve all of the identifiers as type names or
1451 // Objective-C class names. The latter is technically ill-formed,
1452 // but is probably something like \c NSArray<NSView *> missing the
1454 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1455 SmallVector<TypeOrClassDecl, 4> typeDecls;
1456 unsigned numTypeDeclsResolved = 0;
1457 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1458 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1459 LookupOrdinaryName);
1461 typeDecls.push_back(TypeOrClassDecl());
1465 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1466 typeDecls.push_back(typeDecl);
1467 ++numTypeDeclsResolved;
1471 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1472 typeDecls.push_back(objcClass);
1473 ++numTypeDeclsResolved;
1477 typeDecls.push_back(TypeOrClassDecl());
1480 AttributeFactory attrFactory;
1482 // Local function that forms a reference to the given type or
1483 // Objective-C class declaration.
1484 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1486 // Form declaration specifiers. They simply refer to the type.
1487 DeclSpec DS(attrFactory);
1488 const char* prevSpec; // unused
1489 unsigned diagID; // unused
1491 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1492 type = Context.getTypeDeclType(actualTypeDecl);
1494 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1495 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1496 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1497 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1498 parsedType, Context.getPrintingPolicy());
1499 // Use the identifier location for the type source range.
1500 DS.SetRangeStart(loc);
1501 DS.SetRangeEnd(loc);
1503 // Form the declarator.
1504 Declarator D(DS, Declarator::TypeNameContext);
1506 // If we have a typedef of an Objective-C class type that is missing a '*',
1508 if (type->getAs<ObjCInterfaceType>()) {
1509 SourceLocation starLoc = getLocForEndOfToken(loc);
1510 ParsedAttributes parsedAttrs(attrFactory);
1511 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1520 // Diagnose the missing '*'.
1521 Diag(loc, diag::err_objc_type_arg_missing_star)
1523 << FixItHint::CreateInsertion(starLoc, " *");
1526 // Convert this to a type.
1527 return ActOnTypeName(S, D);
1530 // Local function that updates the declaration specifiers with
1531 // type argument information.
1532 auto resolvedAsTypeDecls = [&] {
1533 // We did not resolve these as protocols.
1536 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1537 // Map type declarations to type arguments.
1538 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1539 // Map type reference to a type.
1540 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1541 if (!type.isUsable()) {
1546 typeArgs.push_back(type.get());
1549 typeArgsLAngleLoc = lAngleLoc;
1550 typeArgsRAngleLoc = rAngleLoc;
1553 // If all of the identifiers can be resolved as type names or
1554 // Objective-C class names, we have type arguments.
1555 if (numTypeDeclsResolved == identifiers.size())
1556 return resolvedAsTypeDecls();
1558 // Error recovery: some names weren't found, or we have a mix of
1559 // type and protocol names. Go resolve all of the unresolved names
1560 // and complain if we can't find a consistent answer.
1561 LookupNameKind lookupKind = LookupAnyName;
1562 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1563 // If we already have a protocol or type. Check whether it is the
1565 if (protocols[i] || typeDecls[i]) {
1566 // If we haven't figured out whether we want types or protocols
1567 // yet, try to figure it out from this name.
1568 if (lookupKind == LookupAnyName) {
1569 // If this name refers to both a protocol and a type (e.g., \c
1570 // NSObject), don't conclude anything yet.
1571 if (protocols[i] && typeDecls[i])
1574 // Otherwise, let this name decide whether we'll be correcting
1575 // toward types or protocols.
1576 lookupKind = protocols[i] ? LookupObjCProtocolName
1577 : LookupOrdinaryName;
1581 // If we want protocols and we have a protocol, there's nothing
1583 if (lookupKind == LookupObjCProtocolName && protocols[i])
1586 // If we want types and we have a type declaration, there's
1587 // nothing more to do.
1588 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1591 // We have a conflict: some names refer to protocols and others
1593 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1594 identifiers[i], identifierLocs[i],
1595 protocols[i] != nullptr);
1602 // Perform typo correction on the name.
1603 TypoCorrection corrected = CorrectTypo(
1604 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1606 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1610 // Did we find a protocol?
1611 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1612 diagnoseTypo(corrected,
1613 PDiag(diag::err_undeclared_protocol_suggest)
1615 lookupKind = LookupObjCProtocolName;
1616 protocols[i] = proto;
1617 ++numProtocolsResolved;
1621 // Did we find a type?
1622 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1623 diagnoseTypo(corrected,
1624 PDiag(diag::err_unknown_typename_suggest)
1626 lookupKind = LookupOrdinaryName;
1627 typeDecls[i] = typeDecl;
1628 ++numTypeDeclsResolved;
1632 // Did we find an Objective-C class?
1633 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1634 diagnoseTypo(corrected,
1635 PDiag(diag::err_unknown_type_or_class_name_suggest)
1636 << identifiers[i] << true);
1637 lookupKind = LookupOrdinaryName;
1638 typeDecls[i] = objcClass;
1639 ++numTypeDeclsResolved;
1644 // We couldn't find anything.
1645 Diag(identifierLocs[i],
1646 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1647 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1648 : diag::err_unknown_typename))
1655 // If all of the names were (corrected to) protocols, these were
1656 // protocol qualifiers.
1657 if (numProtocolsResolved == identifiers.size())
1658 return resolvedAsProtocols();
1660 // Otherwise, all of the names were (corrected to) types.
1661 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1662 return resolvedAsTypeDecls();
1665 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1666 /// a class method in its extension.
1668 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1669 ObjCInterfaceDecl *ID) {
1671 return; // Possibly due to previous error
1673 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1674 for (auto *MD : ID->methods())
1675 MethodMap[MD->getSelector()] = MD;
1677 if (MethodMap.empty())
1679 for (const auto *Method : CAT->methods()) {
1680 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1682 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1683 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1684 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1685 << Method->getDeclName();
1686 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1691 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1692 Sema::DeclGroupPtrTy
1693 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
1694 ArrayRef<IdentifierLocPair> IdentList,
1695 AttributeList *attrList) {
1696 SmallVector<Decl *, 8> DeclsInGroup;
1697 for (const IdentifierLocPair &IdentPair : IdentList) {
1698 IdentifierInfo *Ident = IdentPair.first;
1699 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1701 ObjCProtocolDecl *PDecl
1702 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1703 IdentPair.second, AtProtocolLoc,
1706 PushOnScopeChains(PDecl, TUScope);
1707 CheckObjCDeclScope(PDecl);
1710 ProcessDeclAttributeList(TUScope, PDecl, attrList);
1711 AddPragmaAttributes(TUScope, PDecl);
1714 mergeDeclAttributes(PDecl, PrevDecl);
1716 DeclsInGroup.push_back(PDecl);
1719 return BuildDeclaratorGroup(DeclsInGroup);
1723 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1724 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1725 ObjCTypeParamList *typeParamList,
1726 IdentifierInfo *CategoryName,
1727 SourceLocation CategoryLoc,
1728 Decl * const *ProtoRefs,
1729 unsigned NumProtoRefs,
1730 const SourceLocation *ProtoLocs,
1731 SourceLocation EndProtoLoc,
1732 AttributeList *AttrList) {
1733 ObjCCategoryDecl *CDecl;
1734 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1736 /// Check that class of this category is already completely declared.
1739 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1740 diag::err_category_forward_interface,
1741 CategoryName == nullptr)) {
1742 // Create an invalid ObjCCategoryDecl to serve as context for
1743 // the enclosing method declarations. We mark the decl invalid
1744 // to make it clear that this isn't a valid AST.
1745 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1746 ClassLoc, CategoryLoc, CategoryName,
1747 IDecl, typeParamList);
1748 CDecl->setInvalidDecl();
1749 CurContext->addDecl(CDecl);
1752 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1753 return ActOnObjCContainerStartDefinition(CDecl);
1756 if (!CategoryName && IDecl->getImplementation()) {
1757 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1758 Diag(IDecl->getImplementation()->getLocation(),
1759 diag::note_implementation_declared);
1763 /// Check for duplicate interface declaration for this category
1764 if (ObjCCategoryDecl *Previous
1765 = IDecl->FindCategoryDeclaration(CategoryName)) {
1766 // Class extensions can be declared multiple times, categories cannot.
1767 Diag(CategoryLoc, diag::warn_dup_category_def)
1768 << ClassName << CategoryName;
1769 Diag(Previous->getLocation(), diag::note_previous_definition);
1773 // If we have a type parameter list, check it.
1774 if (typeParamList) {
1775 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1776 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1778 ? TypeParamListContext::Category
1779 : TypeParamListContext::Extension))
1780 typeParamList = nullptr;
1782 Diag(typeParamList->getLAngleLoc(),
1783 diag::err_objc_parameterized_category_nonclass)
1784 << (CategoryName != nullptr)
1786 << typeParamList->getSourceRange();
1788 typeParamList = nullptr;
1792 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1793 ClassLoc, CategoryLoc, CategoryName, IDecl,
1795 // FIXME: PushOnScopeChains?
1796 CurContext->addDecl(CDecl);
1799 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1800 NumProtoRefs, ProtoLocs);
1801 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1802 ProtoLocs, Context);
1803 // Protocols in the class extension belong to the class.
1804 if (CDecl->IsClassExtension())
1805 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1806 NumProtoRefs, Context);
1810 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1811 AddPragmaAttributes(TUScope, CDecl);
1813 CheckObjCDeclScope(CDecl);
1814 return ActOnObjCContainerStartDefinition(CDecl);
1817 /// ActOnStartCategoryImplementation - Perform semantic checks on the
1818 /// category implementation declaration and build an ObjCCategoryImplDecl
1820 Decl *Sema::ActOnStartCategoryImplementation(
1821 SourceLocation AtCatImplLoc,
1822 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1823 IdentifierInfo *CatName, SourceLocation CatLoc) {
1824 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1825 ObjCCategoryDecl *CatIDecl = nullptr;
1826 if (IDecl && IDecl->hasDefinition()) {
1827 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1829 // Category @implementation with no corresponding @interface.
1830 // Create and install one.
1831 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1834 /*typeParamList=*/nullptr);
1835 CatIDecl->setImplicit();
1839 ObjCCategoryImplDecl *CDecl =
1840 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
1841 ClassLoc, AtCatImplLoc, CatLoc);
1842 /// Check that class of this category is already completely declared.
1844 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1845 CDecl->setInvalidDecl();
1846 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1847 diag::err_undef_interface)) {
1848 CDecl->setInvalidDecl();
1851 // FIXME: PushOnScopeChains?
1852 CurContext->addDecl(CDecl);
1854 // If the interface is deprecated/unavailable, warn/error about it.
1856 DiagnoseUseOfDecl(IDecl, ClassLoc);
1858 // If the interface has the objc_runtime_visible attribute, we
1859 // cannot implement a category for it.
1860 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1861 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1862 << IDecl->getDeclName();
1865 /// Check that CatName, category name, is not used in another implementation.
1867 if (CatIDecl->getImplementation()) {
1868 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1870 Diag(CatIDecl->getImplementation()->getLocation(),
1871 diag::note_previous_definition);
1872 CDecl->setInvalidDecl();
1874 CatIDecl->setImplementation(CDecl);
1875 // Warn on implementating category of deprecated class under
1876 // -Wdeprecated-implementations flag.
1877 DiagnoseObjCImplementedDeprecations(
1879 CatIDecl->isDeprecated() ? CatIDecl : dyn_cast<NamedDecl>(IDecl),
1880 CDecl->getLocation(), 2);
1884 CheckObjCDeclScope(CDecl);
1885 return ActOnObjCContainerStartDefinition(CDecl);
1888 Decl *Sema::ActOnStartClassImplementation(
1889 SourceLocation AtClassImplLoc,
1890 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1891 IdentifierInfo *SuperClassname,
1892 SourceLocation SuperClassLoc) {
1893 ObjCInterfaceDecl *IDecl = nullptr;
1894 // Check for another declaration kind with the same name.
1896 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1898 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1899 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1900 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1901 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1902 // FIXME: This will produce an error if the definition of the interface has
1903 // been imported from a module but is not visible.
1904 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1905 diag::warn_undef_interface);
1907 // We did not find anything with the name ClassName; try to correct for
1908 // typos in the class name.
1909 TypoCorrection Corrected = CorrectTypo(
1910 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1911 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
1912 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1913 // Suggest the (potentially) correct interface name. Don't provide a
1914 // code-modification hint or use the typo name for recovery, because
1915 // this is just a warning. The program may actually be correct.
1916 diagnoseTypo(Corrected,
1917 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1918 /*ErrorRecovery*/false);
1920 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1924 // Check that super class name is valid class name
1925 ObjCInterfaceDecl *SDecl = nullptr;
1926 if (SuperClassname) {
1927 // Check if a different kind of symbol declared in this scope.
1928 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1929 LookupOrdinaryName);
1930 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1931 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1933 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1935 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1936 if (SDecl && !SDecl->hasDefinition())
1939 Diag(SuperClassLoc, diag::err_undef_superclass)
1940 << SuperClassname << ClassName;
1941 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1942 // This implementation and its interface do not have the same
1944 Diag(SuperClassLoc, diag::err_conflicting_super_class)
1945 << SDecl->getDeclName();
1946 Diag(SDecl->getLocation(), diag::note_previous_definition);
1952 // Legacy case of @implementation with no corresponding @interface.
1953 // Build, chain & install the interface decl into the identifier.
1955 // FIXME: Do we support attributes on the @implementation? If so we should
1957 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1958 ClassName, /*typeParamList=*/nullptr,
1959 /*PrevDecl=*/nullptr, ClassLoc,
1961 AddPragmaAttributes(TUScope, IDecl);
1962 IDecl->startDefinition();
1964 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1965 Context.getObjCInterfaceType(SDecl),
1967 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1969 IDecl->setEndOfDefinitionLoc(ClassLoc);
1972 PushOnScopeChains(IDecl, TUScope);
1974 // Mark the interface as being completed, even if it was just as
1976 // declaration; the user cannot reopen it.
1977 if (!IDecl->hasDefinition())
1978 IDecl->startDefinition();
1981 ObjCImplementationDecl* IMPDecl =
1982 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1983 ClassLoc, AtClassImplLoc, SuperClassLoc);
1985 if (CheckObjCDeclScope(IMPDecl))
1986 return ActOnObjCContainerStartDefinition(IMPDecl);
1988 // Check that there is no duplicate implementation of this class.
1989 if (IDecl->getImplementation()) {
1990 // FIXME: Don't leak everything!
1991 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1992 Diag(IDecl->getImplementation()->getLocation(),
1993 diag::note_previous_definition);
1994 IMPDecl->setInvalidDecl();
1995 } else { // add it to the list.
1996 IDecl->setImplementation(IMPDecl);
1997 PushOnScopeChains(IMPDecl, TUScope);
1998 // Warn on implementating deprecated class under
1999 // -Wdeprecated-implementations flag.
2000 DiagnoseObjCImplementedDeprecations(*this,
2001 dyn_cast<NamedDecl>(IDecl),
2002 IMPDecl->getLocation(), 1);
2005 // If the superclass has the objc_runtime_visible attribute, we
2006 // cannot implement a subclass of it.
2007 if (IDecl->getSuperClass() &&
2008 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2009 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2010 << IDecl->getDeclName()
2011 << IDecl->getSuperClass()->getDeclName();
2014 return ActOnObjCContainerStartDefinition(IMPDecl);
2017 Sema::DeclGroupPtrTy
2018 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2019 SmallVector<Decl *, 64> DeclsInGroup;
2020 DeclsInGroup.reserve(Decls.size() + 1);
2022 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2023 Decl *Dcl = Decls[i];
2026 if (Dcl->getDeclContext()->isFileContext())
2027 Dcl->setTopLevelDeclInObjCContainer();
2028 DeclsInGroup.push_back(Dcl);
2031 DeclsInGroup.push_back(ObjCImpDecl);
2033 return BuildDeclaratorGroup(DeclsInGroup);
2036 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2037 ObjCIvarDecl **ivars, unsigned numIvars,
2038 SourceLocation RBrace) {
2039 assert(ImpDecl && "missing implementation decl");
2040 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2043 /// Check case of non-existing \@interface decl.
2044 /// (legacy objective-c \@implementation decl without an \@interface decl).
2045 /// Add implementations's ivar to the synthesize class's ivar list.
2046 if (IDecl->isImplicitInterfaceDecl()) {
2047 IDecl->setEndOfDefinitionLoc(RBrace);
2048 // Add ivar's to class's DeclContext.
2049 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2050 ivars[i]->setLexicalDeclContext(ImpDecl);
2051 IDecl->makeDeclVisibleInContext(ivars[i]);
2052 ImpDecl->addDecl(ivars[i]);
2057 // If implementation has empty ivar list, just return.
2061 assert(ivars && "missing @implementation ivars");
2062 if (LangOpts.ObjCRuntime.isNonFragile()) {
2063 if (ImpDecl->getSuperClass())
2064 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2065 for (unsigned i = 0; i < numIvars; i++) {
2066 ObjCIvarDecl* ImplIvar = ivars[i];
2067 if (const ObjCIvarDecl *ClsIvar =
2068 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2069 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2070 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2073 // Check class extensions (unnamed categories) for duplicate ivars.
2074 for (const auto *CDecl : IDecl->visible_extensions()) {
2075 if (const ObjCIvarDecl *ClsExtIvar =
2076 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2077 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2078 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2082 // Instance ivar to Implementation's DeclContext.
2083 ImplIvar->setLexicalDeclContext(ImpDecl);
2084 IDecl->makeDeclVisibleInContext(ImplIvar);
2085 ImpDecl->addDecl(ImplIvar);
2089 // Check interface's Ivar list against those in the implementation.
2090 // names and types must match.
2093 ObjCInterfaceDecl::ivar_iterator
2094 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2095 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2096 ObjCIvarDecl* ImplIvar = ivars[j++];
2097 ObjCIvarDecl* ClsIvar = *IVI;
2098 assert (ImplIvar && "missing implementation ivar");
2099 assert (ClsIvar && "missing class ivar");
2101 // First, make sure the types match.
2102 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2103 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2104 << ImplIvar->getIdentifier()
2105 << ImplIvar->getType() << ClsIvar->getType();
2106 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2107 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2108 ImplIvar->getBitWidthValue(Context) !=
2109 ClsIvar->getBitWidthValue(Context)) {
2110 Diag(ImplIvar->getBitWidth()->getLocStart(),
2111 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2112 Diag(ClsIvar->getBitWidth()->getLocStart(),
2113 diag::note_previous_definition);
2115 // Make sure the names are identical.
2116 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2117 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2118 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2119 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2125 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2126 else if (IVI != IVE)
2127 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2130 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2131 ObjCMethodDecl *method,
2132 bool &IncompleteImpl,
2134 NamedDecl *NeededFor = nullptr) {
2135 // No point warning no definition of method which is 'unavailable'.
2136 switch (method->getAvailability()) {
2141 // Don't warn about unavailable or not-yet-introduced methods.
2142 case AR_NotYetIntroduced:
2143 case AR_Unavailable:
2147 // FIXME: For now ignore 'IncompleteImpl'.
2148 // Previously we grouped all unimplemented methods under a single
2149 // warning, but some users strongly voiced that they would prefer
2150 // separate warnings. We will give that approach a try, as that
2151 // matches what we do with protocols.
2153 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2159 // Issue a note to the original declaration.
2160 SourceLocation MethodLoc = method->getLocStart();
2161 if (MethodLoc.isValid())
2162 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2165 /// Determines if type B can be substituted for type A. Returns true if we can
2166 /// guarantee that anything that the user will do to an object of type A can
2167 /// also be done to an object of type B. This is trivially true if the two
2168 /// types are the same, or if B is a subclass of A. It becomes more complex
2169 /// in cases where protocols are involved.
2171 /// Object types in Objective-C describe the minimum requirements for an
2172 /// object, rather than providing a complete description of a type. For
2173 /// example, if A is a subclass of B, then B* may refer to an instance of A.
2174 /// The principle of substitutability means that we may use an instance of A
2175 /// anywhere that we may use an instance of B - it will implement all of the
2176 /// ivars of B and all of the methods of B.
2178 /// This substitutability is important when type checking methods, because
2179 /// the implementation may have stricter type definitions than the interface.
2180 /// The interface specifies minimum requirements, but the implementation may
2181 /// have more accurate ones. For example, a method may privately accept
2182 /// instances of B, but only publish that it accepts instances of A. Any
2183 /// object passed to it will be type checked against B, and so will implicitly
2184 /// by a valid A*. Similarly, a method may return a subclass of the class that
2185 /// it is declared as returning.
2187 /// This is most important when considering subclassing. A method in a
2188 /// subclass must accept any object as an argument that its superclass's
2189 /// implementation accepts. It may, however, accept a more general type
2190 /// without breaking substitutability (i.e. you can still use the subclass
2191 /// anywhere that you can use the superclass, but not vice versa). The
2192 /// converse requirement applies to return types: the return type for a
2193 /// subclass method must be a valid object of the kind that the superclass
2194 /// advertises, but it may be specified more accurately. This avoids the need
2195 /// for explicit down-casting by callers.
2197 /// Note: This is a stricter requirement than for assignment.
2198 static bool isObjCTypeSubstitutable(ASTContext &Context,
2199 const ObjCObjectPointerType *A,
2200 const ObjCObjectPointerType *B,
2202 // Reject a protocol-unqualified id.
2203 if (rejectId && B->isObjCIdType()) return false;
2205 // If B is a qualified id, then A must also be a qualified id and it must
2206 // implement all of the protocols in B. It may not be a qualified class.
2207 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2208 // stricter definition so it is not substitutable for id<A>.
2209 if (B->isObjCQualifiedIdType()) {
2210 return A->isObjCQualifiedIdType() &&
2211 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2217 // id is a special type that bypasses type checking completely. We want a
2218 // warning when it is used in one place but not another.
2219 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2222 // If B is a qualified id, then A must also be a qualified id (which it isn't
2223 // if we've got this far)
2224 if (B->isObjCQualifiedIdType()) return false;
2227 // Now we know that A and B are (potentially-qualified) class types. The
2228 // normal rules for assignment apply.
2229 return Context.canAssignObjCInterfaces(A, B);
2232 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2233 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2236 /// Determine whether two set of Objective-C declaration qualifiers conflict.
2237 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2238 Decl::ObjCDeclQualifier y) {
2239 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2240 (y & ~Decl::OBJC_TQ_CSNullability);
2243 static bool CheckMethodOverrideReturn(Sema &S,
2244 ObjCMethodDecl *MethodImpl,
2245 ObjCMethodDecl *MethodDecl,
2246 bool IsProtocolMethodDecl,
2247 bool IsOverridingMode,
2249 if (IsProtocolMethodDecl &&
2250 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2251 MethodImpl->getObjCDeclQualifier())) {
2253 S.Diag(MethodImpl->getLocation(),
2255 ? diag::warn_conflicting_overriding_ret_type_modifiers
2256 : diag::warn_conflicting_ret_type_modifiers))
2257 << MethodImpl->getDeclName()
2258 << MethodImpl->getReturnTypeSourceRange();
2259 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2260 << MethodDecl->getReturnTypeSourceRange();
2265 if (Warn && IsOverridingMode &&
2266 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2267 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2268 MethodDecl->getReturnType(),
2270 auto nullabilityMethodImpl =
2271 *MethodImpl->getReturnType()->getNullability(S.Context);
2272 auto nullabilityMethodDecl =
2273 *MethodDecl->getReturnType()->getNullability(S.Context);
2274 S.Diag(MethodImpl->getLocation(),
2275 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2276 << DiagNullabilityKind(
2277 nullabilityMethodImpl,
2278 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2280 << DiagNullabilityKind(
2281 nullabilityMethodDecl,
2282 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2284 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2287 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2288 MethodDecl->getReturnType()))
2294 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2295 : diag::warn_conflicting_ret_types;
2297 // Mismatches between ObjC pointers go into a different warning
2298 // category, and sometimes they're even completely whitelisted.
2299 if (const ObjCObjectPointerType *ImplPtrTy =
2300 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2301 if (const ObjCObjectPointerType *IfacePtrTy =
2302 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2303 // Allow non-matching return types as long as they don't violate
2304 // the principle of substitutability. Specifically, we permit
2305 // return types that are subclasses of the declared return type,
2306 // or that are more-qualified versions of the declared type.
2307 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2311 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2312 : diag::warn_non_covariant_ret_types;
2316 S.Diag(MethodImpl->getLocation(), DiagID)
2317 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2318 << MethodImpl->getReturnType()
2319 << MethodImpl->getReturnTypeSourceRange();
2320 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2321 ? diag::note_previous_declaration
2322 : diag::note_previous_definition)
2323 << MethodDecl->getReturnTypeSourceRange();
2327 static bool CheckMethodOverrideParam(Sema &S,
2328 ObjCMethodDecl *MethodImpl,
2329 ObjCMethodDecl *MethodDecl,
2330 ParmVarDecl *ImplVar,
2331 ParmVarDecl *IfaceVar,
2332 bool IsProtocolMethodDecl,
2333 bool IsOverridingMode,
2335 if (IsProtocolMethodDecl &&
2336 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2337 IfaceVar->getObjCDeclQualifier())) {
2339 if (IsOverridingMode)
2340 S.Diag(ImplVar->getLocation(),
2341 diag::warn_conflicting_overriding_param_modifiers)
2342 << getTypeRange(ImplVar->getTypeSourceInfo())
2343 << MethodImpl->getDeclName();
2344 else S.Diag(ImplVar->getLocation(),
2345 diag::warn_conflicting_param_modifiers)
2346 << getTypeRange(ImplVar->getTypeSourceInfo())
2347 << MethodImpl->getDeclName();
2348 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2349 << getTypeRange(IfaceVar->getTypeSourceInfo());
2355 QualType ImplTy = ImplVar->getType();
2356 QualType IfaceTy = IfaceVar->getType();
2357 if (Warn && IsOverridingMode &&
2358 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2359 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2360 S.Diag(ImplVar->getLocation(),
2361 diag::warn_conflicting_nullability_attr_overriding_param_types)
2362 << DiagNullabilityKind(
2363 *ImplTy->getNullability(S.Context),
2364 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2366 << DiagNullabilityKind(
2367 *IfaceTy->getNullability(S.Context),
2368 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2370 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2372 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2378 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2379 : diag::warn_conflicting_param_types;
2381 // Mismatches between ObjC pointers go into a different warning
2382 // category, and sometimes they're even completely whitelisted.
2383 if (const ObjCObjectPointerType *ImplPtrTy =
2384 ImplTy->getAs<ObjCObjectPointerType>()) {
2385 if (const ObjCObjectPointerType *IfacePtrTy =
2386 IfaceTy->getAs<ObjCObjectPointerType>()) {
2387 // Allow non-matching argument types as long as they don't
2388 // violate the principle of substitutability. Specifically, the
2389 // implementation must accept any objects that the superclass
2390 // accepts, however it may also accept others.
2391 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2395 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2396 : diag::warn_non_contravariant_param_types;
2400 S.Diag(ImplVar->getLocation(), DiagID)
2401 << getTypeRange(ImplVar->getTypeSourceInfo())
2402 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2403 S.Diag(IfaceVar->getLocation(),
2404 (IsOverridingMode ? diag::note_previous_declaration
2405 : diag::note_previous_definition))
2406 << getTypeRange(IfaceVar->getTypeSourceInfo());
2410 /// In ARC, check whether the conventional meanings of the two methods
2411 /// match. If they don't, it's a hard error.
2412 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2413 ObjCMethodDecl *decl) {
2414 ObjCMethodFamily implFamily = impl->getMethodFamily();
2415 ObjCMethodFamily declFamily = decl->getMethodFamily();
2416 if (implFamily == declFamily) return false;
2418 // Since conventions are sorted by selector, the only possibility is
2419 // that the types differ enough to cause one selector or the other
2420 // to fall out of the family.
2421 assert(implFamily == OMF_None || declFamily == OMF_None);
2423 // No further diagnostics required on invalid declarations.
2424 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2426 const ObjCMethodDecl *unmatched = impl;
2427 ObjCMethodFamily family = declFamily;
2428 unsigned errorID = diag::err_arc_lost_method_convention;
2429 unsigned noteID = diag::note_arc_lost_method_convention;
2430 if (declFamily == OMF_None) {
2432 family = implFamily;
2433 errorID = diag::err_arc_gained_method_convention;
2434 noteID = diag::note_arc_gained_method_convention;
2437 // Indexes into a %select clause in the diagnostic.
2438 enum FamilySelector {
2439 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2441 FamilySelector familySelector = FamilySelector();
2444 case OMF_None: llvm_unreachable("logic error, no method convention");
2447 case OMF_autorelease:
2450 case OMF_retainCount:
2452 case OMF_initialize:
2453 case OMF_performSelector:
2454 // Mismatches for these methods don't change ownership
2455 // conventions, so we don't care.
2458 case OMF_init: familySelector = F_init; break;
2459 case OMF_alloc: familySelector = F_alloc; break;
2460 case OMF_copy: familySelector = F_copy; break;
2461 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2462 case OMF_new: familySelector = F_new; break;
2465 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2466 ReasonSelector reasonSelector;
2468 // The only reason these methods don't fall within their families is
2469 // due to unusual result types.
2470 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2471 reasonSelector = R_UnrelatedReturn;
2473 reasonSelector = R_NonObjectReturn;
2476 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2477 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2482 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2483 ObjCMethodDecl *MethodDecl,
2484 bool IsProtocolMethodDecl) {
2485 if (getLangOpts().ObjCAutoRefCount &&
2486 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2489 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2490 IsProtocolMethodDecl, false,
2493 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2494 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2495 EF = MethodDecl->param_end();
2496 IM != EM && IF != EF; ++IM, ++IF) {
2497 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2498 IsProtocolMethodDecl, false, true);
2501 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2502 Diag(ImpMethodDecl->getLocation(),
2503 diag::warn_conflicting_variadic);
2504 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2508 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2509 ObjCMethodDecl *Overridden,
2510 bool IsProtocolMethodDecl) {
2512 CheckMethodOverrideReturn(*this, Method, Overridden,
2513 IsProtocolMethodDecl, true,
2516 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2517 IF = Overridden->param_begin(), EM = Method->param_end(),
2518 EF = Overridden->param_end();
2519 IM != EM && IF != EF; ++IM, ++IF) {
2520 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2521 IsProtocolMethodDecl, true, true);
2524 if (Method->isVariadic() != Overridden->isVariadic()) {
2525 Diag(Method->getLocation(),
2526 diag::warn_conflicting_overriding_variadic);
2527 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2531 /// WarnExactTypedMethods - This routine issues a warning if method
2532 /// implementation declaration matches exactly that of its declaration.
2533 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2534 ObjCMethodDecl *MethodDecl,
2535 bool IsProtocolMethodDecl) {
2536 // don't issue warning when protocol method is optional because primary
2537 // class is not required to implement it and it is safe for protocol
2539 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2541 // don't issue warning when primary class's method is
2542 // depecated/unavailable.
2543 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2544 MethodDecl->hasAttr<DeprecatedAttr>())
2547 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2548 IsProtocolMethodDecl, false, false);
2550 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2551 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2552 EF = MethodDecl->param_end();
2553 IM != EM && IF != EF; ++IM, ++IF) {
2554 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2556 IsProtocolMethodDecl, false, false);
2561 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2563 match = !(MethodDecl->isClassMethod() &&
2564 MethodDecl->getSelector() == GetNullarySelector("load", Context));
2567 Diag(ImpMethodDecl->getLocation(),
2568 diag::warn_category_method_impl_match);
2569 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2570 << MethodDecl->getDeclName();
2574 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2575 /// improve the efficiency of selector lookups and type checking by associating
2576 /// with each protocol / interface / category the flattened instance tables. If
2577 /// we used an immutable set to keep the table then it wouldn't add significant
2578 /// memory cost and it would be handy for lookups.
2580 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2581 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2583 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2584 ProtocolNameSet &PNS) {
2585 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2586 PNS.insert(PDecl->getIdentifier());
2587 for (const auto *PI : PDecl->protocols())
2588 findProtocolsWithExplicitImpls(PI, PNS);
2591 /// Recursively populates a set with all conformed protocols in a class
2592 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2594 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2595 ProtocolNameSet &PNS) {
2599 for (const auto *I : Super->all_referenced_protocols())
2600 findProtocolsWithExplicitImpls(I, PNS);
2602 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2605 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
2606 /// Declared in protocol, and those referenced by it.
2607 static void CheckProtocolMethodDefs(Sema &S,
2608 SourceLocation ImpLoc,
2609 ObjCProtocolDecl *PDecl,
2610 bool& IncompleteImpl,
2611 const Sema::SelectorSet &InsMap,
2612 const Sema::SelectorSet &ClsMap,
2613 ObjCContainerDecl *CDecl,
2614 LazyProtocolNameSet &ProtocolsExplictImpl) {
2615 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2616 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2617 : dyn_cast<ObjCInterfaceDecl>(CDecl);
2618 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2620 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2621 ObjCInterfaceDecl *NSIDecl = nullptr;
2623 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2624 // then we should check if any class in the super class hierarchy also
2625 // conforms to this protocol, either directly or via protocol inheritance.
2626 // If so, we can skip checking this protocol completely because we
2627 // know that a parent class already satisfies this protocol.
2629 // Note: we could generalize this logic for all protocols, and merely
2630 // add the limit on looking at the super class chain for just
2631 // specially marked protocols. This may be a good optimization. This
2632 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2633 // protocols for now for controlled evaluation.
2634 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2635 if (!ProtocolsExplictImpl) {
2636 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2637 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2639 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2640 ProtocolsExplictImpl->end())
2643 // If no super class conforms to the protocol, we should not search
2644 // for methods in the super class to implicitly satisfy the protocol.
2648 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2649 // check to see if class implements forwardInvocation method and objects
2650 // of this class are derived from 'NSProxy' so that to forward requests
2651 // from one object to another.
2652 // Under such conditions, which means that every method possible is
2653 // implemented in the class, we should not issue "Method definition not
2655 // FIXME: Use a general GetUnarySelector method for this.
2656 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2657 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2658 if (InsMap.count(fISelector))
2659 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2660 // need be implemented in the implementation.
2661 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2664 // If this is a forward protocol declaration, get its definition.
2665 if (!PDecl->isThisDeclarationADefinition() &&
2666 PDecl->getDefinition())
2667 PDecl = PDecl->getDefinition();
2669 // If a method lookup fails locally we still need to look and see if
2670 // the method was implemented by a base class or an inherited
2671 // protocol. This lookup is slow, but occurs rarely in correct code
2672 // and otherwise would terminate in a warning.
2674 // check unimplemented instance methods.
2676 for (auto *method : PDecl->instance_methods()) {
2677 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2678 !method->isPropertyAccessor() &&
2679 !InsMap.count(method->getSelector()) &&
2680 (!Super || !Super->lookupMethod(method->getSelector(),
2681 true /* instance */,
2682 false /* shallowCategory */,
2683 true /* followsSuper */,
2684 nullptr /* category */))) {
2685 // If a method is not implemented in the category implementation but
2686 // has been declared in its primary class, superclass,
2687 // or in one of their protocols, no need to issue the warning.
2688 // This is because method will be implemented in the primary class
2689 // or one of its super class implementation.
2691 // Ugly, but necessary. Method declared in protcol might have
2692 // have been synthesized due to a property declared in the class which
2693 // uses the protocol.
2694 if (ObjCMethodDecl *MethodInClass =
2695 IDecl->lookupMethod(method->getSelector(),
2696 true /* instance */,
2697 true /* shallowCategoryLookup */,
2698 false /* followSuper */))
2699 if (C || MethodInClass->isPropertyAccessor())
2701 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2702 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2703 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
2708 // check unimplemented class methods
2709 for (auto *method : PDecl->class_methods()) {
2710 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2711 !ClsMap.count(method->getSelector()) &&
2712 (!Super || !Super->lookupMethod(method->getSelector(),
2713 false /* class method */,
2714 false /* shallowCategoryLookup */,
2715 true /* followSuper */,
2716 nullptr /* category */))) {
2717 // See above comment for instance method lookups.
2718 if (C && IDecl->lookupMethod(method->getSelector(),
2720 true /* shallowCategoryLookup */,
2721 false /* followSuper */))
2724 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2725 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2726 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
2730 // Check on this protocols's referenced protocols, recursively.
2731 for (auto *PI : PDecl->protocols())
2732 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
2733 CDecl, ProtocolsExplictImpl);
2736 /// MatchAllMethodDeclarations - Check methods declared in interface
2737 /// or protocol against those declared in their implementations.
2739 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2740 const SelectorSet &ClsMap,
2741 SelectorSet &InsMapSeen,
2742 SelectorSet &ClsMapSeen,
2743 ObjCImplDecl* IMPDecl,
2744 ObjCContainerDecl* CDecl,
2745 bool &IncompleteImpl,
2746 bool ImmediateClass,
2747 bool WarnCategoryMethodImpl) {
2748 // Check and see if instance methods in class interface have been
2749 // implemented in the implementation class. If so, their types match.
2750 for (auto *I : CDecl->instance_methods()) {
2751 if (!InsMapSeen.insert(I->getSelector()).second)
2753 if (!I->isPropertyAccessor() &&
2754 !InsMap.count(I->getSelector())) {
2756 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2757 diag::warn_undef_method_impl);
2760 ObjCMethodDecl *ImpMethodDecl =
2761 IMPDecl->getInstanceMethod(I->getSelector());
2762 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2763 "Expected to find the method through lookup as well");
2764 // ImpMethodDecl may be null as in a @dynamic property.
2765 if (ImpMethodDecl) {
2766 if (!WarnCategoryMethodImpl)
2767 WarnConflictingTypedMethods(ImpMethodDecl, I,
2768 isa<ObjCProtocolDecl>(CDecl));
2769 else if (!I->isPropertyAccessor())
2770 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2775 // Check and see if class methods in class interface have been
2776 // implemented in the implementation class. If so, their types match.
2777 for (auto *I : CDecl->class_methods()) {
2778 if (!ClsMapSeen.insert(I->getSelector()).second)
2780 if (!I->isPropertyAccessor() &&
2781 !ClsMap.count(I->getSelector())) {
2783 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2784 diag::warn_undef_method_impl);
2786 ObjCMethodDecl *ImpMethodDecl =
2787 IMPDecl->getClassMethod(I->getSelector());
2788 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2789 "Expected to find the method through lookup as well");
2790 // ImpMethodDecl may be null as in a @dynamic property.
2791 if (ImpMethodDecl) {
2792 if (!WarnCategoryMethodImpl)
2793 WarnConflictingTypedMethods(ImpMethodDecl, I,
2794 isa<ObjCProtocolDecl>(CDecl));
2795 else if (!I->isPropertyAccessor())
2796 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2801 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2802 // Also, check for methods declared in protocols inherited by
2804 for (auto *PI : PD->protocols())
2805 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2806 IMPDecl, PI, IncompleteImpl, false,
2807 WarnCategoryMethodImpl);
2810 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2811 // when checking that methods in implementation match their declaration,
2812 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2813 // extension; as well as those in categories.
2814 if (!WarnCategoryMethodImpl) {
2815 for (auto *Cat : I->visible_categories())
2816 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2817 IMPDecl, Cat, IncompleteImpl,
2818 ImmediateClass && Cat->IsClassExtension(),
2819 WarnCategoryMethodImpl);
2821 // Also methods in class extensions need be looked at next.
2822 for (auto *Ext : I->visible_extensions())
2823 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2824 IMPDecl, Ext, IncompleteImpl, false,
2825 WarnCategoryMethodImpl);
2828 // Check for any implementation of a methods declared in protocol.
2829 for (auto *PI : I->all_referenced_protocols())
2830 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2831 IMPDecl, PI, IncompleteImpl, false,
2832 WarnCategoryMethodImpl);
2834 // FIXME. For now, we are not checking for extact match of methods
2835 // in category implementation and its primary class's super class.
2836 if (!WarnCategoryMethodImpl && I->getSuperClass())
2837 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2839 I->getSuperClass(), IncompleteImpl, false);
2843 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2844 /// category matches with those implemented in its primary class and
2845 /// warns each time an exact match is found.
2846 void Sema::CheckCategoryVsClassMethodMatches(
2847 ObjCCategoryImplDecl *CatIMPDecl) {
2848 // Get category's primary class.
2849 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2852 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2855 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2856 SelectorSet InsMap, ClsMap;
2858 for (const auto *I : CatIMPDecl->instance_methods()) {
2859 Selector Sel = I->getSelector();
2860 // When checking for methods implemented in the category, skip over
2861 // those declared in category class's super class. This is because
2862 // the super class must implement the method.
2863 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2868 for (const auto *I : CatIMPDecl->class_methods()) {
2869 Selector Sel = I->getSelector();
2870 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2874 if (InsMap.empty() && ClsMap.empty())
2877 SelectorSet InsMapSeen, ClsMapSeen;
2878 bool IncompleteImpl = false;
2879 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2881 IncompleteImpl, false,
2882 true /*WarnCategoryMethodImpl*/);
2885 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2886 ObjCContainerDecl* CDecl,
2887 bool IncompleteImpl) {
2889 // Check and see if instance methods in class interface have been
2890 // implemented in the implementation class.
2891 for (const auto *I : IMPDecl->instance_methods())
2892 InsMap.insert(I->getSelector());
2894 // Add the selectors for getters/setters of @dynamic properties.
2895 for (const auto *PImpl : IMPDecl->property_impls()) {
2896 // We only care about @dynamic implementations.
2897 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2900 const auto *P = PImpl->getPropertyDecl();
2903 InsMap.insert(P->getGetterName());
2904 if (!P->getSetterName().isNull())
2905 InsMap.insert(P->getSetterName());
2908 // Check and see if properties declared in the interface have either 1)
2909 // an implementation or 2) there is a @synthesize/@dynamic implementation
2910 // of the property in the @implementation.
2911 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2912 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2913 LangOpts.ObjCRuntime.isNonFragile() &&
2914 !IDecl->isObjCRequiresPropertyDefs();
2915 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2918 // Diagnose null-resettable synthesized setters.
2919 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2922 for (const auto *I : IMPDecl->class_methods())
2923 ClsMap.insert(I->getSelector());
2925 // Check for type conflict of methods declared in a class/protocol and
2926 // its implementation; if any.
2927 SelectorSet InsMapSeen, ClsMapSeen;
2928 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2930 IncompleteImpl, true);
2932 // check all methods implemented in category against those declared
2933 // in its primary class.
2934 if (ObjCCategoryImplDecl *CatDecl =
2935 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2936 CheckCategoryVsClassMethodMatches(CatDecl);
2938 // Check the protocol list for unimplemented methods in the @implementation
2940 // Check and see if class methods in class interface have been
2941 // implemented in the implementation class.
2943 LazyProtocolNameSet ExplicitImplProtocols;
2945 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2946 for (auto *PI : I->all_referenced_protocols())
2947 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2948 InsMap, ClsMap, I, ExplicitImplProtocols);
2949 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2950 // For extended class, unimplemented methods in its protocols will
2951 // be reported in the primary class.
2952 if (!C->IsClassExtension()) {
2953 for (auto *P : C->protocols())
2954 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2955 IncompleteImpl, InsMap, ClsMap, CDecl,
2956 ExplicitImplProtocols);
2957 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2958 /*SynthesizeProperties=*/false);
2961 llvm_unreachable("invalid ObjCContainerDecl type.");
2964 Sema::DeclGroupPtrTy
2965 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2966 IdentifierInfo **IdentList,
2967 SourceLocation *IdentLocs,
2968 ArrayRef<ObjCTypeParamList *> TypeParamLists,
2970 SmallVector<Decl *, 8> DeclsInGroup;
2971 for (unsigned i = 0; i != NumElts; ++i) {
2972 // Check for another declaration kind with the same name.
2974 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2975 LookupOrdinaryName, ForRedeclaration);
2976 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2977 // GCC apparently allows the following idiom:
2979 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2980 // @class XCElementToggler;
2982 // Here we have chosen to ignore the forward class declaration
2983 // with a warning. Since this is the implied behavior.
2984 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2985 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2986 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2987 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2989 // a forward class declaration matching a typedef name of a class refers
2990 // to the underlying class. Just ignore the forward class with a warning
2991 // as this will force the intended behavior which is to lookup the
2993 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2994 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2996 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3002 // Create a declaration to describe this forward declaration.
3003 ObjCInterfaceDecl *PrevIDecl
3004 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3006 IdentifierInfo *ClassName = IdentList[i];
3007 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3008 // A previous decl with a different name is because of
3009 // @compatibility_alias, for example:
3012 // @compatibility_alias OldImage NewImage;
3014 // A lookup for 'OldImage' will return the 'NewImage' decl.
3016 // In such a case use the real declaration name, instead of the alias one,
3017 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3018 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3019 // has been aliased.
3020 ClassName = PrevIDecl->getIdentifier();
3023 // If this forward declaration has type parameters, compare them with the
3024 // type parameters of the previous declaration.
3025 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3026 if (PrevIDecl && TypeParams) {
3027 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3028 // Check for consistency with the previous declaration.
3029 if (checkTypeParamListConsistency(
3030 *this, PrevTypeParams, TypeParams,
3031 TypeParamListContext::ForwardDeclaration)) {
3032 TypeParams = nullptr;
3034 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3035 // The @interface does not have type parameters. Complain.
3036 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3038 << TypeParams->getSourceRange();
3039 Diag(Def->getLocation(), diag::note_defined_here)
3042 TypeParams = nullptr;
3046 ObjCInterfaceDecl *IDecl
3047 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3048 ClassName, TypeParams, PrevIDecl,
3050 IDecl->setAtEndRange(IdentLocs[i]);
3052 PushOnScopeChains(IDecl, TUScope);
3053 CheckObjCDeclScope(IDecl);
3054 DeclsInGroup.push_back(IDecl);
3057 return BuildDeclaratorGroup(DeclsInGroup);
3060 static bool tryMatchRecordTypes(ASTContext &Context,
3061 Sema::MethodMatchStrategy strategy,
3062 const Type *left, const Type *right);
3064 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3065 QualType leftQT, QualType rightQT) {
3067 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3069 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3071 if (left == right) return true;
3073 // If we're doing a strict match, the types have to match exactly.
3074 if (strategy == Sema::MMS_strict) return false;
3076 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3078 // Otherwise, use this absurdly complicated algorithm to try to
3079 // validate the basic, low-level compatibility of the two types.
3081 // As a minimum, require the sizes and alignments to match.
3082 TypeInfo LeftTI = Context.getTypeInfo(left);
3083 TypeInfo RightTI = Context.getTypeInfo(right);
3084 if (LeftTI.Width != RightTI.Width)
3087 if (LeftTI.Align != RightTI.Align)
3090 // Consider all the kinds of non-dependent canonical types:
3091 // - functions and arrays aren't possible as return and parameter types
3093 // - vector types of equal size can be arbitrarily mixed
3094 if (isa<VectorType>(left)) return isa<VectorType>(right);
3095 if (isa<VectorType>(right)) return false;
3097 // - references should only match references of identical type
3098 // - structs, unions, and Objective-C objects must match more-or-less
3100 // - everything else should be a scalar
3101 if (!left->isScalarType() || !right->isScalarType())
3102 return tryMatchRecordTypes(Context, strategy, left, right);
3104 // Make scalars agree in kind, except count bools as chars, and group
3105 // all non-member pointers together.
3106 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3107 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3108 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3109 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3110 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3111 leftSK = Type::STK_ObjCObjectPointer;
3112 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3113 rightSK = Type::STK_ObjCObjectPointer;
3115 // Note that data member pointers and function member pointers don't
3116 // intermix because of the size differences.
3118 return (leftSK == rightSK);
3121 static bool tryMatchRecordTypes(ASTContext &Context,
3122 Sema::MethodMatchStrategy strategy,
3123 const Type *lt, const Type *rt) {
3124 assert(lt && rt && lt != rt);
3126 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3127 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3128 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3130 // Require union-hood to match.
3131 if (left->isUnion() != right->isUnion()) return false;
3133 // Require an exact match if either is non-POD.
3134 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3135 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3138 // Require size and alignment to match.
3139 TypeInfo LeftTI = Context.getTypeInfo(lt);
3140 TypeInfo RightTI = Context.getTypeInfo(rt);
3141 if (LeftTI.Width != RightTI.Width)
3144 if (LeftTI.Align != RightTI.Align)
3147 // Require fields to match.
3148 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3149 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3150 for (; li != le && ri != re; ++li, ++ri) {
3151 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3154 return (li == le && ri == re);
3157 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3158 /// returns true, or false, accordingly.
3159 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3160 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3161 const ObjCMethodDecl *right,
3162 MethodMatchStrategy strategy) {
3163 if (!matchTypes(Context, strategy, left->getReturnType(),
3164 right->getReturnType()))
3167 // If either is hidden, it is not considered to match.
3168 if (left->isHidden() || right->isHidden())
3171 if (getLangOpts().ObjCAutoRefCount &&
3172 (left->hasAttr<NSReturnsRetainedAttr>()
3173 != right->hasAttr<NSReturnsRetainedAttr>() ||
3174 left->hasAttr<NSConsumesSelfAttr>()
3175 != right->hasAttr<NSConsumesSelfAttr>()))
3178 ObjCMethodDecl::param_const_iterator
3179 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3180 re = right->param_end();
3182 for (; li != le && ri != re; ++li, ++ri) {
3183 assert(ri != right->param_end() && "Param mismatch");
3184 const ParmVarDecl *lparm = *li, *rparm = *ri;
3186 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3189 if (getLangOpts().ObjCAutoRefCount &&
3190 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3196 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3197 ObjCMethodDecl *MethodInList) {
3198 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3199 auto *MethodInListProtocol =
3200 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3201 // If this method belongs to a protocol but the method in list does not, or
3202 // vice versa, we say the context is not the same.
3203 if ((MethodProtocol && !MethodInListProtocol) ||
3204 (!MethodProtocol && MethodInListProtocol))
3207 if (MethodProtocol && MethodInListProtocol)
3210 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3211 ObjCInterfaceDecl *MethodInListInterface =
3212 MethodInList->getClassInterface();
3213 return MethodInterface == MethodInListInterface;
3216 void Sema::addMethodToGlobalList(ObjCMethodList *List,
3217 ObjCMethodDecl *Method) {
3218 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3219 // inside categories.
3220 if (ObjCCategoryDecl *CD =
3221 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3222 if (!CD->IsClassExtension() && List->getBits() < 2)
3223 List->setBits(List->getBits() + 1);
3225 // If the list is empty, make it a singleton list.
3226 if (List->getMethod() == nullptr) {
3227 List->setMethod(Method);
3228 List->setNext(nullptr);
3232 // We've seen a method with this name, see if we have already seen this type
3234 ObjCMethodList *Previous = List;
3235 ObjCMethodList *ListWithSameDeclaration = nullptr;
3236 for (; List; Previous = List, List = List->getNext()) {
3237 // If we are building a module, keep all of the methods.
3238 if (getLangOpts().isCompilingModule())
3241 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3243 // Looking for method with a type bound requires the correct context exists.
3244 // We need to insert a method into the list if the context is different.
3245 // If the method's declaration matches the list
3246 // a> the method belongs to a different context: we need to insert it, in
3247 // order to emit the availability message, we need to prioritize over
3248 // availability among the methods with the same declaration.
3249 // b> the method belongs to the same context: there is no need to insert a
3251 // If the method's declaration does not match the list, we insert it to the
3253 if (!SameDeclaration ||
3254 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3255 // Even if two method types do not match, we would like to say
3256 // there is more than one declaration so unavailability/deprecated
3257 // warning is not too noisy.
3258 if (!Method->isDefined())
3259 List->setHasMoreThanOneDecl(true);
3261 // For methods with the same declaration, the one that is deprecated
3262 // should be put in the front for better diagnostics.
3263 if (Method->isDeprecated() && SameDeclaration &&
3264 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3265 ListWithSameDeclaration = List;
3267 if (Method->isUnavailable() && SameDeclaration &&
3268 !ListWithSameDeclaration &&
3269 List->getMethod()->getAvailability() < AR_Deprecated)
3270 ListWithSameDeclaration = List;
3274 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3276 // Propagate the 'defined' bit.
3277 if (Method->isDefined())
3278 PrevObjCMethod->setDefined(true);
3280 // Objective-C doesn't allow an @interface for a class after its
3281 // @implementation. So if Method is not defined and there already is
3282 // an entry for this type signature, Method has to be for a different
3283 // class than PrevObjCMethod.
3284 List->setHasMoreThanOneDecl(true);
3287 // If a method is deprecated, push it in the global pool.
3288 // This is used for better diagnostics.
3289 if (Method->isDeprecated()) {
3290 if (!PrevObjCMethod->isDeprecated())
3291 List->setMethod(Method);
3293 // If the new method is unavailable, push it into global pool
3294 // unless previous one is deprecated.
3295 if (Method->isUnavailable()) {
3296 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3297 List->setMethod(Method);
3303 // We have a new signature for an existing method - add it.
3304 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3305 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3307 // We insert it right before ListWithSameDeclaration.
3308 if (ListWithSameDeclaration) {
3309 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3310 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3311 ListWithSameDeclaration->setMethod(Method);
3312 ListWithSameDeclaration->setNext(List);
3316 Previous->setNext(new (Mem) ObjCMethodList(Method));
3319 /// \brief Read the contents of the method pool for a given selector from
3320 /// external storage.
3321 void Sema::ReadMethodPool(Selector Sel) {
3322 assert(ExternalSource && "We need an external AST source");
3323 ExternalSource->ReadMethodPool(Sel);
3326 void Sema::updateOutOfDateSelector(Selector Sel) {
3327 if (!ExternalSource)
3329 ExternalSource->updateOutOfDateSelector(Sel);
3332 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3334 // Ignore methods of invalid containers.
3335 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3339 ReadMethodPool(Method->getSelector());
3341 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3342 if (Pos == MethodPool.end())
3343 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3344 GlobalMethods())).first;
3346 Method->setDefined(impl);
3348 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3349 addMethodToGlobalList(&Entry, Method);
3352 /// Determines if this is an "acceptable" loose mismatch in the global
3353 /// method pool. This exists mostly as a hack to get around certain
3354 /// global mismatches which we can't afford to make warnings / errors.
3355 /// Really, what we want is a way to take a method out of the global
3357 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3358 ObjCMethodDecl *other) {
3359 if (!chosen->isInstanceMethod())
3362 Selector sel = chosen->getSelector();
3363 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3366 // Don't complain about mismatches for -length if the method we
3367 // chose has an integral result type.
3368 return (chosen->getReturnType()->isIntegerType());
3371 /// Return true if the given method is wthin the type bound.
3372 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3373 const ObjCObjectType *TypeBound) {
3377 if (TypeBound->isObjCId())
3378 // FIXME: should we handle the case of bounding to id<A, B> differently?
3381 auto *BoundInterface = TypeBound->getInterface();
3382 assert(BoundInterface && "unexpected object type!");
3384 // Check if the Method belongs to a protocol. We should allow any method
3385 // defined in any protocol, because any subclass could adopt the protocol.
3386 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3387 if (MethodProtocol) {
3391 // If the Method belongs to a class, check if it belongs to the class
3392 // hierarchy of the class bound.
3393 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3394 // We allow methods declared within classes that are part of the hierarchy
3395 // of the class bound (superclass of, subclass of, or the same as the class
3397 return MethodInterface == BoundInterface ||
3398 MethodInterface->isSuperClassOf(BoundInterface) ||
3399 BoundInterface->isSuperClassOf(MethodInterface);
3401 llvm_unreachable("unknow method context");
3404 /// We first select the type of the method: Instance or Factory, then collect
3405 /// all methods with that type.
3406 bool Sema::CollectMultipleMethodsInGlobalPool(
3407 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3408 bool InstanceFirst, bool CheckTheOther,
3409 const ObjCObjectType *TypeBound) {
3411 ReadMethodPool(Sel);
3413 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3414 if (Pos == MethodPool.end())
3417 // Gather the non-hidden methods.
3418 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3420 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3421 if (M->getMethod() && !M->getMethod()->isHidden()) {
3422 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3423 Methods.push_back(M->getMethod());
3426 // Return if we find any method with the desired kind.
3427 if (!Methods.empty())
3428 return Methods.size() > 1;
3433 // Gather the other kind.
3434 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3436 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3437 if (M->getMethod() && !M->getMethod()->isHidden()) {
3438 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3439 Methods.push_back(M->getMethod());
3442 return Methods.size() > 1;
3445 bool Sema::AreMultipleMethodsInGlobalPool(
3446 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3447 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3448 // Diagnose finding more than one method in global pool.
3449 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3450 FilteredMethods.push_back(BestMethod);
3452 for (auto *M : Methods)
3453 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3454 FilteredMethods.push_back(M);
3456 if (FilteredMethods.size() > 1)
3457 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3460 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3461 // Test for no method in the pool which should not trigger any warning by
3463 if (Pos == MethodPool.end())
3465 ObjCMethodList &MethList =
3466 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3467 return MethList.hasMoreThanOneDecl();
3470 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3471 bool receiverIdOrClass,
3474 ReadMethodPool(Sel);
3476 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3477 if (Pos == MethodPool.end())
3480 // Gather the non-hidden methods.
3481 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3482 SmallVector<ObjCMethodDecl *, 4> Methods;
3483 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3484 if (M->getMethod() && !M->getMethod()->isHidden())
3485 return M->getMethod();
3490 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3491 Selector Sel, SourceRange R,
3492 bool receiverIdOrClass) {
3493 // We found multiple methods, so we may have to complain.
3494 bool issueDiagnostic = false, issueError = false;
3496 // We support a warning which complains about *any* difference in
3497 // method signature.
3498 bool strictSelectorMatch =
3499 receiverIdOrClass &&
3500 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3501 if (strictSelectorMatch) {
3502 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3503 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3504 issueDiagnostic = true;
3510 // If we didn't see any strict differences, we won't see any loose
3511 // differences. In ARC, however, we also need to check for loose
3512 // mismatches, because most of them are errors.
3513 if (!strictSelectorMatch ||
3514 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3515 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3516 // This checks if the methods differ in type mismatch.
3517 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3518 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3519 issueDiagnostic = true;
3520 if (getLangOpts().ObjCAutoRefCount)
3526 if (issueDiagnostic) {
3528 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3529 else if (strictSelectorMatch)
3530 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3532 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3534 Diag(Methods[0]->getLocStart(),
3535 issueError ? diag::note_possibility : diag::note_using)
3536 << Methods[0]->getSourceRange();
3537 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3538 Diag(Methods[I]->getLocStart(), diag::note_also_found)
3539 << Methods[I]->getSourceRange();
3544 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3545 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3546 if (Pos == MethodPool.end())
3549 GlobalMethods &Methods = Pos->second;
3550 for (const ObjCMethodList *Method = &Methods.first; Method;
3551 Method = Method->getNext())
3552 if (Method->getMethod() &&
3553 (Method->getMethod()->isDefined() ||
3554 Method->getMethod()->isPropertyAccessor()))
3555 return Method->getMethod();
3557 for (const ObjCMethodList *Method = &Methods.second; Method;
3558 Method = Method->getNext())
3559 if (Method->getMethod() &&
3560 (Method->getMethod()->isDefined() ||
3561 Method->getMethod()->isPropertyAccessor()))
3562 return Method->getMethod();
3567 HelperSelectorsForTypoCorrection(
3568 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3569 StringRef Typo, const ObjCMethodDecl * Method) {
3570 const unsigned MaxEditDistance = 1;
3571 unsigned BestEditDistance = MaxEditDistance + 1;
3572 std::string MethodName = Method->getSelector().getAsString();
3574 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3575 if (MinPossibleEditDistance > 0 &&
3576 Typo.size() / MinPossibleEditDistance < 1)
3578 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3579 if (EditDistance > MaxEditDistance)
3581 if (EditDistance == BestEditDistance)
3582 BestMethod.push_back(Method);
3583 else if (EditDistance < BestEditDistance) {
3585 BestMethod.push_back(Method);
3589 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3590 QualType ObjectType) {
3591 if (ObjectType.isNull())
3593 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3595 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3599 const ObjCMethodDecl *
3600 Sema::SelectorsForTypoCorrection(Selector Sel,
3601 QualType ObjectType) {
3602 unsigned NumArgs = Sel.getNumArgs();
3603 SmallVector<const ObjCMethodDecl *, 8> Methods;
3604 bool ObjectIsId = true, ObjectIsClass = true;
3605 if (ObjectType.isNull())
3606 ObjectIsId = ObjectIsClass = false;
3607 else if (!ObjectType->isObjCObjectPointerType())
3609 else if (const ObjCObjectPointerType *ObjCPtr =
3610 ObjectType->getAsObjCInterfacePointerType()) {
3611 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3612 ObjectIsId = ObjectIsClass = false;
3614 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3615 ObjectIsClass = false;
3616 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3621 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3622 e = MethodPool.end(); b != e; b++) {
3624 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3625 if (M->getMethod() &&
3626 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3627 (M->getMethod()->getSelector() != Sel)) {
3629 Methods.push_back(M->getMethod());
3630 else if (!ObjectIsClass &&
3631 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3633 Methods.push_back(M->getMethod());
3636 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3637 if (M->getMethod() &&
3638 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3639 (M->getMethod()->getSelector() != Sel)) {
3641 Methods.push_back(M->getMethod());
3642 else if (!ObjectIsId &&
3643 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3645 Methods.push_back(M->getMethod());
3649 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3650 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3651 HelperSelectorsForTypoCorrection(SelectedMethods,
3652 Sel.getAsString(), Methods[i]);
3654 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3657 /// DiagnoseDuplicateIvars -
3658 /// Check for duplicate ivars in the entire class at the start of
3659 /// \@implementation. This becomes necesssary because class extension can
3660 /// add ivars to a class in random order which will not be known until
3661 /// class's \@implementation is seen.
3662 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3663 ObjCInterfaceDecl *SID) {
3664 for (auto *Ivar : ID->ivars()) {
3665 if (Ivar->isInvalidDecl())
3667 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3668 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3670 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3671 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3672 Ivar->setInvalidDecl();
3678 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3679 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3680 if (S.getLangOpts().ObjCWeak) return;
3682 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3683 ivar; ivar = ivar->getNextIvar()) {
3684 if (ivar->isInvalidDecl()) continue;
3685 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3686 if (S.getLangOpts().ObjCWeakRuntime) {
3687 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3689 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3695 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3696 switch (CurContext->getDeclKind()) {
3697 case Decl::ObjCInterface:
3698 return Sema::OCK_Interface;
3699 case Decl::ObjCProtocol:
3700 return Sema::OCK_Protocol;
3701 case Decl::ObjCCategory:
3702 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3703 return Sema::OCK_ClassExtension;
3704 return Sema::OCK_Category;
3705 case Decl::ObjCImplementation:
3706 return Sema::OCK_Implementation;
3707 case Decl::ObjCCategoryImpl:
3708 return Sema::OCK_CategoryImplementation;
3711 return Sema::OCK_None;
3715 // Note: For class/category implementations, allMethods is always null.
3716 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3717 ArrayRef<DeclGroupPtrTy> allTUVars) {
3718 if (getObjCContainerKind() == Sema::OCK_None)
3721 assert(AtEnd.isValid() && "Invalid location for '@end'");
3723 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3724 Decl *ClassDecl = cast<Decl>(OCD);
3726 bool isInterfaceDeclKind =
3727 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3728 || isa<ObjCProtocolDecl>(ClassDecl);
3729 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3731 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3732 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3733 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3735 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
3736 ObjCMethodDecl *Method =
3737 cast_or_null<ObjCMethodDecl>(allMethods[i]);
3739 if (!Method) continue; // Already issued a diagnostic.
3740 if (Method->isInstanceMethod()) {
3741 /// Check for instance method of the same name with incompatible types
3742 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
3743 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3745 if ((isInterfaceDeclKind && PrevMethod && !match)
3746 || (checkIdenticalMethods && match)) {
3747 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3748 << Method->getDeclName();
3749 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3750 Method->setInvalidDecl();
3753 Method->setAsRedeclaration(PrevMethod);
3754 if (!Context.getSourceManager().isInSystemHeader(
3755 Method->getLocation()))
3756 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3757 << Method->getDeclName();
3758 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3760 InsMap[Method->getSelector()] = Method;
3761 /// The following allows us to typecheck messages to "id".
3762 AddInstanceMethodToGlobalPool(Method);
3765 /// Check for class method of the same name with incompatible types
3766 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
3767 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3769 if ((isInterfaceDeclKind && PrevMethod && !match)
3770 || (checkIdenticalMethods && match)) {
3771 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3772 << Method->getDeclName();
3773 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3774 Method->setInvalidDecl();
3777 Method->setAsRedeclaration(PrevMethod);
3778 if (!Context.getSourceManager().isInSystemHeader(
3779 Method->getLocation()))
3780 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3781 << Method->getDeclName();
3782 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3784 ClsMap[Method->getSelector()] = Method;
3785 AddFactoryMethodToGlobalPool(Method);
3789 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3790 // Nothing to do here.
3791 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
3792 // Categories are used to extend the class by declaring new methods.
3793 // By the same token, they are also used to add new properties. No
3794 // need to compare the added property to those in the class.
3796 if (C->IsClassExtension()) {
3797 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3798 DiagnoseClassExtensionDupMethods(C, CCPrimary);
3801 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
3802 if (CDecl->getIdentifier())
3803 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3804 // user-defined setter/getter. It also synthesizes setter/getter methods
3805 // and adds them to the DeclContext and global method pools.
3806 for (auto *I : CDecl->properties())
3807 ProcessPropertyDecl(I);
3808 CDecl->setAtEndRange(AtEnd);
3810 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
3811 IC->setAtEndRange(AtEnd);
3812 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
3813 // Any property declared in a class extension might have user
3814 // declared setter or getter in current class extension or one
3815 // of the other class extensions. Mark them as synthesized as
3816 // property will be synthesized when property with same name is
3817 // seen in the @implementation.
3818 for (const auto *Ext : IDecl->visible_extensions()) {
3819 for (const auto *Property : Ext->instance_properties()) {
3820 // Skip over properties declared @dynamic
3821 if (const ObjCPropertyImplDecl *PIDecl
3822 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3823 Property->getQueryKind()))
3824 if (PIDecl->getPropertyImplementation()
3825 == ObjCPropertyImplDecl::Dynamic)
3828 for (const auto *Ext : IDecl->visible_extensions()) {
3829 if (ObjCMethodDecl *GetterMethod
3830 = Ext->getInstanceMethod(Property->getGetterName()))
3831 GetterMethod->setPropertyAccessor(true);
3832 if (!Property->isReadOnly())
3833 if (ObjCMethodDecl *SetterMethod
3834 = Ext->getInstanceMethod(Property->getSetterName()))
3835 SetterMethod->setPropertyAccessor(true);
3839 ImplMethodsVsClassMethods(S, IC, IDecl);
3840 AtomicPropertySetterGetterRules(IC, IDecl);
3841 DiagnoseOwningPropertyGetterSynthesis(IC);
3842 DiagnoseUnusedBackingIvarInAccessor(S, IC);
3843 if (IDecl->hasDesignatedInitializers())
3844 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
3845 DiagnoseWeakIvars(*this, IC);
3847 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
3848 if (IDecl->getSuperClass() == nullptr) {
3849 // This class has no superclass, so check that it has been marked with
3850 // __attribute((objc_root_class)).
3851 if (!HasRootClassAttr) {
3852 SourceLocation DeclLoc(IDecl->getLocation());
3853 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
3854 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3855 << IDecl->getIdentifier();
3856 // See if NSObject is in the current scope, and if it is, suggest
3857 // adding " : NSObject " to the class declaration.
3858 NamedDecl *IF = LookupSingleName(TUScope,
3859 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3860 DeclLoc, LookupOrdinaryName);
3861 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3862 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3863 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3864 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3866 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3869 } else if (HasRootClassAttr) {
3870 // Complain that only root classes may have this attribute.
3871 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3874 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
3875 // An interface can subclass another interface with a
3876 // objc_subclassing_restricted attribute when it has that attribute as
3877 // well (because of interfaces imported from Swift). Therefore we have
3878 // to check if we can subclass in the implementation as well.
3879 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3880 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3881 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
3882 Diag(Super->getLocation(), diag::note_class_declared);
3886 if (LangOpts.ObjCRuntime.isNonFragile()) {
3887 while (IDecl->getSuperClass()) {
3888 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3889 IDecl = IDecl->getSuperClass();
3893 SetIvarInitializers(IC);
3894 } else if (ObjCCategoryImplDecl* CatImplClass =
3895 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
3896 CatImplClass->setAtEndRange(AtEnd);
3898 // Find category interface decl and then check that all methods declared
3899 // in this interface are implemented in the category @implementation.
3900 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
3901 if (ObjCCategoryDecl *Cat
3902 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3903 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
3906 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
3907 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
3908 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3909 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3910 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
3911 Diag(Super->getLocation(), diag::note_class_declared);
3915 if (isInterfaceDeclKind) {
3916 // Reject invalid vardecls.
3917 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
3918 DeclGroupRef DG = allTUVars[i].get();
3919 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3920 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
3921 if (!VDecl->hasExternalStorage())
3922 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
3926 ActOnObjCContainerFinishDefinition();
3928 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
3929 DeclGroupRef DG = allTUVars[i].get();
3930 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3931 (*I)->setTopLevelDeclInObjCContainer();
3932 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3935 ActOnDocumentableDecl(ClassDecl);
3939 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3940 /// objective-c's type qualifier from the parser version of the same info.
3941 static Decl::ObjCDeclQualifier
3942 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
3943 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
3946 /// \brief Check whether the declared result type of the given Objective-C
3947 /// method declaration is compatible with the method's class.
3949 static Sema::ResultTypeCompatibilityKind
3950 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3951 ObjCInterfaceDecl *CurrentClass) {
3952 QualType ResultType = Method->getReturnType();
3954 // If an Objective-C method inherits its related result type, then its
3955 // declared result type must be compatible with its own class type. The
3956 // declared result type is compatible if:
3957 if (const ObjCObjectPointerType *ResultObjectType
3958 = ResultType->getAs<ObjCObjectPointerType>()) {
3959 // - it is id or qualified id, or
3960 if (ResultObjectType->isObjCIdType() ||
3961 ResultObjectType->isObjCQualifiedIdType())
3962 return Sema::RTC_Compatible;
3965 if (ObjCInterfaceDecl *ResultClass
3966 = ResultObjectType->getInterfaceDecl()) {
3967 // - it is the same as the method's class type, or
3968 if (declaresSameEntity(CurrentClass, ResultClass))
3969 return Sema::RTC_Compatible;
3971 // - it is a superclass of the method's class type
3972 if (ResultClass->isSuperClassOf(CurrentClass))
3973 return Sema::RTC_Compatible;
3976 // Any Objective-C pointer type might be acceptable for a protocol
3977 // method; we just don't know.
3978 return Sema::RTC_Unknown;
3982 return Sema::RTC_Incompatible;
3986 /// A helper class for searching for methods which a particular method
3988 class OverrideSearch {
3991 ObjCMethodDecl *Method;
3992 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
3996 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
3997 Selector selector = method->getSelector();
3999 // Bypass this search if we've never seen an instance/class method
4000 // with this selector before.
4001 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4002 if (it == S.MethodPool.end()) {
4003 if (!S.getExternalSource()) return;
4004 S.ReadMethodPool(selector);
4006 it = S.MethodPool.find(selector);
4007 if (it == S.MethodPool.end())
4010 ObjCMethodList &list =
4011 method->isInstanceMethod() ? it->second.first : it->second.second;
4012 if (!list.getMethod()) return;
4014 ObjCContainerDecl *container
4015 = cast<ObjCContainerDecl>(method->getDeclContext());
4017 // Prevent the search from reaching this container again. This is
4018 // important with categories, which override methods from the
4019 // interface and each other.
4020 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4021 searchFromContainer(container);
4022 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4023 searchFromContainer(Interface);
4025 searchFromContainer(container);
4029 typedef llvm::SmallPtrSetImpl<ObjCMethodDecl*>::iterator iterator;
4030 iterator begin() const { return Overridden.begin(); }
4031 iterator end() const { return Overridden.end(); }
4034 void searchFromContainer(ObjCContainerDecl *container) {
4035 if (container->isInvalidDecl()) return;
4037 switch (container->getDeclKind()) {
4038 #define OBJCCONTAINER(type, base) \
4040 searchFrom(cast<type##Decl>(container)); \
4042 #define ABSTRACT_DECL(expansion)
4043 #define DECL(type, base) \
4045 #include "clang/AST/DeclNodes.inc"
4046 llvm_unreachable("not an ObjC container!");
4050 void searchFrom(ObjCProtocolDecl *protocol) {
4051 if (!protocol->hasDefinition())
4054 // A method in a protocol declaration overrides declarations from
4055 // referenced ("parent") protocols.
4056 search(protocol->getReferencedProtocols());
4059 void searchFrom(ObjCCategoryDecl *category) {
4060 // A method in a category declaration overrides declarations from
4061 // the main class and from protocols the category references.
4062 // The main class is handled in the constructor.
4063 search(category->getReferencedProtocols());
4066 void searchFrom(ObjCCategoryImplDecl *impl) {
4067 // A method in a category definition that has a category
4068 // declaration overrides declarations from the category
4070 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4072 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4075 // Otherwise it overrides declarations from the class.
4076 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4081 void searchFrom(ObjCInterfaceDecl *iface) {
4082 // A method in a class declaration overrides declarations from
4083 if (!iface->hasDefinition())
4087 for (auto *Cat : iface->known_categories())
4090 // - the super class, and
4091 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4094 // - any referenced protocols.
4095 search(iface->getReferencedProtocols());
4098 void searchFrom(ObjCImplementationDecl *impl) {
4099 // A method in a class implementation overrides declarations from
4100 // the class interface.
4101 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4105 void search(const ObjCProtocolList &protocols) {
4106 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4111 void search(ObjCContainerDecl *container) {
4112 // Check for a method in this container which matches this selector.
4113 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4114 Method->isInstanceMethod(),
4115 /*AllowHidden=*/true);
4117 // If we find one, record it and bail out.
4119 Overridden.insert(meth);
4123 // Otherwise, search for methods that a hypothetical method here
4124 // would have overridden.
4126 // Note that we're now in a recursive case.
4129 searchFromContainer(container);
4132 } // end anonymous namespace
4134 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4135 ObjCInterfaceDecl *CurrentClass,
4136 ResultTypeCompatibilityKind RTC) {
4137 // Search for overridden methods and merge information down from them.
4138 OverrideSearch overrides(*this, ObjCMethod);
4139 // Keep track if the method overrides any method in the class's base classes,
4140 // its protocols, or its categories' protocols; we will keep that info
4141 // in the ObjCMethodDecl.
4142 // For this info, a method in an implementation is not considered as
4143 // overriding the same method in the interface or its categories.
4144 bool hasOverriddenMethodsInBaseOrProtocol = false;
4145 for (OverrideSearch::iterator
4146 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4147 ObjCMethodDecl *overridden = *i;
4149 if (!hasOverriddenMethodsInBaseOrProtocol) {
4150 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4151 CurrentClass != overridden->getClassInterface() ||
4152 overridden->isOverriding()) {
4153 hasOverriddenMethodsInBaseOrProtocol = true;
4155 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4156 // OverrideSearch will return as "overridden" the same method in the
4157 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4158 // check whether a category of a base class introduced a method with the
4159 // same selector, after the interface method declaration.
4160 // To avoid unnecessary lookups in the majority of cases, we use the
4161 // extra info bits in GlobalMethodPool to check whether there were any
4162 // category methods with this selector.
4163 GlobalMethodPool::iterator It =
4164 MethodPool.find(ObjCMethod->getSelector());
4165 if (It != MethodPool.end()) {
4166 ObjCMethodList &List =
4167 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4168 unsigned CategCount = List.getBits();
4169 if (CategCount > 0) {
4170 // If the method is in a category we'll do lookup if there were at
4171 // least 2 category methods recorded, otherwise only one will do.
4172 if (CategCount > 1 ||
4173 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4174 OverrideSearch overrides(*this, overridden);
4175 for (OverrideSearch::iterator
4176 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4177 ObjCMethodDecl *SuperOverridden = *OI;
4178 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4179 CurrentClass != SuperOverridden->getClassInterface()) {
4180 hasOverriddenMethodsInBaseOrProtocol = true;
4181 overridden->setOverriding(true);
4191 // Propagate down the 'related result type' bit from overridden methods.
4192 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4193 ObjCMethod->SetRelatedResultType();
4195 // Then merge the declarations.
4196 mergeObjCMethodDecls(ObjCMethod, overridden);
4198 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4199 continue; // Conflicting properties are detected elsewhere.
4201 // Check for overriding methods
4202 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4203 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4204 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4205 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4207 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4208 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4209 !overridden->isImplicit() /* not meant for properties */) {
4210 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4211 E = ObjCMethod->param_end();
4212 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4213 PrevE = overridden->param_end();
4214 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4215 assert(PrevI != overridden->param_end() && "Param mismatch");
4216 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4217 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4218 // If type of argument of method in this class does not match its
4219 // respective argument type in the super class method, issue warning;
4220 if (!Context.typesAreCompatible(T1, T2)) {
4221 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4223 Diag(overridden->getLocation(), diag::note_previous_declaration);
4230 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4233 /// Merge type nullability from for a redeclaration of the same entity,
4234 /// producing the updated type of the redeclared entity.
4235 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4238 SourceLocation prevLoc,
4240 bool prevUsesCSKeyword) {
4241 // Determine the nullability of both types.
4242 auto nullability = type->getNullability(S.Context);
4243 auto prevNullability = prevType->getNullability(S.Context);
4245 // Easy case: both have nullability.
4246 if (nullability.hasValue() == prevNullability.hasValue()) {
4247 // Neither has nullability; continue.
4251 // The nullabilities are equivalent; do nothing.
4252 if (*nullability == *prevNullability)
4255 // Complain about mismatched nullability.
4256 S.Diag(loc, diag::err_nullability_conflicting)
4257 << DiagNullabilityKind(*nullability, usesCSKeyword)
4258 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4262 // If it's the redeclaration that has nullability, don't change anything.
4266 // Otherwise, provide the result with the same nullability.
4267 return S.Context.getAttributedType(
4268 AttributedType::getNullabilityAttrKind(*prevNullability),
4272 /// Merge information from the declaration of a method in the \@interface
4273 /// (or a category/extension) into the corresponding method in the
4274 /// @implementation (for a class or category).
4275 static void mergeInterfaceMethodToImpl(Sema &S,
4276 ObjCMethodDecl *method,
4277 ObjCMethodDecl *prevMethod) {
4278 // Merge the objc_requires_super attribute.
4279 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4280 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4281 // merge the attribute into implementation.
4283 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4284 method->getLocation()));
4287 // Merge nullability of the result type.
4288 QualType newReturnType
4289 = mergeTypeNullabilityForRedecl(
4290 S, method->getReturnTypeSourceRange().getBegin(),
4291 method->getReturnType(),
4292 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4293 prevMethod->getReturnTypeSourceRange().getBegin(),
4294 prevMethod->getReturnType(),
4295 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4296 method->setReturnType(newReturnType);
4298 // Handle each of the parameters.
4299 unsigned numParams = method->param_size();
4300 unsigned numPrevParams = prevMethod->param_size();
4301 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4302 ParmVarDecl *param = method->param_begin()[i];
4303 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4305 // Merge nullability.
4306 QualType newParamType
4307 = mergeTypeNullabilityForRedecl(
4308 S, param->getLocation(), param->getType(),
4309 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4310 prevParam->getLocation(), prevParam->getType(),
4311 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4312 param->setType(newParamType);
4316 Decl *Sema::ActOnMethodDeclaration(
4318 SourceLocation MethodLoc, SourceLocation EndLoc,
4319 tok::TokenKind MethodType,
4320 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4321 ArrayRef<SourceLocation> SelectorLocs,
4323 // optional arguments. The number of types/arguments is obtained
4324 // from the Sel.getNumArgs().
4325 ObjCArgInfo *ArgInfo,
4326 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
4327 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
4328 bool isVariadic, bool MethodDefinition) {
4329 // Make sure we can establish a context for the method.
4330 if (!CurContext->isObjCContainer()) {
4331 Diag(MethodLoc, diag::err_missing_method_context);
4334 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4335 Decl *ClassDecl = cast<Decl>(OCD);
4336 QualType resultDeclType;
4338 bool HasRelatedResultType = false;
4339 TypeSourceInfo *ReturnTInfo = nullptr;
4341 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4343 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4346 QualType bareResultType = resultDeclType;
4347 (void)AttributedType::stripOuterNullability(bareResultType);
4348 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4349 } else { // get the type for "id".
4350 resultDeclType = Context.getObjCIdType();
4351 Diag(MethodLoc, diag::warn_missing_method_return_type)
4352 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4355 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4356 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4357 MethodType == tok::minus, isVariadic,
4358 /*isPropertyAccessor=*/false,
4359 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4360 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4361 : ObjCMethodDecl::Required,
4362 HasRelatedResultType);
4364 SmallVector<ParmVarDecl*, 16> Params;
4366 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4370 if (!ArgInfo[i].Type) {
4371 ArgType = Context.getObjCIdType();
4374 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4377 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4378 LookupOrdinaryName, ForRedeclaration);
4380 if (R.isSingleResult()) {
4381 NamedDecl *PrevDecl = R.getFoundDecl();
4382 if (S->isDeclScope(PrevDecl)) {
4383 Diag(ArgInfo[i].NameLoc,
4384 (MethodDefinition ? diag::warn_method_param_redefinition
4385 : diag::warn_method_param_declaration))
4387 Diag(PrevDecl->getLocation(),
4388 diag::note_previous_declaration);
4392 SourceLocation StartLoc = DI
4393 ? DI->getTypeLoc().getBeginLoc()
4394 : ArgInfo[i].NameLoc;
4396 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4397 ArgInfo[i].NameLoc, ArgInfo[i].Name,
4398 ArgType, DI, SC_None);
4400 Param->setObjCMethodScopeInfo(i);
4402 Param->setObjCDeclQualifier(
4403 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4405 // Apply the attributes to the parameter.
4406 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4407 AddPragmaAttributes(TUScope, Param);
4409 if (Param->hasAttr<BlocksAttr>()) {
4410 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4411 Param->setInvalidDecl();
4414 IdResolver.AddDecl(Param);
4416 Params.push_back(Param);
4419 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4420 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4421 QualType ArgType = Param->getType();
4422 if (ArgType.isNull())
4423 ArgType = Context.getObjCIdType();
4425 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4426 ArgType = Context.getAdjustedParameterType(ArgType);
4428 Param->setDeclContext(ObjCMethod);
4429 Params.push_back(Param);
4432 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4433 ObjCMethod->setObjCDeclQualifier(
4434 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4437 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4438 AddPragmaAttributes(TUScope, ObjCMethod);
4440 // Add the method now.
4441 const ObjCMethodDecl *PrevMethod = nullptr;
4442 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4443 if (MethodType == tok::minus) {
4444 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4445 ImpDecl->addInstanceMethod(ObjCMethod);
4447 PrevMethod = ImpDecl->getClassMethod(Sel);
4448 ImpDecl->addClassMethod(ObjCMethod);
4451 // Merge information from the @interface declaration into the
4453 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4454 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4455 ObjCMethod->isInstanceMethod())) {
4456 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4458 // Warn about defining -dealloc in a category.
4459 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4460 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4461 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4462 << ObjCMethod->getDeclName();
4467 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4471 // You can never have two method definitions with the same name.
4472 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4473 << ObjCMethod->getDeclName();
4474 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4475 ObjCMethod->setInvalidDecl();
4479 // If this Objective-C method does not have a related result type, but we
4480 // are allowed to infer related result types, try to do so based on the
4482 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4483 if (!CurrentClass) {
4484 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4485 CurrentClass = Cat->getClassInterface();
4486 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4487 CurrentClass = Impl->getClassInterface();
4488 else if (ObjCCategoryImplDecl *CatImpl
4489 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4490 CurrentClass = CatImpl->getClassInterface();
4493 ResultTypeCompatibilityKind RTC
4494 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
4496 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
4498 bool ARCError = false;
4499 if (getLangOpts().ObjCAutoRefCount)
4500 ARCError = CheckARCMethodDecl(ObjCMethod);
4502 // Infer the related result type when possible.
4503 if (!ARCError && RTC == Sema::RTC_Compatible &&
4504 !ObjCMethod->hasRelatedResultType() &&
4505 LangOpts.ObjCInferRelatedResultType) {
4506 bool InferRelatedResultType = false;
4507 switch (ObjCMethod->getMethodFamily()) {
4512 case OMF_mutableCopy:
4514 case OMF_retainCount:
4515 case OMF_initialize:
4516 case OMF_performSelector:
4521 InferRelatedResultType = ObjCMethod->isClassMethod();
4525 case OMF_autorelease:
4528 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4532 if (InferRelatedResultType &&
4533 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
4534 ObjCMethod->SetRelatedResultType();
4537 ActOnDocumentableDecl(ObjCMethod);
4542 bool Sema::CheckObjCDeclScope(Decl *D) {
4543 // Following is also an error. But it is caused by a missing @end
4544 // and diagnostic is issued elsewhere.
4545 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
4548 // If we switched context to translation unit while we are still lexically in
4549 // an objc container, it means the parser missed emitting an error.
4550 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4553 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4554 D->setInvalidDecl();
4559 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
4560 /// instance variables of ClassName into Decls.
4561 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
4562 IdentifierInfo *ClassName,
4563 SmallVectorImpl<Decl*> &Decls) {
4564 // Check that ClassName is a valid class
4565 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
4567 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4570 if (LangOpts.ObjCRuntime.isNonFragile()) {
4571 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4575 // Collect the instance variables
4576 SmallVector<const ObjCIvarDecl*, 32> Ivars;
4577 Context.DeepCollectObjCIvars(Class, true, Ivars);
4578 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
4579 for (unsigned i = 0; i < Ivars.size(); i++) {
4580 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
4581 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
4582 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4583 /*FIXME: StartL=*/ID->getLocation(),
4585 ID->getIdentifier(), ID->getType(),
4587 Decls.push_back(FD);
4590 // Introduce all of these fields into the appropriate scope.
4591 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
4592 D != Decls.end(); ++D) {
4593 FieldDecl *FD = cast<FieldDecl>(*D);
4594 if (getLangOpts().CPlusPlus)
4595 PushOnScopeChains(cast<FieldDecl>(FD), S);
4596 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
4597 Record->addDecl(FD);
4601 /// \brief Build a type-check a new Objective-C exception variable declaration.
4602 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4603 SourceLocation StartLoc,
4604 SourceLocation IdLoc,
4607 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4608 // duration shall not be qualified by an address-space qualifier."
4609 // Since all parameters have automatic store duration, they can not have
4610 // an address space.
4611 if (T.getAddressSpace() != 0) {
4612 Diag(IdLoc, diag::err_arg_with_address_space);
4616 // An @catch parameter must be an unqualified object pointer type;
4617 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4619 // Don't do any further checking.
4620 } else if (T->isDependentType()) {
4621 // Okay: we don't know what this type will instantiate to.
4622 } else if (!T->isObjCObjectPointerType()) {
4624 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
4625 } else if (T->isObjCQualifiedIdType()) {
4627 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
4630 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
4632 New->setExceptionVariable(true);
4634 // In ARC, infer 'retaining' for variables of retainable type.
4635 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
4639 New->setInvalidDecl();
4643 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
4644 const DeclSpec &DS = D.getDeclSpec();
4646 // We allow the "register" storage class on exception variables because
4647 // GCC did, but we drop it completely. Any other storage class is an error.
4648 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4649 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4650 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
4651 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4652 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
4653 << DeclSpec::getSpecifierName(SCS);
4655 if (DS.isInlineSpecified())
4656 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4657 << getLangOpts().CPlusPlus1z;
4658 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4659 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4660 diag::err_invalid_thread)
4661 << DeclSpec::getSpecifierName(TSCS);
4662 D.getMutableDeclSpec().ClearStorageClassSpecs();
4664 DiagnoseFunctionSpecifiers(D.getDeclSpec());
4666 // Check that there are no default arguments inside the type of this
4667 // exception object (C++ only).
4668 if (getLangOpts().CPlusPlus)
4669 CheckExtraCXXDefaultArguments(D);
4671 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4672 QualType ExceptionType = TInfo->getType();
4674 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4675 D.getSourceRange().getBegin(),
4676 D.getIdentifierLoc(),
4680 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4681 if (D.getCXXScopeSpec().isSet()) {
4682 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4683 << D.getCXXScopeSpec().getRange();
4684 New->setInvalidDecl();
4687 // Add the parameter declaration into this scope.
4689 if (D.getIdentifier())
4690 IdResolver.AddDecl(New);
4692 ProcessDeclAttributes(S, New, D);
4694 if (New->hasAttr<BlocksAttr>())
4695 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4699 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4701 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4702 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
4703 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4704 Iv= Iv->getNextIvar()) {
4705 QualType QT = Context.getBaseElementType(Iv->getType());
4706 if (QT->isRecordType())
4707 Ivars.push_back(Iv);
4711 void Sema::DiagnoseUseOfUnimplementedSelectors() {
4712 // Load referenced selectors from the external source.
4713 if (ExternalSource) {
4714 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4715 ExternalSource->ReadReferencedSelectors(Sels);
4716 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4717 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4720 // Warning will be issued only when selector table is
4721 // generated (which means there is at lease one implementation
4722 // in the TU). This is to match gcc's behavior.
4723 if (ReferencedSelectors.empty() ||
4724 !Context.AnyObjCImplementation())
4726 for (auto &SelectorAndLocation : ReferencedSelectors) {
4727 Selector Sel = SelectorAndLocation.first;
4728 SourceLocation Loc = SelectorAndLocation.second;
4729 if (!LookupImplementedMethodInGlobalPool(Sel))
4730 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
4735 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4736 const ObjCPropertyDecl *&PDecl) const {
4737 if (Method->isClassMethod())
4739 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4742 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4743 /*shallowCategoryLookup=*/false,
4744 /*followSuper=*/false);
4745 if (!Method || !Method->isPropertyAccessor())
4747 if ((PDecl = Method->findPropertyDecl()))
4748 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4749 // property backing ivar must belong to property's class
4750 // or be a private ivar in class's implementation.
4751 // FIXME. fix the const-ness issue.
4752 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4753 IV->getIdentifier());
4760 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4761 /// accessor references the backing ivar.
4762 class UnusedBackingIvarChecker :
4763 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
4766 const ObjCMethodDecl *Method;
4767 const ObjCIvarDecl *IvarD;
4769 bool InvokedSelfMethod;
4771 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4772 const ObjCIvarDecl *IvarD)
4773 : S(S), Method(Method), IvarD(IvarD),
4774 AccessedIvar(false), InvokedSelfMethod(false) {
4778 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4779 if (E->getDecl() == IvarD) {
4780 AccessedIvar = true;
4786 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4787 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4788 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4789 InvokedSelfMethod = true;
4794 } // end anonymous namespace
4796 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4797 const ObjCImplementationDecl *ImplD) {
4798 if (S->hasUnrecoverableErrorOccurred())
4801 for (const auto *CurMethod : ImplD->instance_methods()) {
4802 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4803 SourceLocation Loc = CurMethod->getLocation();
4804 if (Diags.isIgnored(DIAG, Loc))
4807 const ObjCPropertyDecl *PDecl;
4808 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4812 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4813 Checker.TraverseStmt(CurMethod->getBody());
4814 if (Checker.AccessedIvar)
4817 // Do not issue this warning if backing ivar is used somewhere and accessor
4818 // implementation makes a self call. This is to prevent false positive in
4819 // cases where the ivar is accessed by another method that the accessor
4821 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
4822 Diag(Loc, DIAG) << IV;
4823 Diag(PDecl->getLocation(), diag::note_property_declare);