1e5dd7070Spatrick //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // This file implements semantic analysis for Objective C declarations.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick
13e5dd7070Spatrick #include "TypeLocBuilder.h"
14e5dd7070Spatrick #include "clang/AST/ASTConsumer.h"
15e5dd7070Spatrick #include "clang/AST/ASTContext.h"
16e5dd7070Spatrick #include "clang/AST/ASTMutationListener.h"
17e5dd7070Spatrick #include "clang/AST/DeclObjC.h"
18e5dd7070Spatrick #include "clang/AST/Expr.h"
19e5dd7070Spatrick #include "clang/AST/ExprObjC.h"
20e5dd7070Spatrick #include "clang/AST/RecursiveASTVisitor.h"
21e5dd7070Spatrick #include "clang/Basic/SourceManager.h"
22ec727ea7Spatrick #include "clang/Basic/TargetInfo.h"
23e5dd7070Spatrick #include "clang/Sema/DeclSpec.h"
24e5dd7070Spatrick #include "clang/Sema/Lookup.h"
25e5dd7070Spatrick #include "clang/Sema/Scope.h"
26e5dd7070Spatrick #include "clang/Sema/ScopeInfo.h"
27e5dd7070Spatrick #include "clang/Sema/SemaInternal.h"
28e5dd7070Spatrick #include "llvm/ADT/DenseMap.h"
29e5dd7070Spatrick #include "llvm/ADT/DenseSet.h"
30e5dd7070Spatrick
31e5dd7070Spatrick using namespace clang;
32e5dd7070Spatrick
33e5dd7070Spatrick /// Check whether the given method, which must be in the 'init'
34e5dd7070Spatrick /// family, is a valid member of that family.
35e5dd7070Spatrick ///
36e5dd7070Spatrick /// \param receiverTypeIfCall - if null, check this as if declaring it;
37e5dd7070Spatrick /// if non-null, check this as if making a call to it with the given
38e5dd7070Spatrick /// receiver type
39e5dd7070Spatrick ///
40e5dd7070Spatrick /// \return true to indicate that there was an error and appropriate
41e5dd7070Spatrick /// actions were taken
checkInitMethod(ObjCMethodDecl * method,QualType receiverTypeIfCall)42e5dd7070Spatrick bool Sema::checkInitMethod(ObjCMethodDecl *method,
43e5dd7070Spatrick QualType receiverTypeIfCall) {
44e5dd7070Spatrick if (method->isInvalidDecl()) return true;
45e5dd7070Spatrick
46e5dd7070Spatrick // This castAs is safe: methods that don't return an object
47e5dd7070Spatrick // pointer won't be inferred as inits and will reject an explicit
48e5dd7070Spatrick // objc_method_family(init).
49e5dd7070Spatrick
50e5dd7070Spatrick // We ignore protocols here. Should we? What about Class?
51e5dd7070Spatrick
52e5dd7070Spatrick const ObjCObjectType *result =
53e5dd7070Spatrick method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
54e5dd7070Spatrick
55e5dd7070Spatrick if (result->isObjCId()) {
56e5dd7070Spatrick return false;
57e5dd7070Spatrick } else if (result->isObjCClass()) {
58e5dd7070Spatrick // fall through: always an error
59e5dd7070Spatrick } else {
60e5dd7070Spatrick ObjCInterfaceDecl *resultClass = result->getInterface();
61e5dd7070Spatrick assert(resultClass && "unexpected object type!");
62e5dd7070Spatrick
63e5dd7070Spatrick // It's okay for the result type to still be a forward declaration
64e5dd7070Spatrick // if we're checking an interface declaration.
65e5dd7070Spatrick if (!resultClass->hasDefinition()) {
66e5dd7070Spatrick if (receiverTypeIfCall.isNull() &&
67e5dd7070Spatrick !isa<ObjCImplementationDecl>(method->getDeclContext()))
68e5dd7070Spatrick return false;
69e5dd7070Spatrick
70e5dd7070Spatrick // Otherwise, we try to compare class types.
71e5dd7070Spatrick } else {
72e5dd7070Spatrick // If this method was declared in a protocol, we can't check
73e5dd7070Spatrick // anything unless we have a receiver type that's an interface.
74e5dd7070Spatrick const ObjCInterfaceDecl *receiverClass = nullptr;
75e5dd7070Spatrick if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76e5dd7070Spatrick if (receiverTypeIfCall.isNull())
77e5dd7070Spatrick return false;
78e5dd7070Spatrick
79e5dd7070Spatrick receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
80e5dd7070Spatrick ->getInterfaceDecl();
81e5dd7070Spatrick
82e5dd7070Spatrick // This can be null for calls to e.g. id<Foo>.
83e5dd7070Spatrick if (!receiverClass) return false;
84e5dd7070Spatrick } else {
85e5dd7070Spatrick receiverClass = method->getClassInterface();
86e5dd7070Spatrick assert(receiverClass && "method not associated with a class!");
87e5dd7070Spatrick }
88e5dd7070Spatrick
89e5dd7070Spatrick // If either class is a subclass of the other, it's fine.
90e5dd7070Spatrick if (receiverClass->isSuperClassOf(resultClass) ||
91e5dd7070Spatrick resultClass->isSuperClassOf(receiverClass))
92e5dd7070Spatrick return false;
93e5dd7070Spatrick }
94e5dd7070Spatrick }
95e5dd7070Spatrick
96e5dd7070Spatrick SourceLocation loc = method->getLocation();
97e5dd7070Spatrick
98e5dd7070Spatrick // If we're in a system header, and this is not a call, just make
99e5dd7070Spatrick // the method unusable.
100e5dd7070Spatrick if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
101e5dd7070Spatrick method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102e5dd7070Spatrick UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
103e5dd7070Spatrick return true;
104e5dd7070Spatrick }
105e5dd7070Spatrick
106e5dd7070Spatrick // Otherwise, it's an error.
107e5dd7070Spatrick Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108e5dd7070Spatrick method->setInvalidDecl();
109e5dd7070Spatrick return true;
110e5dd7070Spatrick }
111e5dd7070Spatrick
112e5dd7070Spatrick /// Issue a warning if the parameter of the overridden method is non-escaping
113e5dd7070Spatrick /// but the parameter of the overriding method is not.
diagnoseNoescape(const ParmVarDecl * NewD,const ParmVarDecl * OldD,Sema & S)114e5dd7070Spatrick static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
115e5dd7070Spatrick Sema &S) {
116e5dd7070Spatrick if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
117e5dd7070Spatrick S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
118e5dd7070Spatrick S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
119e5dd7070Spatrick return false;
120e5dd7070Spatrick }
121e5dd7070Spatrick
122e5dd7070Spatrick return true;
123e5dd7070Spatrick }
124e5dd7070Spatrick
125e5dd7070Spatrick /// Produce additional diagnostics if a category conforms to a protocol that
126e5dd7070Spatrick /// defines a method taking a non-escaping parameter.
diagnoseNoescape(const ParmVarDecl * NewD,const ParmVarDecl * OldD,const ObjCCategoryDecl * CD,const ObjCProtocolDecl * PD,Sema & S)127e5dd7070Spatrick static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
128e5dd7070Spatrick const ObjCCategoryDecl *CD,
129e5dd7070Spatrick const ObjCProtocolDecl *PD, Sema &S) {
130e5dd7070Spatrick if (!diagnoseNoescape(NewD, OldD, S))
131e5dd7070Spatrick S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
132e5dd7070Spatrick << CD->IsClassExtension() << PD
133e5dd7070Spatrick << cast<ObjCMethodDecl>(NewD->getDeclContext());
134e5dd7070Spatrick }
135e5dd7070Spatrick
CheckObjCMethodOverride(ObjCMethodDecl * NewMethod,const ObjCMethodDecl * Overridden)136e5dd7070Spatrick void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
137e5dd7070Spatrick const ObjCMethodDecl *Overridden) {
138e5dd7070Spatrick if (Overridden->hasRelatedResultType() &&
139e5dd7070Spatrick !NewMethod->hasRelatedResultType()) {
140e5dd7070Spatrick // This can only happen when the method follows a naming convention that
141e5dd7070Spatrick // implies a related result type, and the original (overridden) method has
142e5dd7070Spatrick // a suitable return type, but the new (overriding) method does not have
143e5dd7070Spatrick // a suitable return type.
144e5dd7070Spatrick QualType ResultType = NewMethod->getReturnType();
145e5dd7070Spatrick SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
146e5dd7070Spatrick
147e5dd7070Spatrick // Figure out which class this method is part of, if any.
148e5dd7070Spatrick ObjCInterfaceDecl *CurrentClass
149e5dd7070Spatrick = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
150e5dd7070Spatrick if (!CurrentClass) {
151e5dd7070Spatrick DeclContext *DC = NewMethod->getDeclContext();
152e5dd7070Spatrick if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
153e5dd7070Spatrick CurrentClass = Cat->getClassInterface();
154e5dd7070Spatrick else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
155e5dd7070Spatrick CurrentClass = Impl->getClassInterface();
156e5dd7070Spatrick else if (ObjCCategoryImplDecl *CatImpl
157e5dd7070Spatrick = dyn_cast<ObjCCategoryImplDecl>(DC))
158e5dd7070Spatrick CurrentClass = CatImpl->getClassInterface();
159e5dd7070Spatrick }
160e5dd7070Spatrick
161e5dd7070Spatrick if (CurrentClass) {
162e5dd7070Spatrick Diag(NewMethod->getLocation(),
163e5dd7070Spatrick diag::warn_related_result_type_compatibility_class)
164e5dd7070Spatrick << Context.getObjCInterfaceType(CurrentClass)
165e5dd7070Spatrick << ResultType
166e5dd7070Spatrick << ResultTypeRange;
167e5dd7070Spatrick } else {
168e5dd7070Spatrick Diag(NewMethod->getLocation(),
169e5dd7070Spatrick diag::warn_related_result_type_compatibility_protocol)
170e5dd7070Spatrick << ResultType
171e5dd7070Spatrick << ResultTypeRange;
172e5dd7070Spatrick }
173e5dd7070Spatrick
174e5dd7070Spatrick if (ObjCMethodFamily Family = Overridden->getMethodFamily())
175e5dd7070Spatrick Diag(Overridden->getLocation(),
176e5dd7070Spatrick diag::note_related_result_type_family)
177e5dd7070Spatrick << /*overridden method*/ 0
178e5dd7070Spatrick << Family;
179e5dd7070Spatrick else
180e5dd7070Spatrick Diag(Overridden->getLocation(),
181e5dd7070Spatrick diag::note_related_result_type_overridden);
182e5dd7070Spatrick }
183e5dd7070Spatrick
184e5dd7070Spatrick if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
185e5dd7070Spatrick Overridden->hasAttr<NSReturnsRetainedAttr>())) {
186e5dd7070Spatrick Diag(NewMethod->getLocation(),
187e5dd7070Spatrick getLangOpts().ObjCAutoRefCount
188e5dd7070Spatrick ? diag::err_nsreturns_retained_attribute_mismatch
189e5dd7070Spatrick : diag::warn_nsreturns_retained_attribute_mismatch)
190e5dd7070Spatrick << 1;
191e5dd7070Spatrick Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
192e5dd7070Spatrick }
193e5dd7070Spatrick if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
194e5dd7070Spatrick Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
195e5dd7070Spatrick Diag(NewMethod->getLocation(),
196e5dd7070Spatrick getLangOpts().ObjCAutoRefCount
197e5dd7070Spatrick ? diag::err_nsreturns_retained_attribute_mismatch
198e5dd7070Spatrick : diag::warn_nsreturns_retained_attribute_mismatch)
199e5dd7070Spatrick << 0;
200e5dd7070Spatrick Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
201e5dd7070Spatrick }
202e5dd7070Spatrick
203e5dd7070Spatrick ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
204e5dd7070Spatrick oe = Overridden->param_end();
205e5dd7070Spatrick for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
206e5dd7070Spatrick ne = NewMethod->param_end();
207e5dd7070Spatrick ni != ne && oi != oe; ++ni, ++oi) {
208e5dd7070Spatrick const ParmVarDecl *oldDecl = (*oi);
209e5dd7070Spatrick ParmVarDecl *newDecl = (*ni);
210e5dd7070Spatrick if (newDecl->hasAttr<NSConsumedAttr>() !=
211e5dd7070Spatrick oldDecl->hasAttr<NSConsumedAttr>()) {
212e5dd7070Spatrick Diag(newDecl->getLocation(),
213e5dd7070Spatrick getLangOpts().ObjCAutoRefCount
214e5dd7070Spatrick ? diag::err_nsconsumed_attribute_mismatch
215e5dd7070Spatrick : diag::warn_nsconsumed_attribute_mismatch);
216e5dd7070Spatrick Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
217e5dd7070Spatrick }
218e5dd7070Spatrick
219e5dd7070Spatrick diagnoseNoescape(newDecl, oldDecl, *this);
220e5dd7070Spatrick }
221e5dd7070Spatrick }
222e5dd7070Spatrick
223e5dd7070Spatrick /// Check a method declaration for compatibility with the Objective-C
224e5dd7070Spatrick /// ARC conventions.
CheckARCMethodDecl(ObjCMethodDecl * method)225e5dd7070Spatrick bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
226e5dd7070Spatrick ObjCMethodFamily family = method->getMethodFamily();
227e5dd7070Spatrick switch (family) {
228e5dd7070Spatrick case OMF_None:
229e5dd7070Spatrick case OMF_finalize:
230e5dd7070Spatrick case OMF_retain:
231e5dd7070Spatrick case OMF_release:
232e5dd7070Spatrick case OMF_autorelease:
233e5dd7070Spatrick case OMF_retainCount:
234e5dd7070Spatrick case OMF_self:
235e5dd7070Spatrick case OMF_initialize:
236e5dd7070Spatrick case OMF_performSelector:
237e5dd7070Spatrick return false;
238e5dd7070Spatrick
239e5dd7070Spatrick case OMF_dealloc:
240e5dd7070Spatrick if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
241e5dd7070Spatrick SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
242e5dd7070Spatrick if (ResultTypeRange.isInvalid())
243e5dd7070Spatrick Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
244e5dd7070Spatrick << method->getReturnType()
245e5dd7070Spatrick << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
246e5dd7070Spatrick else
247e5dd7070Spatrick Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
248e5dd7070Spatrick << method->getReturnType()
249e5dd7070Spatrick << FixItHint::CreateReplacement(ResultTypeRange, "void");
250e5dd7070Spatrick return true;
251e5dd7070Spatrick }
252e5dd7070Spatrick return false;
253e5dd7070Spatrick
254e5dd7070Spatrick case OMF_init:
255e5dd7070Spatrick // If the method doesn't obey the init rules, don't bother annotating it.
256e5dd7070Spatrick if (checkInitMethod(method, QualType()))
257e5dd7070Spatrick return true;
258e5dd7070Spatrick
259e5dd7070Spatrick method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
260e5dd7070Spatrick
261e5dd7070Spatrick // Don't add a second copy of this attribute, but otherwise don't
262e5dd7070Spatrick // let it be suppressed.
263e5dd7070Spatrick if (method->hasAttr<NSReturnsRetainedAttr>())
264e5dd7070Spatrick return false;
265e5dd7070Spatrick break;
266e5dd7070Spatrick
267e5dd7070Spatrick case OMF_alloc:
268e5dd7070Spatrick case OMF_copy:
269e5dd7070Spatrick case OMF_mutableCopy:
270e5dd7070Spatrick case OMF_new:
271e5dd7070Spatrick if (method->hasAttr<NSReturnsRetainedAttr>() ||
272e5dd7070Spatrick method->hasAttr<NSReturnsNotRetainedAttr>() ||
273e5dd7070Spatrick method->hasAttr<NSReturnsAutoreleasedAttr>())
274e5dd7070Spatrick return false;
275e5dd7070Spatrick break;
276e5dd7070Spatrick }
277e5dd7070Spatrick
278e5dd7070Spatrick method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
279e5dd7070Spatrick return false;
280e5dd7070Spatrick }
281e5dd7070Spatrick
DiagnoseObjCImplementedDeprecations(Sema & S,const NamedDecl * ND,SourceLocation ImplLoc)282e5dd7070Spatrick static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
283e5dd7070Spatrick SourceLocation ImplLoc) {
284e5dd7070Spatrick if (!ND)
285e5dd7070Spatrick return;
286e5dd7070Spatrick bool IsCategory = false;
287e5dd7070Spatrick StringRef RealizedPlatform;
288e5dd7070Spatrick AvailabilityResult Availability = ND->getAvailability(
289e5dd7070Spatrick /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
290e5dd7070Spatrick &RealizedPlatform);
291e5dd7070Spatrick if (Availability != AR_Deprecated) {
292e5dd7070Spatrick if (isa<ObjCMethodDecl>(ND)) {
293e5dd7070Spatrick if (Availability != AR_Unavailable)
294e5dd7070Spatrick return;
295e5dd7070Spatrick if (RealizedPlatform.empty())
296e5dd7070Spatrick RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
297e5dd7070Spatrick // Warn about implementing unavailable methods, unless the unavailable
298e5dd7070Spatrick // is for an app extension.
299e5dd7070Spatrick if (RealizedPlatform.endswith("_app_extension"))
300e5dd7070Spatrick return;
301e5dd7070Spatrick S.Diag(ImplLoc, diag::warn_unavailable_def);
302e5dd7070Spatrick S.Diag(ND->getLocation(), diag::note_method_declared_at)
303e5dd7070Spatrick << ND->getDeclName();
304e5dd7070Spatrick return;
305e5dd7070Spatrick }
306e5dd7070Spatrick if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
307e5dd7070Spatrick if (!CD->getClassInterface()->isDeprecated())
308e5dd7070Spatrick return;
309e5dd7070Spatrick ND = CD->getClassInterface();
310e5dd7070Spatrick IsCategory = true;
311e5dd7070Spatrick } else
312e5dd7070Spatrick return;
313e5dd7070Spatrick }
314e5dd7070Spatrick S.Diag(ImplLoc, diag::warn_deprecated_def)
315e5dd7070Spatrick << (isa<ObjCMethodDecl>(ND)
316e5dd7070Spatrick ? /*Method*/ 0
317e5dd7070Spatrick : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
318e5dd7070Spatrick : /*Class*/ 1);
319e5dd7070Spatrick if (isa<ObjCMethodDecl>(ND))
320e5dd7070Spatrick S.Diag(ND->getLocation(), diag::note_method_declared_at)
321e5dd7070Spatrick << ND->getDeclName();
322e5dd7070Spatrick else
323e5dd7070Spatrick S.Diag(ND->getLocation(), diag::note_previous_decl)
324e5dd7070Spatrick << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
325e5dd7070Spatrick }
326e5dd7070Spatrick
327e5dd7070Spatrick /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
328e5dd7070Spatrick /// pool.
AddAnyMethodToGlobalPool(Decl * D)329e5dd7070Spatrick void Sema::AddAnyMethodToGlobalPool(Decl *D) {
330e5dd7070Spatrick ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
331e5dd7070Spatrick
332e5dd7070Spatrick // If we don't have a valid method decl, simply return.
333e5dd7070Spatrick if (!MDecl)
334e5dd7070Spatrick return;
335e5dd7070Spatrick if (MDecl->isInstanceMethod())
336e5dd7070Spatrick AddInstanceMethodToGlobalPool(MDecl, true);
337e5dd7070Spatrick else
338e5dd7070Spatrick AddFactoryMethodToGlobalPool(MDecl, true);
339e5dd7070Spatrick }
340e5dd7070Spatrick
341e5dd7070Spatrick /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
342e5dd7070Spatrick /// has explicit ownership attribute; false otherwise.
343e5dd7070Spatrick static bool
HasExplicitOwnershipAttr(Sema & S,ParmVarDecl * Param)344e5dd7070Spatrick HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
345e5dd7070Spatrick QualType T = Param->getType();
346e5dd7070Spatrick
347e5dd7070Spatrick if (const PointerType *PT = T->getAs<PointerType>()) {
348e5dd7070Spatrick T = PT->getPointeeType();
349e5dd7070Spatrick } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
350e5dd7070Spatrick T = RT->getPointeeType();
351e5dd7070Spatrick } else {
352e5dd7070Spatrick return true;
353e5dd7070Spatrick }
354e5dd7070Spatrick
355e5dd7070Spatrick // If we have a lifetime qualifier, but it's local, we must have
356e5dd7070Spatrick // inferred it. So, it is implicit.
357e5dd7070Spatrick return !T.getLocalQualifiers().hasObjCLifetime();
358e5dd7070Spatrick }
359e5dd7070Spatrick
360e5dd7070Spatrick /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
361e5dd7070Spatrick /// and user declared, in the method definition's AST.
ActOnStartOfObjCMethodDef(Scope * FnBodyScope,Decl * D)362e5dd7070Spatrick void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
363e5dd7070Spatrick ImplicitlyRetainedSelfLocs.clear();
364e5dd7070Spatrick assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
365e5dd7070Spatrick ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
366e5dd7070Spatrick
367e5dd7070Spatrick PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
368e5dd7070Spatrick
369e5dd7070Spatrick // If we don't have a valid method decl, simply return.
370e5dd7070Spatrick if (!MDecl)
371e5dd7070Spatrick return;
372e5dd7070Spatrick
373e5dd7070Spatrick QualType ResultType = MDecl->getReturnType();
374e5dd7070Spatrick if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
375e5dd7070Spatrick !MDecl->isInvalidDecl() &&
376e5dd7070Spatrick RequireCompleteType(MDecl->getLocation(), ResultType,
377e5dd7070Spatrick diag::err_func_def_incomplete_result))
378e5dd7070Spatrick MDecl->setInvalidDecl();
379e5dd7070Spatrick
380e5dd7070Spatrick // Allow all of Sema to see that we are entering a method definition.
381e5dd7070Spatrick PushDeclContext(FnBodyScope, MDecl);
382e5dd7070Spatrick PushFunctionScope();
383e5dd7070Spatrick
384e5dd7070Spatrick // Create Decl objects for each parameter, entrring them in the scope for
385e5dd7070Spatrick // binding to their use.
386e5dd7070Spatrick
387e5dd7070Spatrick // Insert the invisible arguments, self and _cmd!
388e5dd7070Spatrick MDecl->createImplicitParams(Context, MDecl->getClassInterface());
389e5dd7070Spatrick
390e5dd7070Spatrick PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
391e5dd7070Spatrick PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
392e5dd7070Spatrick
393e5dd7070Spatrick // The ObjC parser requires parameter names so there's no need to check.
394e5dd7070Spatrick CheckParmsForFunctionDef(MDecl->parameters(),
395e5dd7070Spatrick /*CheckParameterNames=*/false);
396e5dd7070Spatrick
397e5dd7070Spatrick // Introduce all of the other parameters into this scope.
398e5dd7070Spatrick for (auto *Param : MDecl->parameters()) {
399e5dd7070Spatrick if (!Param->isInvalidDecl() &&
400e5dd7070Spatrick getLangOpts().ObjCAutoRefCount &&
401e5dd7070Spatrick !HasExplicitOwnershipAttr(*this, Param))
402e5dd7070Spatrick Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
403e5dd7070Spatrick Param->getType();
404e5dd7070Spatrick
405e5dd7070Spatrick if (Param->getIdentifier())
406e5dd7070Spatrick PushOnScopeChains(Param, FnBodyScope);
407e5dd7070Spatrick }
408e5dd7070Spatrick
409e5dd7070Spatrick // In ARC, disallow definition of retain/release/autorelease/retainCount
410e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount) {
411e5dd7070Spatrick switch (MDecl->getMethodFamily()) {
412e5dd7070Spatrick case OMF_retain:
413e5dd7070Spatrick case OMF_retainCount:
414e5dd7070Spatrick case OMF_release:
415e5dd7070Spatrick case OMF_autorelease:
416e5dd7070Spatrick Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
417e5dd7070Spatrick << 0 << MDecl->getSelector();
418e5dd7070Spatrick break;
419e5dd7070Spatrick
420e5dd7070Spatrick case OMF_None:
421e5dd7070Spatrick case OMF_dealloc:
422e5dd7070Spatrick case OMF_finalize:
423e5dd7070Spatrick case OMF_alloc:
424e5dd7070Spatrick case OMF_init:
425e5dd7070Spatrick case OMF_mutableCopy:
426e5dd7070Spatrick case OMF_copy:
427e5dd7070Spatrick case OMF_new:
428e5dd7070Spatrick case OMF_self:
429e5dd7070Spatrick case OMF_initialize:
430e5dd7070Spatrick case OMF_performSelector:
431e5dd7070Spatrick break;
432e5dd7070Spatrick }
433e5dd7070Spatrick }
434e5dd7070Spatrick
435e5dd7070Spatrick // Warn on deprecated methods under -Wdeprecated-implementations,
436e5dd7070Spatrick // and prepare for warning on missing super calls.
437e5dd7070Spatrick if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
438e5dd7070Spatrick ObjCMethodDecl *IMD =
439e5dd7070Spatrick IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
440e5dd7070Spatrick
441e5dd7070Spatrick if (IMD) {
442e5dd7070Spatrick ObjCImplDecl *ImplDeclOfMethodDef =
443e5dd7070Spatrick dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
444e5dd7070Spatrick ObjCContainerDecl *ContDeclOfMethodDecl =
445e5dd7070Spatrick dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
446e5dd7070Spatrick ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
447e5dd7070Spatrick if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
448e5dd7070Spatrick ImplDeclOfMethodDecl = OID->getImplementation();
449e5dd7070Spatrick else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
450e5dd7070Spatrick if (CD->IsClassExtension()) {
451e5dd7070Spatrick if (ObjCInterfaceDecl *OID = CD->getClassInterface())
452e5dd7070Spatrick ImplDeclOfMethodDecl = OID->getImplementation();
453e5dd7070Spatrick } else
454e5dd7070Spatrick ImplDeclOfMethodDecl = CD->getImplementation();
455e5dd7070Spatrick }
456e5dd7070Spatrick // No need to issue deprecated warning if deprecated mehod in class/category
457e5dd7070Spatrick // is being implemented in its own implementation (no overriding is involved).
458e5dd7070Spatrick if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
459e5dd7070Spatrick DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
460e5dd7070Spatrick }
461e5dd7070Spatrick
462e5dd7070Spatrick if (MDecl->getMethodFamily() == OMF_init) {
463e5dd7070Spatrick if (MDecl->isDesignatedInitializerForTheInterface()) {
464e5dd7070Spatrick getCurFunction()->ObjCIsDesignatedInit = true;
465e5dd7070Spatrick getCurFunction()->ObjCWarnForNoDesignatedInitChain =
466e5dd7070Spatrick IC->getSuperClass() != nullptr;
467e5dd7070Spatrick } else if (IC->hasDesignatedInitializers()) {
468e5dd7070Spatrick getCurFunction()->ObjCIsSecondaryInit = true;
469e5dd7070Spatrick getCurFunction()->ObjCWarnForNoInitDelegation = true;
470e5dd7070Spatrick }
471e5dd7070Spatrick }
472e5dd7070Spatrick
473e5dd7070Spatrick // If this is "dealloc" or "finalize", set some bit here.
474e5dd7070Spatrick // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
475e5dd7070Spatrick // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
476e5dd7070Spatrick // Only do this if the current class actually has a superclass.
477e5dd7070Spatrick if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
478e5dd7070Spatrick ObjCMethodFamily Family = MDecl->getMethodFamily();
479e5dd7070Spatrick if (Family == OMF_dealloc) {
480e5dd7070Spatrick if (!(getLangOpts().ObjCAutoRefCount ||
481e5dd7070Spatrick getLangOpts().getGC() == LangOptions::GCOnly))
482e5dd7070Spatrick getCurFunction()->ObjCShouldCallSuper = true;
483e5dd7070Spatrick
484e5dd7070Spatrick } else if (Family == OMF_finalize) {
485e5dd7070Spatrick if (Context.getLangOpts().getGC() != LangOptions::NonGC)
486e5dd7070Spatrick getCurFunction()->ObjCShouldCallSuper = true;
487e5dd7070Spatrick
488e5dd7070Spatrick } else {
489e5dd7070Spatrick const ObjCMethodDecl *SuperMethod =
490e5dd7070Spatrick SuperClass->lookupMethod(MDecl->getSelector(),
491e5dd7070Spatrick MDecl->isInstanceMethod());
492e5dd7070Spatrick getCurFunction()->ObjCShouldCallSuper =
493e5dd7070Spatrick (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
494e5dd7070Spatrick }
495e5dd7070Spatrick }
496e5dd7070Spatrick }
497e5dd7070Spatrick }
498e5dd7070Spatrick
499e5dd7070Spatrick namespace {
500e5dd7070Spatrick
501e5dd7070Spatrick // Callback to only accept typo corrections that are Objective-C classes.
502e5dd7070Spatrick // If an ObjCInterfaceDecl* is given to the constructor, then the validation
503e5dd7070Spatrick // function will reject corrections to that class.
504e5dd7070Spatrick class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
505e5dd7070Spatrick public:
ObjCInterfaceValidatorCCC()506e5dd7070Spatrick ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
ObjCInterfaceValidatorCCC(ObjCInterfaceDecl * IDecl)507e5dd7070Spatrick explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
508e5dd7070Spatrick : CurrentIDecl(IDecl) {}
509e5dd7070Spatrick
ValidateCandidate(const TypoCorrection & candidate)510e5dd7070Spatrick bool ValidateCandidate(const TypoCorrection &candidate) override {
511e5dd7070Spatrick ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
512e5dd7070Spatrick return ID && !declaresSameEntity(ID, CurrentIDecl);
513e5dd7070Spatrick }
514e5dd7070Spatrick
clone()515e5dd7070Spatrick std::unique_ptr<CorrectionCandidateCallback> clone() override {
516e5dd7070Spatrick return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
517e5dd7070Spatrick }
518e5dd7070Spatrick
519e5dd7070Spatrick private:
520e5dd7070Spatrick ObjCInterfaceDecl *CurrentIDecl;
521e5dd7070Spatrick };
522e5dd7070Spatrick
523e5dd7070Spatrick } // end anonymous namespace
524e5dd7070Spatrick
diagnoseUseOfProtocols(Sema & TheSema,ObjCContainerDecl * CD,ObjCProtocolDecl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs)525e5dd7070Spatrick static void diagnoseUseOfProtocols(Sema &TheSema,
526e5dd7070Spatrick ObjCContainerDecl *CD,
527e5dd7070Spatrick ObjCProtocolDecl *const *ProtoRefs,
528e5dd7070Spatrick unsigned NumProtoRefs,
529e5dd7070Spatrick const SourceLocation *ProtoLocs) {
530e5dd7070Spatrick assert(ProtoRefs);
531e5dd7070Spatrick // Diagnose availability in the context of the ObjC container.
532e5dd7070Spatrick Sema::ContextRAII SavedContext(TheSema, CD);
533e5dd7070Spatrick for (unsigned i = 0; i < NumProtoRefs; ++i) {
534e5dd7070Spatrick (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
535e5dd7070Spatrick /*UnknownObjCClass=*/nullptr,
536e5dd7070Spatrick /*ObjCPropertyAccess=*/false,
537e5dd7070Spatrick /*AvoidPartialAvailabilityChecks=*/true);
538e5dd7070Spatrick }
539e5dd7070Spatrick }
540e5dd7070Spatrick
541e5dd7070Spatrick void Sema::
ActOnSuperClassOfClassInterface(Scope * S,SourceLocation AtInterfaceLoc,ObjCInterfaceDecl * IDecl,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * SuperName,SourceLocation SuperLoc,ArrayRef<ParsedType> SuperTypeArgs,SourceRange SuperTypeArgsRange)542e5dd7070Spatrick ActOnSuperClassOfClassInterface(Scope *S,
543e5dd7070Spatrick SourceLocation AtInterfaceLoc,
544e5dd7070Spatrick ObjCInterfaceDecl *IDecl,
545e5dd7070Spatrick IdentifierInfo *ClassName,
546e5dd7070Spatrick SourceLocation ClassLoc,
547e5dd7070Spatrick IdentifierInfo *SuperName,
548e5dd7070Spatrick SourceLocation SuperLoc,
549e5dd7070Spatrick ArrayRef<ParsedType> SuperTypeArgs,
550e5dd7070Spatrick SourceRange SuperTypeArgsRange) {
551e5dd7070Spatrick // Check if a different kind of symbol declared in this scope.
552e5dd7070Spatrick NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
553e5dd7070Spatrick LookupOrdinaryName);
554e5dd7070Spatrick
555e5dd7070Spatrick if (!PrevDecl) {
556e5dd7070Spatrick // Try to correct for a typo in the superclass name without correcting
557e5dd7070Spatrick // to the class we're defining.
558e5dd7070Spatrick ObjCInterfaceValidatorCCC CCC(IDecl);
559e5dd7070Spatrick if (TypoCorrection Corrected = CorrectTypo(
560e5dd7070Spatrick DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
561e5dd7070Spatrick TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
562e5dd7070Spatrick diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
563e5dd7070Spatrick << SuperName << ClassName);
564e5dd7070Spatrick PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
565e5dd7070Spatrick }
566e5dd7070Spatrick }
567e5dd7070Spatrick
568e5dd7070Spatrick if (declaresSameEntity(PrevDecl, IDecl)) {
569e5dd7070Spatrick Diag(SuperLoc, diag::err_recursive_superclass)
570e5dd7070Spatrick << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
571e5dd7070Spatrick IDecl->setEndOfDefinitionLoc(ClassLoc);
572e5dd7070Spatrick } else {
573e5dd7070Spatrick ObjCInterfaceDecl *SuperClassDecl =
574e5dd7070Spatrick dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
575e5dd7070Spatrick QualType SuperClassType;
576e5dd7070Spatrick
577e5dd7070Spatrick // Diagnose classes that inherit from deprecated classes.
578e5dd7070Spatrick if (SuperClassDecl) {
579e5dd7070Spatrick (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
580e5dd7070Spatrick SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
581e5dd7070Spatrick }
582e5dd7070Spatrick
583e5dd7070Spatrick if (PrevDecl && !SuperClassDecl) {
584e5dd7070Spatrick // The previous declaration was not a class decl. Check if we have a
585e5dd7070Spatrick // typedef. If we do, get the underlying class type.
586e5dd7070Spatrick if (const TypedefNameDecl *TDecl =
587e5dd7070Spatrick dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
588e5dd7070Spatrick QualType T = TDecl->getUnderlyingType();
589e5dd7070Spatrick if (T->isObjCObjectType()) {
590e5dd7070Spatrick if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
591e5dd7070Spatrick SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
592e5dd7070Spatrick SuperClassType = Context.getTypeDeclType(TDecl);
593e5dd7070Spatrick
594e5dd7070Spatrick // This handles the following case:
595e5dd7070Spatrick // @interface NewI @end
596e5dd7070Spatrick // typedef NewI DeprI __attribute__((deprecated("blah")))
597e5dd7070Spatrick // @interface SI : DeprI /* warn here */ @end
598e5dd7070Spatrick (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
599e5dd7070Spatrick }
600e5dd7070Spatrick }
601e5dd7070Spatrick }
602e5dd7070Spatrick
603e5dd7070Spatrick // This handles the following case:
604e5dd7070Spatrick //
605e5dd7070Spatrick // typedef int SuperClass;
606e5dd7070Spatrick // @interface MyClass : SuperClass {} @end
607e5dd7070Spatrick //
608e5dd7070Spatrick if (!SuperClassDecl) {
609e5dd7070Spatrick Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
610e5dd7070Spatrick Diag(PrevDecl->getLocation(), diag::note_previous_definition);
611e5dd7070Spatrick }
612e5dd7070Spatrick }
613e5dd7070Spatrick
614*12c85518Srobert if (!isa_and_nonnull<TypedefNameDecl>(PrevDecl)) {
615e5dd7070Spatrick if (!SuperClassDecl)
616e5dd7070Spatrick Diag(SuperLoc, diag::err_undef_superclass)
617e5dd7070Spatrick << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
618e5dd7070Spatrick else if (RequireCompleteType(SuperLoc,
619e5dd7070Spatrick SuperClassType,
620e5dd7070Spatrick diag::err_forward_superclass,
621e5dd7070Spatrick SuperClassDecl->getDeclName(),
622e5dd7070Spatrick ClassName,
623e5dd7070Spatrick SourceRange(AtInterfaceLoc, ClassLoc))) {
624e5dd7070Spatrick SuperClassDecl = nullptr;
625e5dd7070Spatrick SuperClassType = QualType();
626e5dd7070Spatrick }
627e5dd7070Spatrick }
628e5dd7070Spatrick
629e5dd7070Spatrick if (SuperClassType.isNull()) {
630e5dd7070Spatrick assert(!SuperClassDecl && "Failed to set SuperClassType?");
631e5dd7070Spatrick return;
632e5dd7070Spatrick }
633e5dd7070Spatrick
634e5dd7070Spatrick // Handle type arguments on the superclass.
635e5dd7070Spatrick TypeSourceInfo *SuperClassTInfo = nullptr;
636e5dd7070Spatrick if (!SuperTypeArgs.empty()) {
637e5dd7070Spatrick TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
638e5dd7070Spatrick S,
639e5dd7070Spatrick SuperLoc,
640e5dd7070Spatrick CreateParsedType(SuperClassType,
641e5dd7070Spatrick nullptr),
642e5dd7070Spatrick SuperTypeArgsRange.getBegin(),
643e5dd7070Spatrick SuperTypeArgs,
644e5dd7070Spatrick SuperTypeArgsRange.getEnd(),
645e5dd7070Spatrick SourceLocation(),
646e5dd7070Spatrick { },
647e5dd7070Spatrick { },
648e5dd7070Spatrick SourceLocation());
649e5dd7070Spatrick if (!fullSuperClassType.isUsable())
650e5dd7070Spatrick return;
651e5dd7070Spatrick
652e5dd7070Spatrick SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
653e5dd7070Spatrick &SuperClassTInfo);
654e5dd7070Spatrick }
655e5dd7070Spatrick
656e5dd7070Spatrick if (!SuperClassTInfo) {
657e5dd7070Spatrick SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
658e5dd7070Spatrick SuperLoc);
659e5dd7070Spatrick }
660e5dd7070Spatrick
661e5dd7070Spatrick IDecl->setSuperClass(SuperClassTInfo);
662e5dd7070Spatrick IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
663e5dd7070Spatrick }
664e5dd7070Spatrick }
665e5dd7070Spatrick
actOnObjCTypeParam(Scope * S,ObjCTypeParamVariance variance,SourceLocation varianceLoc,unsigned index,IdentifierInfo * paramName,SourceLocation paramLoc,SourceLocation colonLoc,ParsedType parsedTypeBound)666e5dd7070Spatrick DeclResult Sema::actOnObjCTypeParam(Scope *S,
667e5dd7070Spatrick ObjCTypeParamVariance variance,
668e5dd7070Spatrick SourceLocation varianceLoc,
669e5dd7070Spatrick unsigned index,
670e5dd7070Spatrick IdentifierInfo *paramName,
671e5dd7070Spatrick SourceLocation paramLoc,
672e5dd7070Spatrick SourceLocation colonLoc,
673e5dd7070Spatrick ParsedType parsedTypeBound) {
674e5dd7070Spatrick // If there was an explicitly-provided type bound, check it.
675e5dd7070Spatrick TypeSourceInfo *typeBoundInfo = nullptr;
676e5dd7070Spatrick if (parsedTypeBound) {
677e5dd7070Spatrick // The type bound can be any Objective-C pointer type.
678e5dd7070Spatrick QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
679e5dd7070Spatrick if (typeBound->isObjCObjectPointerType()) {
680e5dd7070Spatrick // okay
681e5dd7070Spatrick } else if (typeBound->isObjCObjectType()) {
682e5dd7070Spatrick // The user forgot the * on an Objective-C pointer type, e.g.,
683e5dd7070Spatrick // "T : NSView".
684e5dd7070Spatrick SourceLocation starLoc = getLocForEndOfToken(
685e5dd7070Spatrick typeBoundInfo->getTypeLoc().getEndLoc());
686e5dd7070Spatrick Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
687e5dd7070Spatrick diag::err_objc_type_param_bound_missing_pointer)
688e5dd7070Spatrick << typeBound << paramName
689e5dd7070Spatrick << FixItHint::CreateInsertion(starLoc, " *");
690e5dd7070Spatrick
691e5dd7070Spatrick // Create a new type location builder so we can update the type
692e5dd7070Spatrick // location information we have.
693e5dd7070Spatrick TypeLocBuilder builder;
694e5dd7070Spatrick builder.pushFullCopy(typeBoundInfo->getTypeLoc());
695e5dd7070Spatrick
696e5dd7070Spatrick // Create the Objective-C pointer type.
697e5dd7070Spatrick typeBound = Context.getObjCObjectPointerType(typeBound);
698e5dd7070Spatrick ObjCObjectPointerTypeLoc newT
699e5dd7070Spatrick = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
700e5dd7070Spatrick newT.setStarLoc(starLoc);
701e5dd7070Spatrick
702e5dd7070Spatrick // Form the new type source information.
703e5dd7070Spatrick typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
704e5dd7070Spatrick } else {
705e5dd7070Spatrick // Not a valid type bound.
706e5dd7070Spatrick Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
707e5dd7070Spatrick diag::err_objc_type_param_bound_nonobject)
708e5dd7070Spatrick << typeBound << paramName;
709e5dd7070Spatrick
710e5dd7070Spatrick // Forget the bound; we'll default to id later.
711e5dd7070Spatrick typeBoundInfo = nullptr;
712e5dd7070Spatrick }
713e5dd7070Spatrick
714e5dd7070Spatrick // Type bounds cannot have qualifiers (even indirectly) or explicit
715e5dd7070Spatrick // nullability.
716e5dd7070Spatrick if (typeBoundInfo) {
717e5dd7070Spatrick QualType typeBound = typeBoundInfo->getType();
718e5dd7070Spatrick TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
719e5dd7070Spatrick if (qual || typeBound.hasQualifiers()) {
720e5dd7070Spatrick bool diagnosed = false;
721e5dd7070Spatrick SourceRange rangeToRemove;
722e5dd7070Spatrick if (qual) {
723e5dd7070Spatrick if (auto attr = qual.getAs<AttributedTypeLoc>()) {
724e5dd7070Spatrick rangeToRemove = attr.getLocalSourceRange();
725e5dd7070Spatrick if (attr.getTypePtr()->getImmediateNullability()) {
726e5dd7070Spatrick Diag(attr.getBeginLoc(),
727e5dd7070Spatrick diag::err_objc_type_param_bound_explicit_nullability)
728e5dd7070Spatrick << paramName << typeBound
729e5dd7070Spatrick << FixItHint::CreateRemoval(rangeToRemove);
730e5dd7070Spatrick diagnosed = true;
731e5dd7070Spatrick }
732e5dd7070Spatrick }
733e5dd7070Spatrick }
734e5dd7070Spatrick
735e5dd7070Spatrick if (!diagnosed) {
736e5dd7070Spatrick Diag(qual ? qual.getBeginLoc()
737e5dd7070Spatrick : typeBoundInfo->getTypeLoc().getBeginLoc(),
738e5dd7070Spatrick diag::err_objc_type_param_bound_qualified)
739e5dd7070Spatrick << paramName << typeBound
740e5dd7070Spatrick << typeBound.getQualifiers().getAsString()
741e5dd7070Spatrick << FixItHint::CreateRemoval(rangeToRemove);
742e5dd7070Spatrick }
743e5dd7070Spatrick
744e5dd7070Spatrick // If the type bound has qualifiers other than CVR, we need to strip
745e5dd7070Spatrick // them or we'll probably assert later when trying to apply new
746e5dd7070Spatrick // qualifiers.
747e5dd7070Spatrick Qualifiers quals = typeBound.getQualifiers();
748e5dd7070Spatrick quals.removeCVRQualifiers();
749e5dd7070Spatrick if (!quals.empty()) {
750e5dd7070Spatrick typeBoundInfo =
751e5dd7070Spatrick Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
752e5dd7070Spatrick }
753e5dd7070Spatrick }
754e5dd7070Spatrick }
755e5dd7070Spatrick }
756e5dd7070Spatrick
757e5dd7070Spatrick // If there was no explicit type bound (or we removed it due to an error),
758e5dd7070Spatrick // use 'id' instead.
759e5dd7070Spatrick if (!typeBoundInfo) {
760e5dd7070Spatrick colonLoc = SourceLocation();
761e5dd7070Spatrick typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
762e5dd7070Spatrick }
763e5dd7070Spatrick
764e5dd7070Spatrick // Create the type parameter.
765e5dd7070Spatrick return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
766e5dd7070Spatrick index, paramLoc, paramName, colonLoc,
767e5dd7070Spatrick typeBoundInfo);
768e5dd7070Spatrick }
769e5dd7070Spatrick
actOnObjCTypeParamList(Scope * S,SourceLocation lAngleLoc,ArrayRef<Decl * > typeParamsIn,SourceLocation rAngleLoc)770e5dd7070Spatrick ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
771e5dd7070Spatrick SourceLocation lAngleLoc,
772e5dd7070Spatrick ArrayRef<Decl *> typeParamsIn,
773e5dd7070Spatrick SourceLocation rAngleLoc) {
774e5dd7070Spatrick // We know that the array only contains Objective-C type parameters.
775e5dd7070Spatrick ArrayRef<ObjCTypeParamDecl *>
776e5dd7070Spatrick typeParams(
777e5dd7070Spatrick reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
778e5dd7070Spatrick typeParamsIn.size());
779e5dd7070Spatrick
780e5dd7070Spatrick // Diagnose redeclarations of type parameters.
781e5dd7070Spatrick // We do this now because Objective-C type parameters aren't pushed into
782e5dd7070Spatrick // scope until later (after the instance variable block), but we want the
783e5dd7070Spatrick // diagnostics to occur right after we parse the type parameter list.
784e5dd7070Spatrick llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
785*12c85518Srobert for (auto *typeParam : typeParams) {
786e5dd7070Spatrick auto known = knownParams.find(typeParam->getIdentifier());
787e5dd7070Spatrick if (known != knownParams.end()) {
788e5dd7070Spatrick Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
789e5dd7070Spatrick << typeParam->getIdentifier()
790e5dd7070Spatrick << SourceRange(known->second->getLocation());
791e5dd7070Spatrick
792e5dd7070Spatrick typeParam->setInvalidDecl();
793e5dd7070Spatrick } else {
794e5dd7070Spatrick knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
795e5dd7070Spatrick
796e5dd7070Spatrick // Push the type parameter into scope.
797e5dd7070Spatrick PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
798e5dd7070Spatrick }
799e5dd7070Spatrick }
800e5dd7070Spatrick
801e5dd7070Spatrick // Create the parameter list.
802e5dd7070Spatrick return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
803e5dd7070Spatrick }
804e5dd7070Spatrick
popObjCTypeParamList(Scope * S,ObjCTypeParamList * typeParamList)805e5dd7070Spatrick void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
806*12c85518Srobert for (auto *typeParam : *typeParamList) {
807e5dd7070Spatrick if (!typeParam->isInvalidDecl()) {
808e5dd7070Spatrick S->RemoveDecl(typeParam);
809e5dd7070Spatrick IdResolver.RemoveDecl(typeParam);
810e5dd7070Spatrick }
811e5dd7070Spatrick }
812e5dd7070Spatrick }
813e5dd7070Spatrick
814e5dd7070Spatrick namespace {
815e5dd7070Spatrick /// The context in which an Objective-C type parameter list occurs, for use
816e5dd7070Spatrick /// in diagnostics.
817e5dd7070Spatrick enum class TypeParamListContext {
818e5dd7070Spatrick ForwardDeclaration,
819e5dd7070Spatrick Definition,
820e5dd7070Spatrick Category,
821e5dd7070Spatrick Extension
822e5dd7070Spatrick };
823e5dd7070Spatrick } // end anonymous namespace
824e5dd7070Spatrick
825e5dd7070Spatrick /// Check consistency between two Objective-C type parameter lists, e.g.,
826e5dd7070Spatrick /// between a category/extension and an \@interface or between an \@class and an
827e5dd7070Spatrick /// \@interface.
checkTypeParamListConsistency(Sema & S,ObjCTypeParamList * prevTypeParams,ObjCTypeParamList * newTypeParams,TypeParamListContext newContext)828e5dd7070Spatrick static bool checkTypeParamListConsistency(Sema &S,
829e5dd7070Spatrick ObjCTypeParamList *prevTypeParams,
830e5dd7070Spatrick ObjCTypeParamList *newTypeParams,
831e5dd7070Spatrick TypeParamListContext newContext) {
832e5dd7070Spatrick // If the sizes don't match, complain about that.
833e5dd7070Spatrick if (prevTypeParams->size() != newTypeParams->size()) {
834e5dd7070Spatrick SourceLocation diagLoc;
835e5dd7070Spatrick if (newTypeParams->size() > prevTypeParams->size()) {
836e5dd7070Spatrick diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
837e5dd7070Spatrick } else {
838e5dd7070Spatrick diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
839e5dd7070Spatrick }
840e5dd7070Spatrick
841e5dd7070Spatrick S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
842e5dd7070Spatrick << static_cast<unsigned>(newContext)
843e5dd7070Spatrick << (newTypeParams->size() > prevTypeParams->size())
844e5dd7070Spatrick << prevTypeParams->size()
845e5dd7070Spatrick << newTypeParams->size();
846e5dd7070Spatrick
847e5dd7070Spatrick return true;
848e5dd7070Spatrick }
849e5dd7070Spatrick
850e5dd7070Spatrick // Match up the type parameters.
851e5dd7070Spatrick for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
852e5dd7070Spatrick ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
853e5dd7070Spatrick ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
854e5dd7070Spatrick
855e5dd7070Spatrick // Check for consistency of the variance.
856e5dd7070Spatrick if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
857e5dd7070Spatrick if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
858e5dd7070Spatrick newContext != TypeParamListContext::Definition) {
859e5dd7070Spatrick // When the new type parameter is invariant and is not part
860e5dd7070Spatrick // of the definition, just propagate the variance.
861e5dd7070Spatrick newTypeParam->setVariance(prevTypeParam->getVariance());
862e5dd7070Spatrick } else if (prevTypeParam->getVariance()
863e5dd7070Spatrick == ObjCTypeParamVariance::Invariant &&
864e5dd7070Spatrick !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
865e5dd7070Spatrick cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
866e5dd7070Spatrick ->getDefinition() == prevTypeParam->getDeclContext())) {
867e5dd7070Spatrick // When the old parameter is invariant and was not part of the
868e5dd7070Spatrick // definition, just ignore the difference because it doesn't
869e5dd7070Spatrick // matter.
870e5dd7070Spatrick } else {
871e5dd7070Spatrick {
872e5dd7070Spatrick // Diagnose the conflict and update the second declaration.
873e5dd7070Spatrick SourceLocation diagLoc = newTypeParam->getVarianceLoc();
874e5dd7070Spatrick if (diagLoc.isInvalid())
875e5dd7070Spatrick diagLoc = newTypeParam->getBeginLoc();
876e5dd7070Spatrick
877e5dd7070Spatrick auto diag = S.Diag(diagLoc,
878e5dd7070Spatrick diag::err_objc_type_param_variance_conflict)
879e5dd7070Spatrick << static_cast<unsigned>(newTypeParam->getVariance())
880e5dd7070Spatrick << newTypeParam->getDeclName()
881e5dd7070Spatrick << static_cast<unsigned>(prevTypeParam->getVariance())
882e5dd7070Spatrick << prevTypeParam->getDeclName();
883e5dd7070Spatrick switch (prevTypeParam->getVariance()) {
884e5dd7070Spatrick case ObjCTypeParamVariance::Invariant:
885e5dd7070Spatrick diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
886e5dd7070Spatrick break;
887e5dd7070Spatrick
888e5dd7070Spatrick case ObjCTypeParamVariance::Covariant:
889e5dd7070Spatrick case ObjCTypeParamVariance::Contravariant: {
890e5dd7070Spatrick StringRef newVarianceStr
891e5dd7070Spatrick = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
892e5dd7070Spatrick ? "__covariant"
893e5dd7070Spatrick : "__contravariant";
894e5dd7070Spatrick if (newTypeParam->getVariance()
895e5dd7070Spatrick == ObjCTypeParamVariance::Invariant) {
896e5dd7070Spatrick diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
897e5dd7070Spatrick (newVarianceStr + " ").str());
898e5dd7070Spatrick } else {
899e5dd7070Spatrick diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
900e5dd7070Spatrick newVarianceStr);
901e5dd7070Spatrick }
902e5dd7070Spatrick }
903e5dd7070Spatrick }
904e5dd7070Spatrick }
905e5dd7070Spatrick
906e5dd7070Spatrick S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
907e5dd7070Spatrick << prevTypeParam->getDeclName();
908e5dd7070Spatrick
909e5dd7070Spatrick // Override the variance.
910e5dd7070Spatrick newTypeParam->setVariance(prevTypeParam->getVariance());
911e5dd7070Spatrick }
912e5dd7070Spatrick }
913e5dd7070Spatrick
914e5dd7070Spatrick // If the bound types match, there's nothing to do.
915e5dd7070Spatrick if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
916e5dd7070Spatrick newTypeParam->getUnderlyingType()))
917e5dd7070Spatrick continue;
918e5dd7070Spatrick
919e5dd7070Spatrick // If the new type parameter's bound was explicit, complain about it being
920e5dd7070Spatrick // different from the original.
921e5dd7070Spatrick if (newTypeParam->hasExplicitBound()) {
922e5dd7070Spatrick SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
923e5dd7070Spatrick ->getTypeLoc().getSourceRange();
924e5dd7070Spatrick S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
925e5dd7070Spatrick << newTypeParam->getUnderlyingType()
926e5dd7070Spatrick << newTypeParam->getDeclName()
927e5dd7070Spatrick << prevTypeParam->hasExplicitBound()
928e5dd7070Spatrick << prevTypeParam->getUnderlyingType()
929e5dd7070Spatrick << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
930e5dd7070Spatrick << prevTypeParam->getDeclName()
931e5dd7070Spatrick << FixItHint::CreateReplacement(
932e5dd7070Spatrick newBoundRange,
933e5dd7070Spatrick prevTypeParam->getUnderlyingType().getAsString(
934e5dd7070Spatrick S.Context.getPrintingPolicy()));
935e5dd7070Spatrick
936e5dd7070Spatrick S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
937e5dd7070Spatrick << prevTypeParam->getDeclName();
938e5dd7070Spatrick
939e5dd7070Spatrick // Override the new type parameter's bound type with the previous type,
940e5dd7070Spatrick // so that it's consistent.
941ec727ea7Spatrick S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
942e5dd7070Spatrick continue;
943e5dd7070Spatrick }
944e5dd7070Spatrick
945e5dd7070Spatrick // The new type parameter got the implicit bound of 'id'. That's okay for
946e5dd7070Spatrick // categories and extensions (overwrite it later), but not for forward
947e5dd7070Spatrick // declarations and @interfaces, because those must be standalone.
948e5dd7070Spatrick if (newContext == TypeParamListContext::ForwardDeclaration ||
949e5dd7070Spatrick newContext == TypeParamListContext::Definition) {
950e5dd7070Spatrick // Diagnose this problem for forward declarations and definitions.
951e5dd7070Spatrick SourceLocation insertionLoc
952e5dd7070Spatrick = S.getLocForEndOfToken(newTypeParam->getLocation());
953e5dd7070Spatrick std::string newCode
954e5dd7070Spatrick = " : " + prevTypeParam->getUnderlyingType().getAsString(
955e5dd7070Spatrick S.Context.getPrintingPolicy());
956e5dd7070Spatrick S.Diag(newTypeParam->getLocation(),
957e5dd7070Spatrick diag::err_objc_type_param_bound_missing)
958e5dd7070Spatrick << prevTypeParam->getUnderlyingType()
959e5dd7070Spatrick << newTypeParam->getDeclName()
960e5dd7070Spatrick << (newContext == TypeParamListContext::ForwardDeclaration)
961e5dd7070Spatrick << FixItHint::CreateInsertion(insertionLoc, newCode);
962e5dd7070Spatrick
963e5dd7070Spatrick S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
964e5dd7070Spatrick << prevTypeParam->getDeclName();
965e5dd7070Spatrick }
966e5dd7070Spatrick
967e5dd7070Spatrick // Update the new type parameter's bound to match the previous one.
968ec727ea7Spatrick S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
969e5dd7070Spatrick }
970e5dd7070Spatrick
971e5dd7070Spatrick return false;
972e5dd7070Spatrick }
973e5dd7070Spatrick
ActOnStartClassInterface(Scope * S,SourceLocation AtInterfaceLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,ObjCTypeParamList * typeParamList,IdentifierInfo * SuperName,SourceLocation SuperLoc,ArrayRef<ParsedType> SuperTypeArgs,SourceRange SuperTypeArgsRange,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc,const ParsedAttributesView & AttrList,SkipBodyInfo * SkipBody)974*12c85518Srobert ObjCInterfaceDecl *Sema::ActOnStartClassInterface(
975e5dd7070Spatrick Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
976e5dd7070Spatrick SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
977e5dd7070Spatrick IdentifierInfo *SuperName, SourceLocation SuperLoc,
978e5dd7070Spatrick ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
979e5dd7070Spatrick Decl *const *ProtoRefs, unsigned NumProtoRefs,
980e5dd7070Spatrick const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
981*12c85518Srobert const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
982e5dd7070Spatrick assert(ClassName && "Missing class identifier");
983e5dd7070Spatrick
984e5dd7070Spatrick // Check for another declaration kind with the same name.
985e5dd7070Spatrick NamedDecl *PrevDecl =
986e5dd7070Spatrick LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
987e5dd7070Spatrick forRedeclarationInCurContext());
988e5dd7070Spatrick
989e5dd7070Spatrick if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
990e5dd7070Spatrick Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
991e5dd7070Spatrick Diag(PrevDecl->getLocation(), diag::note_previous_definition);
992e5dd7070Spatrick }
993e5dd7070Spatrick
994e5dd7070Spatrick // Create a declaration to describe this @interface.
995e5dd7070Spatrick ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
996e5dd7070Spatrick
997e5dd7070Spatrick if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
998e5dd7070Spatrick // A previous decl with a different name is because of
999e5dd7070Spatrick // @compatibility_alias, for example:
1000e5dd7070Spatrick // \code
1001e5dd7070Spatrick // @class NewImage;
1002e5dd7070Spatrick // @compatibility_alias OldImage NewImage;
1003e5dd7070Spatrick // \endcode
1004e5dd7070Spatrick // A lookup for 'OldImage' will return the 'NewImage' decl.
1005e5dd7070Spatrick //
1006e5dd7070Spatrick // In such a case use the real declaration name, instead of the alias one,
1007e5dd7070Spatrick // otherwise we will break IdentifierResolver and redecls-chain invariants.
1008e5dd7070Spatrick // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1009e5dd7070Spatrick // has been aliased.
1010e5dd7070Spatrick ClassName = PrevIDecl->getIdentifier();
1011e5dd7070Spatrick }
1012e5dd7070Spatrick
1013e5dd7070Spatrick // If there was a forward declaration with type parameters, check
1014e5dd7070Spatrick // for consistency.
1015e5dd7070Spatrick if (PrevIDecl) {
1016e5dd7070Spatrick if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1017e5dd7070Spatrick if (typeParamList) {
1018e5dd7070Spatrick // Both have type parameter lists; check for consistency.
1019e5dd7070Spatrick if (checkTypeParamListConsistency(*this, prevTypeParamList,
1020e5dd7070Spatrick typeParamList,
1021e5dd7070Spatrick TypeParamListContext::Definition)) {
1022e5dd7070Spatrick typeParamList = nullptr;
1023e5dd7070Spatrick }
1024e5dd7070Spatrick } else {
1025e5dd7070Spatrick Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1026e5dd7070Spatrick << ClassName;
1027e5dd7070Spatrick Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1028e5dd7070Spatrick << ClassName;
1029e5dd7070Spatrick
1030e5dd7070Spatrick // Clone the type parameter list.
1031e5dd7070Spatrick SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1032*12c85518Srobert for (auto *typeParam : *prevTypeParamList) {
1033e5dd7070Spatrick clonedTypeParams.push_back(
1034e5dd7070Spatrick ObjCTypeParamDecl::Create(
1035e5dd7070Spatrick Context,
1036e5dd7070Spatrick CurContext,
1037e5dd7070Spatrick typeParam->getVariance(),
1038e5dd7070Spatrick SourceLocation(),
1039e5dd7070Spatrick typeParam->getIndex(),
1040e5dd7070Spatrick SourceLocation(),
1041e5dd7070Spatrick typeParam->getIdentifier(),
1042e5dd7070Spatrick SourceLocation(),
1043e5dd7070Spatrick Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1044e5dd7070Spatrick }
1045e5dd7070Spatrick
1046e5dd7070Spatrick typeParamList = ObjCTypeParamList::create(Context,
1047e5dd7070Spatrick SourceLocation(),
1048e5dd7070Spatrick clonedTypeParams,
1049e5dd7070Spatrick SourceLocation());
1050e5dd7070Spatrick }
1051e5dd7070Spatrick }
1052e5dd7070Spatrick }
1053e5dd7070Spatrick
1054e5dd7070Spatrick ObjCInterfaceDecl *IDecl
1055e5dd7070Spatrick = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
1056e5dd7070Spatrick typeParamList, PrevIDecl, ClassLoc);
1057e5dd7070Spatrick if (PrevIDecl) {
1058e5dd7070Spatrick // Class already seen. Was it a definition?
1059e5dd7070Spatrick if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1060*12c85518Srobert if (SkipBody && !hasVisibleDefinition(Def)) {
1061*12c85518Srobert SkipBody->CheckSameAsPrevious = true;
1062*12c85518Srobert SkipBody->New = IDecl;
1063*12c85518Srobert SkipBody->Previous = Def;
1064*12c85518Srobert } else {
1065e5dd7070Spatrick Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1066e5dd7070Spatrick << PrevIDecl->getDeclName();
1067e5dd7070Spatrick Diag(Def->getLocation(), diag::note_previous_definition);
1068e5dd7070Spatrick IDecl->setInvalidDecl();
1069e5dd7070Spatrick }
1070e5dd7070Spatrick }
1071*12c85518Srobert }
1072e5dd7070Spatrick
1073e5dd7070Spatrick ProcessDeclAttributeList(TUScope, IDecl, AttrList);
1074e5dd7070Spatrick AddPragmaAttributes(TUScope, IDecl);
1075a9ac8606Spatrick
1076a9ac8606Spatrick // Merge attributes from previous declarations.
1077a9ac8606Spatrick if (PrevIDecl)
1078a9ac8606Spatrick mergeDeclAttributes(IDecl, PrevIDecl);
1079a9ac8606Spatrick
1080e5dd7070Spatrick PushOnScopeChains(IDecl, TUScope);
1081e5dd7070Spatrick
1082e5dd7070Spatrick // Start the definition of this class. If we're in a redefinition case, there
1083e5dd7070Spatrick // may already be a definition, so we'll end up adding to it.
1084*12c85518Srobert if (SkipBody && SkipBody->CheckSameAsPrevious)
1085*12c85518Srobert IDecl->startDuplicateDefinitionForComparison();
1086*12c85518Srobert else if (!IDecl->hasDefinition())
1087e5dd7070Spatrick IDecl->startDefinition();
1088e5dd7070Spatrick
1089e5dd7070Spatrick if (SuperName) {
1090e5dd7070Spatrick // Diagnose availability in the context of the @interface.
1091e5dd7070Spatrick ContextRAII SavedContext(*this, IDecl);
1092e5dd7070Spatrick
1093e5dd7070Spatrick ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1094e5dd7070Spatrick ClassName, ClassLoc,
1095e5dd7070Spatrick SuperName, SuperLoc, SuperTypeArgs,
1096e5dd7070Spatrick SuperTypeArgsRange);
1097e5dd7070Spatrick } else { // we have a root class.
1098e5dd7070Spatrick IDecl->setEndOfDefinitionLoc(ClassLoc);
1099e5dd7070Spatrick }
1100e5dd7070Spatrick
1101e5dd7070Spatrick // Check then save referenced protocols.
1102e5dd7070Spatrick if (NumProtoRefs) {
1103e5dd7070Spatrick diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1104e5dd7070Spatrick NumProtoRefs, ProtoLocs);
1105e5dd7070Spatrick IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1106e5dd7070Spatrick ProtoLocs, Context);
1107e5dd7070Spatrick IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1108e5dd7070Spatrick }
1109e5dd7070Spatrick
1110e5dd7070Spatrick CheckObjCDeclScope(IDecl);
1111*12c85518Srobert ActOnObjCContainerStartDefinition(IDecl);
1112*12c85518Srobert return IDecl;
1113e5dd7070Spatrick }
1114e5dd7070Spatrick
1115e5dd7070Spatrick /// ActOnTypedefedProtocols - this action finds protocol list as part of the
1116e5dd7070Spatrick /// typedef'ed use for a qualified super class and adds them to the list
1117e5dd7070Spatrick /// of the protocols.
ActOnTypedefedProtocols(SmallVectorImpl<Decl * > & ProtocolRefs,SmallVectorImpl<SourceLocation> & ProtocolLocs,IdentifierInfo * SuperName,SourceLocation SuperLoc)1118e5dd7070Spatrick void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1119e5dd7070Spatrick SmallVectorImpl<SourceLocation> &ProtocolLocs,
1120e5dd7070Spatrick IdentifierInfo *SuperName,
1121e5dd7070Spatrick SourceLocation SuperLoc) {
1122e5dd7070Spatrick if (!SuperName)
1123e5dd7070Spatrick return;
1124e5dd7070Spatrick NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1125e5dd7070Spatrick LookupOrdinaryName);
1126e5dd7070Spatrick if (!IDecl)
1127e5dd7070Spatrick return;
1128e5dd7070Spatrick
1129e5dd7070Spatrick if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1130e5dd7070Spatrick QualType T = TDecl->getUnderlyingType();
1131e5dd7070Spatrick if (T->isObjCObjectType())
1132e5dd7070Spatrick if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1133e5dd7070Spatrick ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1134e5dd7070Spatrick // FIXME: Consider whether this should be an invalid loc since the loc
1135e5dd7070Spatrick // is not actually pointing to a protocol name reference but to the
1136e5dd7070Spatrick // typedef reference. Note that the base class name loc is also pointing
1137e5dd7070Spatrick // at the typedef.
1138e5dd7070Spatrick ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1139e5dd7070Spatrick }
1140e5dd7070Spatrick }
1141e5dd7070Spatrick }
1142e5dd7070Spatrick
1143e5dd7070Spatrick /// ActOnCompatibilityAlias - this action is called after complete parsing of
1144e5dd7070Spatrick /// a \@compatibility_alias declaration. It sets up the alias relationships.
ActOnCompatibilityAlias(SourceLocation AtLoc,IdentifierInfo * AliasName,SourceLocation AliasLocation,IdentifierInfo * ClassName,SourceLocation ClassLocation)1145e5dd7070Spatrick Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1146e5dd7070Spatrick IdentifierInfo *AliasName,
1147e5dd7070Spatrick SourceLocation AliasLocation,
1148e5dd7070Spatrick IdentifierInfo *ClassName,
1149e5dd7070Spatrick SourceLocation ClassLocation) {
1150e5dd7070Spatrick // Look for previous declaration of alias name
1151e5dd7070Spatrick NamedDecl *ADecl =
1152e5dd7070Spatrick LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1153e5dd7070Spatrick forRedeclarationInCurContext());
1154e5dd7070Spatrick if (ADecl) {
1155e5dd7070Spatrick Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1156e5dd7070Spatrick Diag(ADecl->getLocation(), diag::note_previous_declaration);
1157e5dd7070Spatrick return nullptr;
1158e5dd7070Spatrick }
1159e5dd7070Spatrick // Check for class declaration
1160e5dd7070Spatrick NamedDecl *CDeclU =
1161e5dd7070Spatrick LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1162e5dd7070Spatrick forRedeclarationInCurContext());
1163e5dd7070Spatrick if (const TypedefNameDecl *TDecl =
1164e5dd7070Spatrick dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1165e5dd7070Spatrick QualType T = TDecl->getUnderlyingType();
1166e5dd7070Spatrick if (T->isObjCObjectType()) {
1167e5dd7070Spatrick if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
1168e5dd7070Spatrick ClassName = IDecl->getIdentifier();
1169e5dd7070Spatrick CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1170e5dd7070Spatrick LookupOrdinaryName,
1171e5dd7070Spatrick forRedeclarationInCurContext());
1172e5dd7070Spatrick }
1173e5dd7070Spatrick }
1174e5dd7070Spatrick }
1175e5dd7070Spatrick ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1176e5dd7070Spatrick if (!CDecl) {
1177e5dd7070Spatrick Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1178e5dd7070Spatrick if (CDeclU)
1179e5dd7070Spatrick Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1180e5dd7070Spatrick return nullptr;
1181e5dd7070Spatrick }
1182e5dd7070Spatrick
1183e5dd7070Spatrick // Everything checked out, instantiate a new alias declaration AST.
1184e5dd7070Spatrick ObjCCompatibleAliasDecl *AliasDecl =
1185e5dd7070Spatrick ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1186e5dd7070Spatrick
1187e5dd7070Spatrick if (!CheckObjCDeclScope(AliasDecl))
1188e5dd7070Spatrick PushOnScopeChains(AliasDecl, TUScope);
1189e5dd7070Spatrick
1190e5dd7070Spatrick return AliasDecl;
1191e5dd7070Spatrick }
1192e5dd7070Spatrick
CheckForwardProtocolDeclarationForCircularDependency(IdentifierInfo * PName,SourceLocation & Ploc,SourceLocation PrevLoc,const ObjCList<ObjCProtocolDecl> & PList)1193e5dd7070Spatrick bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
1194e5dd7070Spatrick IdentifierInfo *PName,
1195e5dd7070Spatrick SourceLocation &Ploc, SourceLocation PrevLoc,
1196e5dd7070Spatrick const ObjCList<ObjCProtocolDecl> &PList) {
1197e5dd7070Spatrick
1198e5dd7070Spatrick bool res = false;
1199e5dd7070Spatrick for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1200e5dd7070Spatrick E = PList.end(); I != E; ++I) {
1201e5dd7070Spatrick if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1202e5dd7070Spatrick Ploc)) {
1203e5dd7070Spatrick if (PDecl->getIdentifier() == PName) {
1204e5dd7070Spatrick Diag(Ploc, diag::err_protocol_has_circular_dependency);
1205e5dd7070Spatrick Diag(PrevLoc, diag::note_previous_definition);
1206e5dd7070Spatrick res = true;
1207e5dd7070Spatrick }
1208e5dd7070Spatrick
1209e5dd7070Spatrick if (!PDecl->hasDefinition())
1210e5dd7070Spatrick continue;
1211e5dd7070Spatrick
1212e5dd7070Spatrick if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1213e5dd7070Spatrick PDecl->getLocation(), PDecl->getReferencedProtocols()))
1214e5dd7070Spatrick res = true;
1215e5dd7070Spatrick }
1216e5dd7070Spatrick }
1217e5dd7070Spatrick return res;
1218e5dd7070Spatrick }
1219e5dd7070Spatrick
ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,IdentifierInfo * ProtocolName,SourceLocation ProtocolLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc,const ParsedAttributesView & AttrList,SkipBodyInfo * SkipBody)1220*12c85518Srobert ObjCProtocolDecl *Sema::ActOnStartProtocolInterface(
1221e5dd7070Spatrick SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1222e5dd7070Spatrick SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1223e5dd7070Spatrick const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1224*12c85518Srobert const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
1225e5dd7070Spatrick bool err = false;
1226e5dd7070Spatrick // FIXME: Deal with AttrList.
1227e5dd7070Spatrick assert(ProtocolName && "Missing protocol identifier");
1228e5dd7070Spatrick ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1229e5dd7070Spatrick forRedeclarationInCurContext());
1230e5dd7070Spatrick ObjCProtocolDecl *PDecl = nullptr;
1231e5dd7070Spatrick if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1232e5dd7070Spatrick // Create a new protocol that is completely distinct from previous
1233e5dd7070Spatrick // declarations, and do not make this protocol available for name lookup.
1234e5dd7070Spatrick // That way, we'll end up completely ignoring the duplicate.
1235e5dd7070Spatrick // FIXME: Can we turn this into an error?
1236e5dd7070Spatrick PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1237e5dd7070Spatrick ProtocolLoc, AtProtoInterfaceLoc,
1238*12c85518Srobert /*PrevDecl=*/Def);
1239*12c85518Srobert
1240*12c85518Srobert if (SkipBody && !hasVisibleDefinition(Def)) {
1241*12c85518Srobert SkipBody->CheckSameAsPrevious = true;
1242*12c85518Srobert SkipBody->New = PDecl;
1243*12c85518Srobert SkipBody->Previous = Def;
1244*12c85518Srobert } else {
1245*12c85518Srobert // If we already have a definition, complain.
1246*12c85518Srobert Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1247*12c85518Srobert Diag(Def->getLocation(), diag::note_previous_definition);
1248*12c85518Srobert }
1249e5dd7070Spatrick
1250e5dd7070Spatrick // If we are using modules, add the decl to the context in order to
1251e5dd7070Spatrick // serialize something meaningful.
1252e5dd7070Spatrick if (getLangOpts().Modules)
1253e5dd7070Spatrick PushOnScopeChains(PDecl, TUScope);
1254*12c85518Srobert PDecl->startDuplicateDefinitionForComparison();
1255e5dd7070Spatrick } else {
1256e5dd7070Spatrick if (PrevDecl) {
1257e5dd7070Spatrick // Check for circular dependencies among protocol declarations. This can
1258e5dd7070Spatrick // only happen if this protocol was forward-declared.
1259e5dd7070Spatrick ObjCList<ObjCProtocolDecl> PList;
1260e5dd7070Spatrick PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1261e5dd7070Spatrick err = CheckForwardProtocolDeclarationForCircularDependency(
1262e5dd7070Spatrick ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1263e5dd7070Spatrick }
1264e5dd7070Spatrick
1265e5dd7070Spatrick // Create the new declaration.
1266e5dd7070Spatrick PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1267e5dd7070Spatrick ProtocolLoc, AtProtoInterfaceLoc,
1268e5dd7070Spatrick /*PrevDecl=*/PrevDecl);
1269e5dd7070Spatrick
1270e5dd7070Spatrick PushOnScopeChains(PDecl, TUScope);
1271e5dd7070Spatrick PDecl->startDefinition();
1272e5dd7070Spatrick }
1273e5dd7070Spatrick
1274e5dd7070Spatrick ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1275e5dd7070Spatrick AddPragmaAttributes(TUScope, PDecl);
1276e5dd7070Spatrick
1277e5dd7070Spatrick // Merge attributes from previous declarations.
1278e5dd7070Spatrick if (PrevDecl)
1279e5dd7070Spatrick mergeDeclAttributes(PDecl, PrevDecl);
1280e5dd7070Spatrick
1281e5dd7070Spatrick if (!err && NumProtoRefs ) {
1282e5dd7070Spatrick /// Check then save referenced protocols.
1283e5dd7070Spatrick diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1284e5dd7070Spatrick NumProtoRefs, ProtoLocs);
1285e5dd7070Spatrick PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1286e5dd7070Spatrick ProtoLocs, Context);
1287e5dd7070Spatrick }
1288e5dd7070Spatrick
1289e5dd7070Spatrick CheckObjCDeclScope(PDecl);
1290*12c85518Srobert ActOnObjCContainerStartDefinition(PDecl);
1291*12c85518Srobert return PDecl;
1292e5dd7070Spatrick }
1293e5dd7070Spatrick
NestedProtocolHasNoDefinition(ObjCProtocolDecl * PDecl,ObjCProtocolDecl * & UndefinedProtocol)1294e5dd7070Spatrick static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1295e5dd7070Spatrick ObjCProtocolDecl *&UndefinedProtocol) {
1296ec727ea7Spatrick if (!PDecl->hasDefinition() ||
1297ec727ea7Spatrick !PDecl->getDefinition()->isUnconditionallyVisible()) {
1298e5dd7070Spatrick UndefinedProtocol = PDecl;
1299e5dd7070Spatrick return true;
1300e5dd7070Spatrick }
1301e5dd7070Spatrick
1302e5dd7070Spatrick for (auto *PI : PDecl->protocols())
1303e5dd7070Spatrick if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1304e5dd7070Spatrick UndefinedProtocol = PI;
1305e5dd7070Spatrick return true;
1306e5dd7070Spatrick }
1307e5dd7070Spatrick return false;
1308e5dd7070Spatrick }
1309e5dd7070Spatrick
1310e5dd7070Spatrick /// FindProtocolDeclaration - This routine looks up protocols and
1311e5dd7070Spatrick /// issues an error if they are not declared. It returns list of
1312e5dd7070Spatrick /// protocol declarations in its 'Protocols' argument.
1313e5dd7070Spatrick void
FindProtocolDeclaration(bool WarnOnDeclarations,bool ForObjCContainer,ArrayRef<IdentifierLocPair> ProtocolId,SmallVectorImpl<Decl * > & Protocols)1314e5dd7070Spatrick Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1315e5dd7070Spatrick ArrayRef<IdentifierLocPair> ProtocolId,
1316e5dd7070Spatrick SmallVectorImpl<Decl *> &Protocols) {
1317e5dd7070Spatrick for (const IdentifierLocPair &Pair : ProtocolId) {
1318e5dd7070Spatrick ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1319e5dd7070Spatrick if (!PDecl) {
1320e5dd7070Spatrick DeclFilterCCC<ObjCProtocolDecl> CCC{};
1321e5dd7070Spatrick TypoCorrection Corrected = CorrectTypo(
1322e5dd7070Spatrick DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
1323e5dd7070Spatrick TUScope, nullptr, CCC, CTK_ErrorRecovery);
1324e5dd7070Spatrick if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1325e5dd7070Spatrick diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1326e5dd7070Spatrick << Pair.first);
1327e5dd7070Spatrick }
1328e5dd7070Spatrick
1329e5dd7070Spatrick if (!PDecl) {
1330e5dd7070Spatrick Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1331e5dd7070Spatrick continue;
1332e5dd7070Spatrick }
1333e5dd7070Spatrick // If this is a forward protocol declaration, get its definition.
1334e5dd7070Spatrick if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1335e5dd7070Spatrick PDecl = PDecl->getDefinition();
1336e5dd7070Spatrick
1337e5dd7070Spatrick // For an objc container, delay protocol reference checking until after we
1338e5dd7070Spatrick // can set the objc decl as the availability context, otherwise check now.
1339e5dd7070Spatrick if (!ForObjCContainer) {
1340e5dd7070Spatrick (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1341e5dd7070Spatrick }
1342e5dd7070Spatrick
1343e5dd7070Spatrick // If this is a forward declaration and we are supposed to warn in this
1344e5dd7070Spatrick // case, do it.
1345e5dd7070Spatrick // FIXME: Recover nicely in the hidden case.
1346e5dd7070Spatrick ObjCProtocolDecl *UndefinedProtocol;
1347e5dd7070Spatrick
1348e5dd7070Spatrick if (WarnOnDeclarations &&
1349e5dd7070Spatrick NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1350e5dd7070Spatrick Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1351e5dd7070Spatrick Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1352e5dd7070Spatrick << UndefinedProtocol;
1353e5dd7070Spatrick }
1354e5dd7070Spatrick Protocols.push_back(PDecl);
1355e5dd7070Spatrick }
1356e5dd7070Spatrick }
1357e5dd7070Spatrick
1358e5dd7070Spatrick namespace {
1359e5dd7070Spatrick // Callback to only accept typo corrections that are either
1360e5dd7070Spatrick // Objective-C protocols or valid Objective-C type arguments.
1361e5dd7070Spatrick class ObjCTypeArgOrProtocolValidatorCCC final
1362e5dd7070Spatrick : public CorrectionCandidateCallback {
1363e5dd7070Spatrick ASTContext &Context;
1364e5dd7070Spatrick Sema::LookupNameKind LookupKind;
1365e5dd7070Spatrick public:
ObjCTypeArgOrProtocolValidatorCCC(ASTContext & context,Sema::LookupNameKind lookupKind)1366e5dd7070Spatrick ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1367e5dd7070Spatrick Sema::LookupNameKind lookupKind)
1368e5dd7070Spatrick : Context(context), LookupKind(lookupKind) { }
1369e5dd7070Spatrick
ValidateCandidate(const TypoCorrection & candidate)1370e5dd7070Spatrick bool ValidateCandidate(const TypoCorrection &candidate) override {
1371e5dd7070Spatrick // If we're allowed to find protocols and we have a protocol, accept it.
1372e5dd7070Spatrick if (LookupKind != Sema::LookupOrdinaryName) {
1373e5dd7070Spatrick if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1374e5dd7070Spatrick return true;
1375e5dd7070Spatrick }
1376e5dd7070Spatrick
1377e5dd7070Spatrick // If we're allowed to find type names and we have one, accept it.
1378e5dd7070Spatrick if (LookupKind != Sema::LookupObjCProtocolName) {
1379e5dd7070Spatrick // If we have a type declaration, we might accept this result.
1380e5dd7070Spatrick if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1381e5dd7070Spatrick // If we found a tag declaration outside of C++, skip it. This
1382e5dd7070Spatrick // can happy because we look for any name when there is no
1383e5dd7070Spatrick // bias to protocol or type names.
1384e5dd7070Spatrick if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1385e5dd7070Spatrick return false;
1386e5dd7070Spatrick
1387e5dd7070Spatrick // Make sure the type is something we would accept as a type
1388e5dd7070Spatrick // argument.
1389e5dd7070Spatrick auto type = Context.getTypeDeclType(typeDecl);
1390e5dd7070Spatrick if (type->isObjCObjectPointerType() ||
1391e5dd7070Spatrick type->isBlockPointerType() ||
1392e5dd7070Spatrick type->isDependentType() ||
1393e5dd7070Spatrick type->isObjCObjectType())
1394e5dd7070Spatrick return true;
1395e5dd7070Spatrick
1396e5dd7070Spatrick return false;
1397e5dd7070Spatrick }
1398e5dd7070Spatrick
1399e5dd7070Spatrick // If we have an Objective-C class type, accept it; there will
1400e5dd7070Spatrick // be another fix to add the '*'.
1401e5dd7070Spatrick if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1402e5dd7070Spatrick return true;
1403e5dd7070Spatrick
1404e5dd7070Spatrick return false;
1405e5dd7070Spatrick }
1406e5dd7070Spatrick
1407e5dd7070Spatrick return false;
1408e5dd7070Spatrick }
1409e5dd7070Spatrick
clone()1410e5dd7070Spatrick std::unique_ptr<CorrectionCandidateCallback> clone() override {
1411e5dd7070Spatrick return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1412e5dd7070Spatrick }
1413e5dd7070Spatrick };
1414e5dd7070Spatrick } // end anonymous namespace
1415e5dd7070Spatrick
DiagnoseTypeArgsAndProtocols(IdentifierInfo * ProtocolId,SourceLocation ProtocolLoc,IdentifierInfo * TypeArgId,SourceLocation TypeArgLoc,bool SelectProtocolFirst)1416e5dd7070Spatrick void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1417e5dd7070Spatrick SourceLocation ProtocolLoc,
1418e5dd7070Spatrick IdentifierInfo *TypeArgId,
1419e5dd7070Spatrick SourceLocation TypeArgLoc,
1420e5dd7070Spatrick bool SelectProtocolFirst) {
1421e5dd7070Spatrick Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1422e5dd7070Spatrick << SelectProtocolFirst << TypeArgId << ProtocolId
1423e5dd7070Spatrick << SourceRange(ProtocolLoc);
1424e5dd7070Spatrick }
1425e5dd7070Spatrick
actOnObjCTypeArgsOrProtocolQualifiers(Scope * S,ParsedType baseType,SourceLocation lAngleLoc,ArrayRef<IdentifierInfo * > identifiers,ArrayRef<SourceLocation> identifierLocs,SourceLocation rAngleLoc,SourceLocation & typeArgsLAngleLoc,SmallVectorImpl<ParsedType> & typeArgs,SourceLocation & typeArgsRAngleLoc,SourceLocation & protocolLAngleLoc,SmallVectorImpl<Decl * > & protocols,SourceLocation & protocolRAngleLoc,bool warnOnIncompleteProtocols)1426e5dd7070Spatrick void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1427e5dd7070Spatrick Scope *S,
1428e5dd7070Spatrick ParsedType baseType,
1429e5dd7070Spatrick SourceLocation lAngleLoc,
1430e5dd7070Spatrick ArrayRef<IdentifierInfo *> identifiers,
1431e5dd7070Spatrick ArrayRef<SourceLocation> identifierLocs,
1432e5dd7070Spatrick SourceLocation rAngleLoc,
1433e5dd7070Spatrick SourceLocation &typeArgsLAngleLoc,
1434e5dd7070Spatrick SmallVectorImpl<ParsedType> &typeArgs,
1435e5dd7070Spatrick SourceLocation &typeArgsRAngleLoc,
1436e5dd7070Spatrick SourceLocation &protocolLAngleLoc,
1437e5dd7070Spatrick SmallVectorImpl<Decl *> &protocols,
1438e5dd7070Spatrick SourceLocation &protocolRAngleLoc,
1439e5dd7070Spatrick bool warnOnIncompleteProtocols) {
1440e5dd7070Spatrick // Local function that updates the declaration specifiers with
1441e5dd7070Spatrick // protocol information.
1442e5dd7070Spatrick unsigned numProtocolsResolved = 0;
1443e5dd7070Spatrick auto resolvedAsProtocols = [&] {
1444e5dd7070Spatrick assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1445e5dd7070Spatrick
1446e5dd7070Spatrick // Determine whether the base type is a parameterized class, in
1447e5dd7070Spatrick // which case we want to warn about typos such as
1448e5dd7070Spatrick // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1449e5dd7070Spatrick ObjCInterfaceDecl *baseClass = nullptr;
1450e5dd7070Spatrick QualType base = GetTypeFromParser(baseType, nullptr);
1451e5dd7070Spatrick bool allAreTypeNames = false;
1452e5dd7070Spatrick SourceLocation firstClassNameLoc;
1453e5dd7070Spatrick if (!base.isNull()) {
1454e5dd7070Spatrick if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1455e5dd7070Spatrick baseClass = objcObjectType->getInterface();
1456e5dd7070Spatrick if (baseClass) {
1457e5dd7070Spatrick if (auto typeParams = baseClass->getTypeParamList()) {
1458e5dd7070Spatrick if (typeParams->size() == numProtocolsResolved) {
1459e5dd7070Spatrick // Note that we should be looking for type names, too.
1460e5dd7070Spatrick allAreTypeNames = true;
1461e5dd7070Spatrick }
1462e5dd7070Spatrick }
1463e5dd7070Spatrick }
1464e5dd7070Spatrick }
1465e5dd7070Spatrick }
1466e5dd7070Spatrick
1467e5dd7070Spatrick for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1468e5dd7070Spatrick ObjCProtocolDecl *&proto
1469e5dd7070Spatrick = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1470e5dd7070Spatrick // For an objc container, delay protocol reference checking until after we
1471e5dd7070Spatrick // can set the objc decl as the availability context, otherwise check now.
1472e5dd7070Spatrick if (!warnOnIncompleteProtocols) {
1473e5dd7070Spatrick (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1474e5dd7070Spatrick }
1475e5dd7070Spatrick
1476e5dd7070Spatrick // If this is a forward protocol declaration, get its definition.
1477e5dd7070Spatrick if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1478e5dd7070Spatrick proto = proto->getDefinition();
1479e5dd7070Spatrick
1480e5dd7070Spatrick // If this is a forward declaration and we are supposed to warn in this
1481e5dd7070Spatrick // case, do it.
1482e5dd7070Spatrick // FIXME: Recover nicely in the hidden case.
1483e5dd7070Spatrick ObjCProtocolDecl *forwardDecl = nullptr;
1484e5dd7070Spatrick if (warnOnIncompleteProtocols &&
1485e5dd7070Spatrick NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1486e5dd7070Spatrick Diag(identifierLocs[i], diag::warn_undef_protocolref)
1487e5dd7070Spatrick << proto->getDeclName();
1488e5dd7070Spatrick Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1489e5dd7070Spatrick << forwardDecl;
1490e5dd7070Spatrick }
1491e5dd7070Spatrick
1492e5dd7070Spatrick // If everything this far has been a type name (and we care
1493e5dd7070Spatrick // about such things), check whether this name refers to a type
1494e5dd7070Spatrick // as well.
1495e5dd7070Spatrick if (allAreTypeNames) {
1496e5dd7070Spatrick if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1497e5dd7070Spatrick LookupOrdinaryName)) {
1498e5dd7070Spatrick if (isa<ObjCInterfaceDecl>(decl)) {
1499e5dd7070Spatrick if (firstClassNameLoc.isInvalid())
1500e5dd7070Spatrick firstClassNameLoc = identifierLocs[i];
1501e5dd7070Spatrick } else if (!isa<TypeDecl>(decl)) {
1502e5dd7070Spatrick // Not a type.
1503e5dd7070Spatrick allAreTypeNames = false;
1504e5dd7070Spatrick }
1505e5dd7070Spatrick } else {
1506e5dd7070Spatrick allAreTypeNames = false;
1507e5dd7070Spatrick }
1508e5dd7070Spatrick }
1509e5dd7070Spatrick }
1510e5dd7070Spatrick
1511e5dd7070Spatrick // All of the protocols listed also have type names, and at least
1512e5dd7070Spatrick // one is an Objective-C class name. Check whether all of the
1513e5dd7070Spatrick // protocol conformances are declared by the base class itself, in
1514e5dd7070Spatrick // which case we warn.
1515e5dd7070Spatrick if (allAreTypeNames && firstClassNameLoc.isValid()) {
1516e5dd7070Spatrick llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1517e5dd7070Spatrick Context.CollectInheritedProtocols(baseClass, knownProtocols);
1518e5dd7070Spatrick bool allProtocolsDeclared = true;
1519*12c85518Srobert for (auto *proto : protocols) {
1520e5dd7070Spatrick if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1521e5dd7070Spatrick allProtocolsDeclared = false;
1522e5dd7070Spatrick break;
1523e5dd7070Spatrick }
1524e5dd7070Spatrick }
1525e5dd7070Spatrick
1526e5dd7070Spatrick if (allProtocolsDeclared) {
1527e5dd7070Spatrick Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1528e5dd7070Spatrick << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1529e5dd7070Spatrick << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1530e5dd7070Spatrick " *");
1531e5dd7070Spatrick }
1532e5dd7070Spatrick }
1533e5dd7070Spatrick
1534e5dd7070Spatrick protocolLAngleLoc = lAngleLoc;
1535e5dd7070Spatrick protocolRAngleLoc = rAngleLoc;
1536e5dd7070Spatrick assert(protocols.size() == identifierLocs.size());
1537e5dd7070Spatrick };
1538e5dd7070Spatrick
1539e5dd7070Spatrick // Attempt to resolve all of the identifiers as protocols.
1540e5dd7070Spatrick for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1541e5dd7070Spatrick ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1542e5dd7070Spatrick protocols.push_back(proto);
1543e5dd7070Spatrick if (proto)
1544e5dd7070Spatrick ++numProtocolsResolved;
1545e5dd7070Spatrick }
1546e5dd7070Spatrick
1547e5dd7070Spatrick // If all of the names were protocols, these were protocol qualifiers.
1548e5dd7070Spatrick if (numProtocolsResolved == identifiers.size())
1549e5dd7070Spatrick return resolvedAsProtocols();
1550e5dd7070Spatrick
1551e5dd7070Spatrick // Attempt to resolve all of the identifiers as type names or
1552e5dd7070Spatrick // Objective-C class names. The latter is technically ill-formed,
1553e5dd7070Spatrick // but is probably something like \c NSArray<NSView *> missing the
1554e5dd7070Spatrick // \c*.
1555e5dd7070Spatrick typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1556e5dd7070Spatrick SmallVector<TypeOrClassDecl, 4> typeDecls;
1557e5dd7070Spatrick unsigned numTypeDeclsResolved = 0;
1558e5dd7070Spatrick for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1559e5dd7070Spatrick NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1560e5dd7070Spatrick LookupOrdinaryName);
1561e5dd7070Spatrick if (!decl) {
1562e5dd7070Spatrick typeDecls.push_back(TypeOrClassDecl());
1563e5dd7070Spatrick continue;
1564e5dd7070Spatrick }
1565e5dd7070Spatrick
1566e5dd7070Spatrick if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1567e5dd7070Spatrick typeDecls.push_back(typeDecl);
1568e5dd7070Spatrick ++numTypeDeclsResolved;
1569e5dd7070Spatrick continue;
1570e5dd7070Spatrick }
1571e5dd7070Spatrick
1572e5dd7070Spatrick if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1573e5dd7070Spatrick typeDecls.push_back(objcClass);
1574e5dd7070Spatrick ++numTypeDeclsResolved;
1575e5dd7070Spatrick continue;
1576e5dd7070Spatrick }
1577e5dd7070Spatrick
1578e5dd7070Spatrick typeDecls.push_back(TypeOrClassDecl());
1579e5dd7070Spatrick }
1580e5dd7070Spatrick
1581e5dd7070Spatrick AttributeFactory attrFactory;
1582e5dd7070Spatrick
1583e5dd7070Spatrick // Local function that forms a reference to the given type or
1584e5dd7070Spatrick // Objective-C class declaration.
1585e5dd7070Spatrick auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1586e5dd7070Spatrick -> TypeResult {
1587e5dd7070Spatrick // Form declaration specifiers. They simply refer to the type.
1588e5dd7070Spatrick DeclSpec DS(attrFactory);
1589e5dd7070Spatrick const char* prevSpec; // unused
1590e5dd7070Spatrick unsigned diagID; // unused
1591e5dd7070Spatrick QualType type;
1592e5dd7070Spatrick if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1593e5dd7070Spatrick type = Context.getTypeDeclType(actualTypeDecl);
1594e5dd7070Spatrick else
1595e5dd7070Spatrick type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1596e5dd7070Spatrick TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1597e5dd7070Spatrick ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1598e5dd7070Spatrick DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1599e5dd7070Spatrick parsedType, Context.getPrintingPolicy());
1600e5dd7070Spatrick // Use the identifier location for the type source range.
1601e5dd7070Spatrick DS.SetRangeStart(loc);
1602e5dd7070Spatrick DS.SetRangeEnd(loc);
1603e5dd7070Spatrick
1604e5dd7070Spatrick // Form the declarator.
1605*12c85518Srobert Declarator D(DS, ParsedAttributesView::none(), DeclaratorContext::TypeName);
1606e5dd7070Spatrick
1607e5dd7070Spatrick // If we have a typedef of an Objective-C class type that is missing a '*',
1608e5dd7070Spatrick // add the '*'.
1609e5dd7070Spatrick if (type->getAs<ObjCInterfaceType>()) {
1610e5dd7070Spatrick SourceLocation starLoc = getLocForEndOfToken(loc);
1611e5dd7070Spatrick D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1612e5dd7070Spatrick SourceLocation(),
1613e5dd7070Spatrick SourceLocation(),
1614e5dd7070Spatrick SourceLocation(),
1615e5dd7070Spatrick SourceLocation(),
1616e5dd7070Spatrick SourceLocation()),
1617e5dd7070Spatrick starLoc);
1618e5dd7070Spatrick
1619e5dd7070Spatrick // Diagnose the missing '*'.
1620e5dd7070Spatrick Diag(loc, diag::err_objc_type_arg_missing_star)
1621e5dd7070Spatrick << type
1622e5dd7070Spatrick << FixItHint::CreateInsertion(starLoc, " *");
1623e5dd7070Spatrick }
1624e5dd7070Spatrick
1625e5dd7070Spatrick // Convert this to a type.
1626e5dd7070Spatrick return ActOnTypeName(S, D);
1627e5dd7070Spatrick };
1628e5dd7070Spatrick
1629e5dd7070Spatrick // Local function that updates the declaration specifiers with
1630e5dd7070Spatrick // type argument information.
1631e5dd7070Spatrick auto resolvedAsTypeDecls = [&] {
1632e5dd7070Spatrick // We did not resolve these as protocols.
1633e5dd7070Spatrick protocols.clear();
1634e5dd7070Spatrick
1635e5dd7070Spatrick assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1636e5dd7070Spatrick // Map type declarations to type arguments.
1637e5dd7070Spatrick for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1638e5dd7070Spatrick // Map type reference to a type.
1639e5dd7070Spatrick TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1640e5dd7070Spatrick if (!type.isUsable()) {
1641e5dd7070Spatrick typeArgs.clear();
1642e5dd7070Spatrick return;
1643e5dd7070Spatrick }
1644e5dd7070Spatrick
1645e5dd7070Spatrick typeArgs.push_back(type.get());
1646e5dd7070Spatrick }
1647e5dd7070Spatrick
1648e5dd7070Spatrick typeArgsLAngleLoc = lAngleLoc;
1649e5dd7070Spatrick typeArgsRAngleLoc = rAngleLoc;
1650e5dd7070Spatrick };
1651e5dd7070Spatrick
1652e5dd7070Spatrick // If all of the identifiers can be resolved as type names or
1653e5dd7070Spatrick // Objective-C class names, we have type arguments.
1654e5dd7070Spatrick if (numTypeDeclsResolved == identifiers.size())
1655e5dd7070Spatrick return resolvedAsTypeDecls();
1656e5dd7070Spatrick
1657e5dd7070Spatrick // Error recovery: some names weren't found, or we have a mix of
1658e5dd7070Spatrick // type and protocol names. Go resolve all of the unresolved names
1659e5dd7070Spatrick // and complain if we can't find a consistent answer.
1660e5dd7070Spatrick LookupNameKind lookupKind = LookupAnyName;
1661e5dd7070Spatrick for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1662e5dd7070Spatrick // If we already have a protocol or type. Check whether it is the
1663e5dd7070Spatrick // right thing.
1664e5dd7070Spatrick if (protocols[i] || typeDecls[i]) {
1665e5dd7070Spatrick // If we haven't figured out whether we want types or protocols
1666e5dd7070Spatrick // yet, try to figure it out from this name.
1667e5dd7070Spatrick if (lookupKind == LookupAnyName) {
1668e5dd7070Spatrick // If this name refers to both a protocol and a type (e.g., \c
1669e5dd7070Spatrick // NSObject), don't conclude anything yet.
1670e5dd7070Spatrick if (protocols[i] && typeDecls[i])
1671e5dd7070Spatrick continue;
1672e5dd7070Spatrick
1673e5dd7070Spatrick // Otherwise, let this name decide whether we'll be correcting
1674e5dd7070Spatrick // toward types or protocols.
1675e5dd7070Spatrick lookupKind = protocols[i] ? LookupObjCProtocolName
1676e5dd7070Spatrick : LookupOrdinaryName;
1677e5dd7070Spatrick continue;
1678e5dd7070Spatrick }
1679e5dd7070Spatrick
1680e5dd7070Spatrick // If we want protocols and we have a protocol, there's nothing
1681e5dd7070Spatrick // more to do.
1682e5dd7070Spatrick if (lookupKind == LookupObjCProtocolName && protocols[i])
1683e5dd7070Spatrick continue;
1684e5dd7070Spatrick
1685e5dd7070Spatrick // If we want types and we have a type declaration, there's
1686e5dd7070Spatrick // nothing more to do.
1687e5dd7070Spatrick if (lookupKind == LookupOrdinaryName && typeDecls[i])
1688e5dd7070Spatrick continue;
1689e5dd7070Spatrick
1690e5dd7070Spatrick // We have a conflict: some names refer to protocols and others
1691e5dd7070Spatrick // refer to types.
1692e5dd7070Spatrick DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1693e5dd7070Spatrick identifiers[i], identifierLocs[i],
1694e5dd7070Spatrick protocols[i] != nullptr);
1695e5dd7070Spatrick
1696e5dd7070Spatrick protocols.clear();
1697e5dd7070Spatrick typeArgs.clear();
1698e5dd7070Spatrick return;
1699e5dd7070Spatrick }
1700e5dd7070Spatrick
1701e5dd7070Spatrick // Perform typo correction on the name.
1702e5dd7070Spatrick ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1703e5dd7070Spatrick TypoCorrection corrected =
1704e5dd7070Spatrick CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
1705e5dd7070Spatrick lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
1706e5dd7070Spatrick if (corrected) {
1707e5dd7070Spatrick // Did we find a protocol?
1708e5dd7070Spatrick if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1709e5dd7070Spatrick diagnoseTypo(corrected,
1710e5dd7070Spatrick PDiag(diag::err_undeclared_protocol_suggest)
1711e5dd7070Spatrick << identifiers[i]);
1712e5dd7070Spatrick lookupKind = LookupObjCProtocolName;
1713e5dd7070Spatrick protocols[i] = proto;
1714e5dd7070Spatrick ++numProtocolsResolved;
1715e5dd7070Spatrick continue;
1716e5dd7070Spatrick }
1717e5dd7070Spatrick
1718e5dd7070Spatrick // Did we find a type?
1719e5dd7070Spatrick if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1720e5dd7070Spatrick diagnoseTypo(corrected,
1721e5dd7070Spatrick PDiag(diag::err_unknown_typename_suggest)
1722e5dd7070Spatrick << identifiers[i]);
1723e5dd7070Spatrick lookupKind = LookupOrdinaryName;
1724e5dd7070Spatrick typeDecls[i] = typeDecl;
1725e5dd7070Spatrick ++numTypeDeclsResolved;
1726e5dd7070Spatrick continue;
1727e5dd7070Spatrick }
1728e5dd7070Spatrick
1729e5dd7070Spatrick // Did we find an Objective-C class?
1730e5dd7070Spatrick if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1731e5dd7070Spatrick diagnoseTypo(corrected,
1732e5dd7070Spatrick PDiag(diag::err_unknown_type_or_class_name_suggest)
1733e5dd7070Spatrick << identifiers[i] << true);
1734e5dd7070Spatrick lookupKind = LookupOrdinaryName;
1735e5dd7070Spatrick typeDecls[i] = objcClass;
1736e5dd7070Spatrick ++numTypeDeclsResolved;
1737e5dd7070Spatrick continue;
1738e5dd7070Spatrick }
1739e5dd7070Spatrick }
1740e5dd7070Spatrick
1741e5dd7070Spatrick // We couldn't find anything.
1742e5dd7070Spatrick Diag(identifierLocs[i],
1743e5dd7070Spatrick (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1744e5dd7070Spatrick : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1745e5dd7070Spatrick : diag::err_unknown_typename))
1746e5dd7070Spatrick << identifiers[i];
1747e5dd7070Spatrick protocols.clear();
1748e5dd7070Spatrick typeArgs.clear();
1749e5dd7070Spatrick return;
1750e5dd7070Spatrick }
1751e5dd7070Spatrick
1752e5dd7070Spatrick // If all of the names were (corrected to) protocols, these were
1753e5dd7070Spatrick // protocol qualifiers.
1754e5dd7070Spatrick if (numProtocolsResolved == identifiers.size())
1755e5dd7070Spatrick return resolvedAsProtocols();
1756e5dd7070Spatrick
1757e5dd7070Spatrick // Otherwise, all of the names were (corrected to) types.
1758e5dd7070Spatrick assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1759e5dd7070Spatrick return resolvedAsTypeDecls();
1760e5dd7070Spatrick }
1761e5dd7070Spatrick
1762e5dd7070Spatrick /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1763e5dd7070Spatrick /// a class method in its extension.
1764e5dd7070Spatrick ///
DiagnoseClassExtensionDupMethods(ObjCCategoryDecl * CAT,ObjCInterfaceDecl * ID)1765e5dd7070Spatrick void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1766e5dd7070Spatrick ObjCInterfaceDecl *ID) {
1767e5dd7070Spatrick if (!ID)
1768e5dd7070Spatrick return; // Possibly due to previous error
1769e5dd7070Spatrick
1770e5dd7070Spatrick llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1771e5dd7070Spatrick for (auto *MD : ID->methods())
1772e5dd7070Spatrick MethodMap[MD->getSelector()] = MD;
1773e5dd7070Spatrick
1774e5dd7070Spatrick if (MethodMap.empty())
1775e5dd7070Spatrick return;
1776e5dd7070Spatrick for (const auto *Method : CAT->methods()) {
1777e5dd7070Spatrick const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1778e5dd7070Spatrick if (PrevMethod &&
1779e5dd7070Spatrick (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1780e5dd7070Spatrick !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1781e5dd7070Spatrick Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1782e5dd7070Spatrick << Method->getDeclName();
1783e5dd7070Spatrick Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1784e5dd7070Spatrick }
1785e5dd7070Spatrick }
1786e5dd7070Spatrick }
1787e5dd7070Spatrick
1788e5dd7070Spatrick /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1789e5dd7070Spatrick Sema::DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,ArrayRef<IdentifierLocPair> IdentList,const ParsedAttributesView & attrList)1790e5dd7070Spatrick Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
1791e5dd7070Spatrick ArrayRef<IdentifierLocPair> IdentList,
1792e5dd7070Spatrick const ParsedAttributesView &attrList) {
1793e5dd7070Spatrick SmallVector<Decl *, 8> DeclsInGroup;
1794e5dd7070Spatrick for (const IdentifierLocPair &IdentPair : IdentList) {
1795e5dd7070Spatrick IdentifierInfo *Ident = IdentPair.first;
1796e5dd7070Spatrick ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1797e5dd7070Spatrick forRedeclarationInCurContext());
1798e5dd7070Spatrick ObjCProtocolDecl *PDecl
1799e5dd7070Spatrick = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1800e5dd7070Spatrick IdentPair.second, AtProtocolLoc,
1801e5dd7070Spatrick PrevDecl);
1802e5dd7070Spatrick
1803e5dd7070Spatrick PushOnScopeChains(PDecl, TUScope);
1804e5dd7070Spatrick CheckObjCDeclScope(PDecl);
1805e5dd7070Spatrick
1806e5dd7070Spatrick ProcessDeclAttributeList(TUScope, PDecl, attrList);
1807e5dd7070Spatrick AddPragmaAttributes(TUScope, PDecl);
1808e5dd7070Spatrick
1809e5dd7070Spatrick if (PrevDecl)
1810e5dd7070Spatrick mergeDeclAttributes(PDecl, PrevDecl);
1811e5dd7070Spatrick
1812e5dd7070Spatrick DeclsInGroup.push_back(PDecl);
1813e5dd7070Spatrick }
1814e5dd7070Spatrick
1815e5dd7070Spatrick return BuildDeclaratorGroup(DeclsInGroup);
1816e5dd7070Spatrick }
1817e5dd7070Spatrick
ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,ObjCTypeParamList * typeParamList,IdentifierInfo * CategoryName,SourceLocation CategoryLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc,const ParsedAttributesView & AttrList)1818*12c85518Srobert ObjCCategoryDecl *Sema::ActOnStartCategoryInterface(
1819e5dd7070Spatrick SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1820e5dd7070Spatrick SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1821e5dd7070Spatrick IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1822e5dd7070Spatrick Decl *const *ProtoRefs, unsigned NumProtoRefs,
1823e5dd7070Spatrick const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1824e5dd7070Spatrick const ParsedAttributesView &AttrList) {
1825e5dd7070Spatrick ObjCCategoryDecl *CDecl;
1826e5dd7070Spatrick ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1827e5dd7070Spatrick
1828e5dd7070Spatrick /// Check that class of this category is already completely declared.
1829e5dd7070Spatrick
1830e5dd7070Spatrick if (!IDecl
1831e5dd7070Spatrick || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1832e5dd7070Spatrick diag::err_category_forward_interface,
1833e5dd7070Spatrick CategoryName == nullptr)) {
1834e5dd7070Spatrick // Create an invalid ObjCCategoryDecl to serve as context for
1835e5dd7070Spatrick // the enclosing method declarations. We mark the decl invalid
1836e5dd7070Spatrick // to make it clear that this isn't a valid AST.
1837e5dd7070Spatrick CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1838e5dd7070Spatrick ClassLoc, CategoryLoc, CategoryName,
1839e5dd7070Spatrick IDecl, typeParamList);
1840e5dd7070Spatrick CDecl->setInvalidDecl();
1841e5dd7070Spatrick CurContext->addDecl(CDecl);
1842e5dd7070Spatrick
1843e5dd7070Spatrick if (!IDecl)
1844e5dd7070Spatrick Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1845*12c85518Srobert ActOnObjCContainerStartDefinition(CDecl);
1846*12c85518Srobert return CDecl;
1847e5dd7070Spatrick }
1848e5dd7070Spatrick
1849e5dd7070Spatrick if (!CategoryName && IDecl->getImplementation()) {
1850e5dd7070Spatrick Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1851e5dd7070Spatrick Diag(IDecl->getImplementation()->getLocation(),
1852e5dd7070Spatrick diag::note_implementation_declared);
1853e5dd7070Spatrick }
1854e5dd7070Spatrick
1855e5dd7070Spatrick if (CategoryName) {
1856e5dd7070Spatrick /// Check for duplicate interface declaration for this category
1857e5dd7070Spatrick if (ObjCCategoryDecl *Previous
1858e5dd7070Spatrick = IDecl->FindCategoryDeclaration(CategoryName)) {
1859e5dd7070Spatrick // Class extensions can be declared multiple times, categories cannot.
1860e5dd7070Spatrick Diag(CategoryLoc, diag::warn_dup_category_def)
1861e5dd7070Spatrick << ClassName << CategoryName;
1862e5dd7070Spatrick Diag(Previous->getLocation(), diag::note_previous_definition);
1863e5dd7070Spatrick }
1864e5dd7070Spatrick }
1865e5dd7070Spatrick
1866e5dd7070Spatrick // If we have a type parameter list, check it.
1867e5dd7070Spatrick if (typeParamList) {
1868e5dd7070Spatrick if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1869e5dd7070Spatrick if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1870e5dd7070Spatrick CategoryName
1871e5dd7070Spatrick ? TypeParamListContext::Category
1872e5dd7070Spatrick : TypeParamListContext::Extension))
1873e5dd7070Spatrick typeParamList = nullptr;
1874e5dd7070Spatrick } else {
1875e5dd7070Spatrick Diag(typeParamList->getLAngleLoc(),
1876e5dd7070Spatrick diag::err_objc_parameterized_category_nonclass)
1877e5dd7070Spatrick << (CategoryName != nullptr)
1878e5dd7070Spatrick << ClassName
1879e5dd7070Spatrick << typeParamList->getSourceRange();
1880e5dd7070Spatrick
1881e5dd7070Spatrick typeParamList = nullptr;
1882e5dd7070Spatrick }
1883e5dd7070Spatrick }
1884e5dd7070Spatrick
1885e5dd7070Spatrick CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1886e5dd7070Spatrick ClassLoc, CategoryLoc, CategoryName, IDecl,
1887e5dd7070Spatrick typeParamList);
1888e5dd7070Spatrick // FIXME: PushOnScopeChains?
1889e5dd7070Spatrick CurContext->addDecl(CDecl);
1890e5dd7070Spatrick
1891e5dd7070Spatrick // Process the attributes before looking at protocols to ensure that the
1892e5dd7070Spatrick // availability attribute is attached to the category to provide availability
1893e5dd7070Spatrick // checking for protocol uses.
1894e5dd7070Spatrick ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1895e5dd7070Spatrick AddPragmaAttributes(TUScope, CDecl);
1896e5dd7070Spatrick
1897e5dd7070Spatrick if (NumProtoRefs) {
1898e5dd7070Spatrick diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1899e5dd7070Spatrick NumProtoRefs, ProtoLocs);
1900e5dd7070Spatrick CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1901e5dd7070Spatrick ProtoLocs, Context);
1902e5dd7070Spatrick // Protocols in the class extension belong to the class.
1903e5dd7070Spatrick if (CDecl->IsClassExtension())
1904e5dd7070Spatrick IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1905e5dd7070Spatrick NumProtoRefs, Context);
1906e5dd7070Spatrick }
1907e5dd7070Spatrick
1908e5dd7070Spatrick CheckObjCDeclScope(CDecl);
1909*12c85518Srobert ActOnObjCContainerStartDefinition(CDecl);
1910*12c85518Srobert return CDecl;
1911e5dd7070Spatrick }
1912e5dd7070Spatrick
1913e5dd7070Spatrick /// ActOnStartCategoryImplementation - Perform semantic checks on the
1914e5dd7070Spatrick /// category implementation declaration and build an ObjCCategoryImplDecl
1915e5dd7070Spatrick /// object.
ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * CatName,SourceLocation CatLoc,const ParsedAttributesView & Attrs)1916*12c85518Srobert ObjCCategoryImplDecl *Sema::ActOnStartCategoryImplementation(
1917*12c85518Srobert SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
1918*12c85518Srobert SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
1919e5dd7070Spatrick const ParsedAttributesView &Attrs) {
1920e5dd7070Spatrick ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1921e5dd7070Spatrick ObjCCategoryDecl *CatIDecl = nullptr;
1922e5dd7070Spatrick if (IDecl && IDecl->hasDefinition()) {
1923e5dd7070Spatrick CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1924e5dd7070Spatrick if (!CatIDecl) {
1925e5dd7070Spatrick // Category @implementation with no corresponding @interface.
1926e5dd7070Spatrick // Create and install one.
1927e5dd7070Spatrick CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1928e5dd7070Spatrick ClassLoc, CatLoc,
1929e5dd7070Spatrick CatName, IDecl,
1930e5dd7070Spatrick /*typeParamList=*/nullptr);
1931e5dd7070Spatrick CatIDecl->setImplicit();
1932e5dd7070Spatrick }
1933e5dd7070Spatrick }
1934e5dd7070Spatrick
1935e5dd7070Spatrick ObjCCategoryImplDecl *CDecl =
1936e5dd7070Spatrick ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
1937e5dd7070Spatrick ClassLoc, AtCatImplLoc, CatLoc);
1938e5dd7070Spatrick /// Check that class of this category is already completely declared.
1939e5dd7070Spatrick if (!IDecl) {
1940e5dd7070Spatrick Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1941e5dd7070Spatrick CDecl->setInvalidDecl();
1942e5dd7070Spatrick } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1943e5dd7070Spatrick diag::err_undef_interface)) {
1944e5dd7070Spatrick CDecl->setInvalidDecl();
1945e5dd7070Spatrick }
1946e5dd7070Spatrick
1947e5dd7070Spatrick ProcessDeclAttributeList(TUScope, CDecl, Attrs);
1948e5dd7070Spatrick AddPragmaAttributes(TUScope, CDecl);
1949e5dd7070Spatrick
1950e5dd7070Spatrick // FIXME: PushOnScopeChains?
1951e5dd7070Spatrick CurContext->addDecl(CDecl);
1952e5dd7070Spatrick
1953e5dd7070Spatrick // If the interface has the objc_runtime_visible attribute, we
1954e5dd7070Spatrick // cannot implement a category for it.
1955e5dd7070Spatrick if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1956e5dd7070Spatrick Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1957e5dd7070Spatrick << IDecl->getDeclName();
1958e5dd7070Spatrick }
1959e5dd7070Spatrick
1960e5dd7070Spatrick /// Check that CatName, category name, is not used in another implementation.
1961e5dd7070Spatrick if (CatIDecl) {
1962e5dd7070Spatrick if (CatIDecl->getImplementation()) {
1963e5dd7070Spatrick Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1964e5dd7070Spatrick << CatName;
1965e5dd7070Spatrick Diag(CatIDecl->getImplementation()->getLocation(),
1966e5dd7070Spatrick diag::note_previous_definition);
1967e5dd7070Spatrick CDecl->setInvalidDecl();
1968e5dd7070Spatrick } else {
1969e5dd7070Spatrick CatIDecl->setImplementation(CDecl);
1970e5dd7070Spatrick // Warn on implementating category of deprecated class under
1971e5dd7070Spatrick // -Wdeprecated-implementations flag.
1972e5dd7070Spatrick DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1973e5dd7070Spatrick CDecl->getLocation());
1974e5dd7070Spatrick }
1975e5dd7070Spatrick }
1976e5dd7070Spatrick
1977e5dd7070Spatrick CheckObjCDeclScope(CDecl);
1978*12c85518Srobert ActOnObjCContainerStartDefinition(CDecl);
1979*12c85518Srobert return CDecl;
1980e5dd7070Spatrick }
1981e5dd7070Spatrick
ActOnStartClassImplementation(SourceLocation AtClassImplLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * SuperClassname,SourceLocation SuperClassLoc,const ParsedAttributesView & Attrs)1982*12c85518Srobert ObjCImplementationDecl *Sema::ActOnStartClassImplementation(
1983*12c85518Srobert SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
1984*12c85518Srobert SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
1985*12c85518Srobert SourceLocation SuperClassLoc, const ParsedAttributesView &Attrs) {
1986e5dd7070Spatrick ObjCInterfaceDecl *IDecl = nullptr;
1987e5dd7070Spatrick // Check for another declaration kind with the same name.
1988e5dd7070Spatrick NamedDecl *PrevDecl
1989e5dd7070Spatrick = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1990e5dd7070Spatrick forRedeclarationInCurContext());
1991e5dd7070Spatrick if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1992e5dd7070Spatrick Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1993e5dd7070Spatrick Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1994e5dd7070Spatrick } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1995e5dd7070Spatrick // FIXME: This will produce an error if the definition of the interface has
1996e5dd7070Spatrick // been imported from a module but is not visible.
1997e5dd7070Spatrick RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1998e5dd7070Spatrick diag::warn_undef_interface);
1999e5dd7070Spatrick } else {
2000e5dd7070Spatrick // We did not find anything with the name ClassName; try to correct for
2001e5dd7070Spatrick // typos in the class name.
2002e5dd7070Spatrick ObjCInterfaceValidatorCCC CCC{};
2003e5dd7070Spatrick TypoCorrection Corrected =
2004e5dd7070Spatrick CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
2005e5dd7070Spatrick LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
2006e5dd7070Spatrick if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2007e5dd7070Spatrick // Suggest the (potentially) correct interface name. Don't provide a
2008e5dd7070Spatrick // code-modification hint or use the typo name for recovery, because
2009e5dd7070Spatrick // this is just a warning. The program may actually be correct.
2010e5dd7070Spatrick diagnoseTypo(Corrected,
2011e5dd7070Spatrick PDiag(diag::warn_undef_interface_suggest) << ClassName,
2012e5dd7070Spatrick /*ErrorRecovery*/false);
2013e5dd7070Spatrick } else {
2014e5dd7070Spatrick Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
2015e5dd7070Spatrick }
2016e5dd7070Spatrick }
2017e5dd7070Spatrick
2018e5dd7070Spatrick // Check that super class name is valid class name
2019e5dd7070Spatrick ObjCInterfaceDecl *SDecl = nullptr;
2020e5dd7070Spatrick if (SuperClassname) {
2021e5dd7070Spatrick // Check if a different kind of symbol declared in this scope.
2022e5dd7070Spatrick PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
2023e5dd7070Spatrick LookupOrdinaryName);
2024e5dd7070Spatrick if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2025e5dd7070Spatrick Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2026e5dd7070Spatrick << SuperClassname;
2027e5dd7070Spatrick Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2028e5dd7070Spatrick } else {
2029e5dd7070Spatrick SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2030e5dd7070Spatrick if (SDecl && !SDecl->hasDefinition())
2031e5dd7070Spatrick SDecl = nullptr;
2032e5dd7070Spatrick if (!SDecl)
2033e5dd7070Spatrick Diag(SuperClassLoc, diag::err_undef_superclass)
2034e5dd7070Spatrick << SuperClassname << ClassName;
2035e5dd7070Spatrick else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2036e5dd7070Spatrick // This implementation and its interface do not have the same
2037e5dd7070Spatrick // super class.
2038e5dd7070Spatrick Diag(SuperClassLoc, diag::err_conflicting_super_class)
2039e5dd7070Spatrick << SDecl->getDeclName();
2040e5dd7070Spatrick Diag(SDecl->getLocation(), diag::note_previous_definition);
2041e5dd7070Spatrick }
2042e5dd7070Spatrick }
2043e5dd7070Spatrick }
2044e5dd7070Spatrick
2045e5dd7070Spatrick if (!IDecl) {
2046e5dd7070Spatrick // Legacy case of @implementation with no corresponding @interface.
2047e5dd7070Spatrick // Build, chain & install the interface decl into the identifier.
2048e5dd7070Spatrick
2049e5dd7070Spatrick // FIXME: Do we support attributes on the @implementation? If so we should
2050e5dd7070Spatrick // copy them over.
2051e5dd7070Spatrick IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
2052e5dd7070Spatrick ClassName, /*typeParamList=*/nullptr,
2053e5dd7070Spatrick /*PrevDecl=*/nullptr, ClassLoc,
2054e5dd7070Spatrick true);
2055e5dd7070Spatrick AddPragmaAttributes(TUScope, IDecl);
2056e5dd7070Spatrick IDecl->startDefinition();
2057e5dd7070Spatrick if (SDecl) {
2058e5dd7070Spatrick IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2059e5dd7070Spatrick Context.getObjCInterfaceType(SDecl),
2060e5dd7070Spatrick SuperClassLoc));
2061e5dd7070Spatrick IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2062e5dd7070Spatrick } else {
2063e5dd7070Spatrick IDecl->setEndOfDefinitionLoc(ClassLoc);
2064e5dd7070Spatrick }
2065e5dd7070Spatrick
2066e5dd7070Spatrick PushOnScopeChains(IDecl, TUScope);
2067e5dd7070Spatrick } else {
2068e5dd7070Spatrick // Mark the interface as being completed, even if it was just as
2069e5dd7070Spatrick // @class ....;
2070e5dd7070Spatrick // declaration; the user cannot reopen it.
2071e5dd7070Spatrick if (!IDecl->hasDefinition())
2072e5dd7070Spatrick IDecl->startDefinition();
2073e5dd7070Spatrick }
2074e5dd7070Spatrick
2075e5dd7070Spatrick ObjCImplementationDecl* IMPDecl =
2076e5dd7070Spatrick ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
2077e5dd7070Spatrick ClassLoc, AtClassImplLoc, SuperClassLoc);
2078e5dd7070Spatrick
2079e5dd7070Spatrick ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
2080e5dd7070Spatrick AddPragmaAttributes(TUScope, IMPDecl);
2081e5dd7070Spatrick
2082*12c85518Srobert if (CheckObjCDeclScope(IMPDecl)) {
2083*12c85518Srobert ActOnObjCContainerStartDefinition(IMPDecl);
2084*12c85518Srobert return IMPDecl;
2085*12c85518Srobert }
2086e5dd7070Spatrick
2087e5dd7070Spatrick // Check that there is no duplicate implementation of this class.
2088e5dd7070Spatrick if (IDecl->getImplementation()) {
2089e5dd7070Spatrick // FIXME: Don't leak everything!
2090e5dd7070Spatrick Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2091e5dd7070Spatrick Diag(IDecl->getImplementation()->getLocation(),
2092e5dd7070Spatrick diag::note_previous_definition);
2093e5dd7070Spatrick IMPDecl->setInvalidDecl();
2094e5dd7070Spatrick } else { // add it to the list.
2095e5dd7070Spatrick IDecl->setImplementation(IMPDecl);
2096e5dd7070Spatrick PushOnScopeChains(IMPDecl, TUScope);
2097e5dd7070Spatrick // Warn on implementating deprecated class under
2098e5dd7070Spatrick // -Wdeprecated-implementations flag.
2099e5dd7070Spatrick DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
2100e5dd7070Spatrick }
2101e5dd7070Spatrick
2102e5dd7070Spatrick // If the superclass has the objc_runtime_visible attribute, we
2103e5dd7070Spatrick // cannot implement a subclass of it.
2104e5dd7070Spatrick if (IDecl->getSuperClass() &&
2105e5dd7070Spatrick IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2106e5dd7070Spatrick Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2107e5dd7070Spatrick << IDecl->getDeclName()
2108e5dd7070Spatrick << IDecl->getSuperClass()->getDeclName();
2109e5dd7070Spatrick }
2110e5dd7070Spatrick
2111*12c85518Srobert ActOnObjCContainerStartDefinition(IMPDecl);
2112*12c85518Srobert return IMPDecl;
2113e5dd7070Spatrick }
2114e5dd7070Spatrick
2115e5dd7070Spatrick Sema::DeclGroupPtrTy
ActOnFinishObjCImplementation(Decl * ObjCImpDecl,ArrayRef<Decl * > Decls)2116e5dd7070Spatrick Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2117e5dd7070Spatrick SmallVector<Decl *, 64> DeclsInGroup;
2118e5dd7070Spatrick DeclsInGroup.reserve(Decls.size() + 1);
2119e5dd7070Spatrick
2120e5dd7070Spatrick for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2121e5dd7070Spatrick Decl *Dcl = Decls[i];
2122e5dd7070Spatrick if (!Dcl)
2123e5dd7070Spatrick continue;
2124e5dd7070Spatrick if (Dcl->getDeclContext()->isFileContext())
2125e5dd7070Spatrick Dcl->setTopLevelDeclInObjCContainer();
2126e5dd7070Spatrick DeclsInGroup.push_back(Dcl);
2127e5dd7070Spatrick }
2128e5dd7070Spatrick
2129e5dd7070Spatrick DeclsInGroup.push_back(ObjCImpDecl);
2130e5dd7070Spatrick
2131e5dd7070Spatrick return BuildDeclaratorGroup(DeclsInGroup);
2132e5dd7070Spatrick }
2133e5dd7070Spatrick
CheckImplementationIvars(ObjCImplementationDecl * ImpDecl,ObjCIvarDecl ** ivars,unsigned numIvars,SourceLocation RBrace)2134e5dd7070Spatrick void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2135e5dd7070Spatrick ObjCIvarDecl **ivars, unsigned numIvars,
2136e5dd7070Spatrick SourceLocation RBrace) {
2137e5dd7070Spatrick assert(ImpDecl && "missing implementation decl");
2138e5dd7070Spatrick ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2139e5dd7070Spatrick if (!IDecl)
2140e5dd7070Spatrick return;
2141e5dd7070Spatrick /// Check case of non-existing \@interface decl.
2142e5dd7070Spatrick /// (legacy objective-c \@implementation decl without an \@interface decl).
2143e5dd7070Spatrick /// Add implementations's ivar to the synthesize class's ivar list.
2144e5dd7070Spatrick if (IDecl->isImplicitInterfaceDecl()) {
2145e5dd7070Spatrick IDecl->setEndOfDefinitionLoc(RBrace);
2146e5dd7070Spatrick // Add ivar's to class's DeclContext.
2147e5dd7070Spatrick for (unsigned i = 0, e = numIvars; i != e; ++i) {
2148e5dd7070Spatrick ivars[i]->setLexicalDeclContext(ImpDecl);
2149a9ac8606Spatrick // In a 'fragile' runtime the ivar was added to the implicit
2150a9ac8606Spatrick // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is
2151a9ac8606Spatrick // only in the ObjCImplementationDecl. In the non-fragile case the ivar
2152a9ac8606Spatrick // therefore also needs to be propagated to the ObjCInterfaceDecl.
2153a9ac8606Spatrick if (!LangOpts.ObjCRuntime.isFragile())
2154e5dd7070Spatrick IDecl->makeDeclVisibleInContext(ivars[i]);
2155e5dd7070Spatrick ImpDecl->addDecl(ivars[i]);
2156e5dd7070Spatrick }
2157e5dd7070Spatrick
2158e5dd7070Spatrick return;
2159e5dd7070Spatrick }
2160e5dd7070Spatrick // If implementation has empty ivar list, just return.
2161e5dd7070Spatrick if (numIvars == 0)
2162e5dd7070Spatrick return;
2163e5dd7070Spatrick
2164e5dd7070Spatrick assert(ivars && "missing @implementation ivars");
2165e5dd7070Spatrick if (LangOpts.ObjCRuntime.isNonFragile()) {
2166e5dd7070Spatrick if (ImpDecl->getSuperClass())
2167e5dd7070Spatrick Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2168e5dd7070Spatrick for (unsigned i = 0; i < numIvars; i++) {
2169e5dd7070Spatrick ObjCIvarDecl* ImplIvar = ivars[i];
2170e5dd7070Spatrick if (const ObjCIvarDecl *ClsIvar =
2171e5dd7070Spatrick IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2172e5dd7070Spatrick Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2173e5dd7070Spatrick Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2174e5dd7070Spatrick continue;
2175e5dd7070Spatrick }
2176e5dd7070Spatrick // Check class extensions (unnamed categories) for duplicate ivars.
2177e5dd7070Spatrick for (const auto *CDecl : IDecl->visible_extensions()) {
2178e5dd7070Spatrick if (const ObjCIvarDecl *ClsExtIvar =
2179e5dd7070Spatrick CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2180e5dd7070Spatrick Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2181e5dd7070Spatrick Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2182e5dd7070Spatrick continue;
2183e5dd7070Spatrick }
2184e5dd7070Spatrick }
2185e5dd7070Spatrick // Instance ivar to Implementation's DeclContext.
2186e5dd7070Spatrick ImplIvar->setLexicalDeclContext(ImpDecl);
2187e5dd7070Spatrick IDecl->makeDeclVisibleInContext(ImplIvar);
2188e5dd7070Spatrick ImpDecl->addDecl(ImplIvar);
2189e5dd7070Spatrick }
2190e5dd7070Spatrick return;
2191e5dd7070Spatrick }
2192e5dd7070Spatrick // Check interface's Ivar list against those in the implementation.
2193e5dd7070Spatrick // names and types must match.
2194e5dd7070Spatrick //
2195e5dd7070Spatrick unsigned j = 0;
2196e5dd7070Spatrick ObjCInterfaceDecl::ivar_iterator
2197e5dd7070Spatrick IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2198e5dd7070Spatrick for (; numIvars > 0 && IVI != IVE; ++IVI) {
2199e5dd7070Spatrick ObjCIvarDecl* ImplIvar = ivars[j++];
2200e5dd7070Spatrick ObjCIvarDecl* ClsIvar = *IVI;
2201e5dd7070Spatrick assert (ImplIvar && "missing implementation ivar");
2202e5dd7070Spatrick assert (ClsIvar && "missing class ivar");
2203e5dd7070Spatrick
2204e5dd7070Spatrick // First, make sure the types match.
2205e5dd7070Spatrick if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2206e5dd7070Spatrick Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2207e5dd7070Spatrick << ImplIvar->getIdentifier()
2208e5dd7070Spatrick << ImplIvar->getType() << ClsIvar->getType();
2209e5dd7070Spatrick Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2210e5dd7070Spatrick } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2211e5dd7070Spatrick ImplIvar->getBitWidthValue(Context) !=
2212e5dd7070Spatrick ClsIvar->getBitWidthValue(Context)) {
2213e5dd7070Spatrick Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2214e5dd7070Spatrick diag::err_conflicting_ivar_bitwidth)
2215e5dd7070Spatrick << ImplIvar->getIdentifier();
2216e5dd7070Spatrick Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2217e5dd7070Spatrick diag::note_previous_definition);
2218e5dd7070Spatrick }
2219e5dd7070Spatrick // Make sure the names are identical.
2220e5dd7070Spatrick if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2221e5dd7070Spatrick Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2222e5dd7070Spatrick << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2223e5dd7070Spatrick Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2224e5dd7070Spatrick }
2225e5dd7070Spatrick --numIvars;
2226e5dd7070Spatrick }
2227e5dd7070Spatrick
2228e5dd7070Spatrick if (numIvars > 0)
2229e5dd7070Spatrick Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2230e5dd7070Spatrick else if (IVI != IVE)
2231e5dd7070Spatrick Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2232e5dd7070Spatrick }
2233e5dd7070Spatrick
WarnUndefinedMethod(Sema & S,ObjCImplDecl * Impl,ObjCMethodDecl * method,bool & IncompleteImpl,unsigned DiagID,NamedDecl * NeededFor=nullptr)2234*12c85518Srobert static void WarnUndefinedMethod(Sema &S, ObjCImplDecl *Impl,
2235*12c85518Srobert ObjCMethodDecl *method, bool &IncompleteImpl,
2236e5dd7070Spatrick unsigned DiagID,
2237e5dd7070Spatrick NamedDecl *NeededFor = nullptr) {
2238e5dd7070Spatrick // No point warning no definition of method which is 'unavailable'.
2239e5dd7070Spatrick if (method->getAvailability() == AR_Unavailable)
2240e5dd7070Spatrick return;
2241e5dd7070Spatrick
2242e5dd7070Spatrick // FIXME: For now ignore 'IncompleteImpl'.
2243e5dd7070Spatrick // Previously we grouped all unimplemented methods under a single
2244e5dd7070Spatrick // warning, but some users strongly voiced that they would prefer
2245e5dd7070Spatrick // separate warnings. We will give that approach a try, as that
2246e5dd7070Spatrick // matches what we do with protocols.
2247e5dd7070Spatrick {
2248*12c85518Srobert const Sema::SemaDiagnosticBuilder &B = S.Diag(Impl->getLocation(), DiagID);
2249e5dd7070Spatrick B << method;
2250e5dd7070Spatrick if (NeededFor)
2251e5dd7070Spatrick B << NeededFor;
2252*12c85518Srobert
2253*12c85518Srobert // Add an empty definition at the end of the @implementation.
2254*12c85518Srobert std::string FixItStr;
2255*12c85518Srobert llvm::raw_string_ostream Out(FixItStr);
2256*12c85518Srobert method->print(Out, Impl->getASTContext().getPrintingPolicy());
2257*12c85518Srobert Out << " {\n}\n\n";
2258*12c85518Srobert
2259*12c85518Srobert SourceLocation Loc = Impl->getAtEndRange().getBegin();
2260*12c85518Srobert B << FixItHint::CreateInsertion(Loc, FixItStr);
2261e5dd7070Spatrick }
2262e5dd7070Spatrick
2263e5dd7070Spatrick // Issue a note to the original declaration.
2264e5dd7070Spatrick SourceLocation MethodLoc = method->getBeginLoc();
2265e5dd7070Spatrick if (MethodLoc.isValid())
2266e5dd7070Spatrick S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2267e5dd7070Spatrick }
2268e5dd7070Spatrick
2269e5dd7070Spatrick /// Determines if type B can be substituted for type A. Returns true if we can
2270e5dd7070Spatrick /// guarantee that anything that the user will do to an object of type A can
2271e5dd7070Spatrick /// also be done to an object of type B. This is trivially true if the two
2272e5dd7070Spatrick /// types are the same, or if B is a subclass of A. It becomes more complex
2273e5dd7070Spatrick /// in cases where protocols are involved.
2274e5dd7070Spatrick ///
2275e5dd7070Spatrick /// Object types in Objective-C describe the minimum requirements for an
2276e5dd7070Spatrick /// object, rather than providing a complete description of a type. For
2277e5dd7070Spatrick /// example, if A is a subclass of B, then B* may refer to an instance of A.
2278e5dd7070Spatrick /// The principle of substitutability means that we may use an instance of A
2279e5dd7070Spatrick /// anywhere that we may use an instance of B - it will implement all of the
2280e5dd7070Spatrick /// ivars of B and all of the methods of B.
2281e5dd7070Spatrick ///
2282e5dd7070Spatrick /// This substitutability is important when type checking methods, because
2283e5dd7070Spatrick /// the implementation may have stricter type definitions than the interface.
2284e5dd7070Spatrick /// The interface specifies minimum requirements, but the implementation may
2285e5dd7070Spatrick /// have more accurate ones. For example, a method may privately accept
2286e5dd7070Spatrick /// instances of B, but only publish that it accepts instances of A. Any
2287e5dd7070Spatrick /// object passed to it will be type checked against B, and so will implicitly
2288e5dd7070Spatrick /// by a valid A*. Similarly, a method may return a subclass of the class that
2289e5dd7070Spatrick /// it is declared as returning.
2290e5dd7070Spatrick ///
2291e5dd7070Spatrick /// This is most important when considering subclassing. A method in a
2292e5dd7070Spatrick /// subclass must accept any object as an argument that its superclass's
2293e5dd7070Spatrick /// implementation accepts. It may, however, accept a more general type
2294e5dd7070Spatrick /// without breaking substitutability (i.e. you can still use the subclass
2295e5dd7070Spatrick /// anywhere that you can use the superclass, but not vice versa). The
2296e5dd7070Spatrick /// converse requirement applies to return types: the return type for a
2297e5dd7070Spatrick /// subclass method must be a valid object of the kind that the superclass
2298e5dd7070Spatrick /// advertises, but it may be specified more accurately. This avoids the need
2299e5dd7070Spatrick /// for explicit down-casting by callers.
2300e5dd7070Spatrick ///
2301e5dd7070Spatrick /// Note: This is a stricter requirement than for assignment.
isObjCTypeSubstitutable(ASTContext & Context,const ObjCObjectPointerType * A,const ObjCObjectPointerType * B,bool rejectId)2302e5dd7070Spatrick static bool isObjCTypeSubstitutable(ASTContext &Context,
2303e5dd7070Spatrick const ObjCObjectPointerType *A,
2304e5dd7070Spatrick const ObjCObjectPointerType *B,
2305e5dd7070Spatrick bool rejectId) {
2306e5dd7070Spatrick // Reject a protocol-unqualified id.
2307e5dd7070Spatrick if (rejectId && B->isObjCIdType()) return false;
2308e5dd7070Spatrick
2309e5dd7070Spatrick // If B is a qualified id, then A must also be a qualified id and it must
2310e5dd7070Spatrick // implement all of the protocols in B. It may not be a qualified class.
2311e5dd7070Spatrick // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2312e5dd7070Spatrick // stricter definition so it is not substitutable for id<A>.
2313e5dd7070Spatrick if (B->isObjCQualifiedIdType()) {
2314e5dd7070Spatrick return A->isObjCQualifiedIdType() &&
2315e5dd7070Spatrick Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2316e5dd7070Spatrick }
2317e5dd7070Spatrick
2318e5dd7070Spatrick /*
2319e5dd7070Spatrick // id is a special type that bypasses type checking completely. We want a
2320e5dd7070Spatrick // warning when it is used in one place but not another.
2321e5dd7070Spatrick if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2322e5dd7070Spatrick
2323e5dd7070Spatrick
2324e5dd7070Spatrick // If B is a qualified id, then A must also be a qualified id (which it isn't
2325e5dd7070Spatrick // if we've got this far)
2326e5dd7070Spatrick if (B->isObjCQualifiedIdType()) return false;
2327e5dd7070Spatrick */
2328e5dd7070Spatrick
2329e5dd7070Spatrick // Now we know that A and B are (potentially-qualified) class types. The
2330e5dd7070Spatrick // normal rules for assignment apply.
2331e5dd7070Spatrick return Context.canAssignObjCInterfaces(A, B);
2332e5dd7070Spatrick }
2333e5dd7070Spatrick
getTypeRange(TypeSourceInfo * TSI)2334e5dd7070Spatrick static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2335e5dd7070Spatrick return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2336e5dd7070Spatrick }
2337e5dd7070Spatrick
2338e5dd7070Spatrick /// Determine whether two set of Objective-C declaration qualifiers conflict.
objcModifiersConflict(Decl::ObjCDeclQualifier x,Decl::ObjCDeclQualifier y)2339e5dd7070Spatrick static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2340e5dd7070Spatrick Decl::ObjCDeclQualifier y) {
2341e5dd7070Spatrick return (x & ~Decl::OBJC_TQ_CSNullability) !=
2342e5dd7070Spatrick (y & ~Decl::OBJC_TQ_CSNullability);
2343e5dd7070Spatrick }
2344e5dd7070Spatrick
CheckMethodOverrideReturn(Sema & S,ObjCMethodDecl * MethodImpl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl,bool IsOverridingMode,bool Warn)2345e5dd7070Spatrick static bool CheckMethodOverrideReturn(Sema &S,
2346e5dd7070Spatrick ObjCMethodDecl *MethodImpl,
2347e5dd7070Spatrick ObjCMethodDecl *MethodDecl,
2348e5dd7070Spatrick bool IsProtocolMethodDecl,
2349e5dd7070Spatrick bool IsOverridingMode,
2350e5dd7070Spatrick bool Warn) {
2351e5dd7070Spatrick if (IsProtocolMethodDecl &&
2352e5dd7070Spatrick objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2353e5dd7070Spatrick MethodImpl->getObjCDeclQualifier())) {
2354e5dd7070Spatrick if (Warn) {
2355e5dd7070Spatrick S.Diag(MethodImpl->getLocation(),
2356e5dd7070Spatrick (IsOverridingMode
2357e5dd7070Spatrick ? diag::warn_conflicting_overriding_ret_type_modifiers
2358e5dd7070Spatrick : diag::warn_conflicting_ret_type_modifiers))
2359e5dd7070Spatrick << MethodImpl->getDeclName()
2360e5dd7070Spatrick << MethodImpl->getReturnTypeSourceRange();
2361e5dd7070Spatrick S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2362e5dd7070Spatrick << MethodDecl->getReturnTypeSourceRange();
2363e5dd7070Spatrick }
2364e5dd7070Spatrick else
2365e5dd7070Spatrick return false;
2366e5dd7070Spatrick }
2367e5dd7070Spatrick if (Warn && IsOverridingMode &&
2368e5dd7070Spatrick !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2369e5dd7070Spatrick !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2370e5dd7070Spatrick MethodDecl->getReturnType(),
2371e5dd7070Spatrick false)) {
2372*12c85518Srobert auto nullabilityMethodImpl = *MethodImpl->getReturnType()->getNullability();
2373*12c85518Srobert auto nullabilityMethodDecl = *MethodDecl->getReturnType()->getNullability();
2374e5dd7070Spatrick S.Diag(MethodImpl->getLocation(),
2375e5dd7070Spatrick diag::warn_conflicting_nullability_attr_overriding_ret_types)
2376*12c85518Srobert << DiagNullabilityKind(nullabilityMethodImpl,
2377*12c85518Srobert ((MethodImpl->getObjCDeclQualifier() &
2378*12c85518Srobert Decl::OBJC_TQ_CSNullability) != 0))
2379*12c85518Srobert << DiagNullabilityKind(nullabilityMethodDecl,
2380*12c85518Srobert ((MethodDecl->getObjCDeclQualifier() &
2381*12c85518Srobert Decl::OBJC_TQ_CSNullability) != 0));
2382e5dd7070Spatrick S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2383e5dd7070Spatrick }
2384e5dd7070Spatrick
2385e5dd7070Spatrick if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2386e5dd7070Spatrick MethodDecl->getReturnType()))
2387e5dd7070Spatrick return true;
2388e5dd7070Spatrick if (!Warn)
2389e5dd7070Spatrick return false;
2390e5dd7070Spatrick
2391e5dd7070Spatrick unsigned DiagID =
2392e5dd7070Spatrick IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2393e5dd7070Spatrick : diag::warn_conflicting_ret_types;
2394e5dd7070Spatrick
2395e5dd7070Spatrick // Mismatches between ObjC pointers go into a different warning
2396ec727ea7Spatrick // category, and sometimes they're even completely explicitly allowed.
2397e5dd7070Spatrick if (const ObjCObjectPointerType *ImplPtrTy =
2398e5dd7070Spatrick MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2399e5dd7070Spatrick if (const ObjCObjectPointerType *IfacePtrTy =
2400e5dd7070Spatrick MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2401e5dd7070Spatrick // Allow non-matching return types as long as they don't violate
2402e5dd7070Spatrick // the principle of substitutability. Specifically, we permit
2403e5dd7070Spatrick // return types that are subclasses of the declared return type,
2404e5dd7070Spatrick // or that are more-qualified versions of the declared type.
2405e5dd7070Spatrick if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2406e5dd7070Spatrick return false;
2407e5dd7070Spatrick
2408e5dd7070Spatrick DiagID =
2409e5dd7070Spatrick IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2410e5dd7070Spatrick : diag::warn_non_covariant_ret_types;
2411e5dd7070Spatrick }
2412e5dd7070Spatrick }
2413e5dd7070Spatrick
2414e5dd7070Spatrick S.Diag(MethodImpl->getLocation(), DiagID)
2415e5dd7070Spatrick << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2416e5dd7070Spatrick << MethodImpl->getReturnType()
2417e5dd7070Spatrick << MethodImpl->getReturnTypeSourceRange();
2418e5dd7070Spatrick S.Diag(MethodDecl->getLocation(), IsOverridingMode
2419e5dd7070Spatrick ? diag::note_previous_declaration
2420e5dd7070Spatrick : diag::note_previous_definition)
2421e5dd7070Spatrick << MethodDecl->getReturnTypeSourceRange();
2422e5dd7070Spatrick return false;
2423e5dd7070Spatrick }
2424e5dd7070Spatrick
CheckMethodOverrideParam(Sema & S,ObjCMethodDecl * MethodImpl,ObjCMethodDecl * MethodDecl,ParmVarDecl * ImplVar,ParmVarDecl * IfaceVar,bool IsProtocolMethodDecl,bool IsOverridingMode,bool Warn)2425e5dd7070Spatrick static bool CheckMethodOverrideParam(Sema &S,
2426e5dd7070Spatrick ObjCMethodDecl *MethodImpl,
2427e5dd7070Spatrick ObjCMethodDecl *MethodDecl,
2428e5dd7070Spatrick ParmVarDecl *ImplVar,
2429e5dd7070Spatrick ParmVarDecl *IfaceVar,
2430e5dd7070Spatrick bool IsProtocolMethodDecl,
2431e5dd7070Spatrick bool IsOverridingMode,
2432e5dd7070Spatrick bool Warn) {
2433e5dd7070Spatrick if (IsProtocolMethodDecl &&
2434e5dd7070Spatrick objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2435e5dd7070Spatrick IfaceVar->getObjCDeclQualifier())) {
2436e5dd7070Spatrick if (Warn) {
2437e5dd7070Spatrick if (IsOverridingMode)
2438e5dd7070Spatrick S.Diag(ImplVar->getLocation(),
2439e5dd7070Spatrick diag::warn_conflicting_overriding_param_modifiers)
2440e5dd7070Spatrick << getTypeRange(ImplVar->getTypeSourceInfo())
2441e5dd7070Spatrick << MethodImpl->getDeclName();
2442e5dd7070Spatrick else S.Diag(ImplVar->getLocation(),
2443e5dd7070Spatrick diag::warn_conflicting_param_modifiers)
2444e5dd7070Spatrick << getTypeRange(ImplVar->getTypeSourceInfo())
2445e5dd7070Spatrick << MethodImpl->getDeclName();
2446e5dd7070Spatrick S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2447e5dd7070Spatrick << getTypeRange(IfaceVar->getTypeSourceInfo());
2448e5dd7070Spatrick }
2449e5dd7070Spatrick else
2450e5dd7070Spatrick return false;
2451e5dd7070Spatrick }
2452e5dd7070Spatrick
2453e5dd7070Spatrick QualType ImplTy = ImplVar->getType();
2454e5dd7070Spatrick QualType IfaceTy = IfaceVar->getType();
2455e5dd7070Spatrick if (Warn && IsOverridingMode &&
2456e5dd7070Spatrick !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2457e5dd7070Spatrick !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2458e5dd7070Spatrick S.Diag(ImplVar->getLocation(),
2459e5dd7070Spatrick diag::warn_conflicting_nullability_attr_overriding_param_types)
2460*12c85518Srobert << DiagNullabilityKind(*ImplTy->getNullability(),
2461*12c85518Srobert ((ImplVar->getObjCDeclQualifier() &
2462*12c85518Srobert Decl::OBJC_TQ_CSNullability) != 0))
2463*12c85518Srobert << DiagNullabilityKind(*IfaceTy->getNullability(),
2464*12c85518Srobert ((IfaceVar->getObjCDeclQualifier() &
2465*12c85518Srobert Decl::OBJC_TQ_CSNullability) != 0));
2466e5dd7070Spatrick S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2467e5dd7070Spatrick }
2468e5dd7070Spatrick if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2469e5dd7070Spatrick return true;
2470e5dd7070Spatrick
2471e5dd7070Spatrick if (!Warn)
2472e5dd7070Spatrick return false;
2473e5dd7070Spatrick unsigned DiagID =
2474e5dd7070Spatrick IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2475e5dd7070Spatrick : diag::warn_conflicting_param_types;
2476e5dd7070Spatrick
2477e5dd7070Spatrick // Mismatches between ObjC pointers go into a different warning
2478ec727ea7Spatrick // category, and sometimes they're even completely explicitly allowed..
2479e5dd7070Spatrick if (const ObjCObjectPointerType *ImplPtrTy =
2480e5dd7070Spatrick ImplTy->getAs<ObjCObjectPointerType>()) {
2481e5dd7070Spatrick if (const ObjCObjectPointerType *IfacePtrTy =
2482e5dd7070Spatrick IfaceTy->getAs<ObjCObjectPointerType>()) {
2483e5dd7070Spatrick // Allow non-matching argument types as long as they don't
2484e5dd7070Spatrick // violate the principle of substitutability. Specifically, the
2485e5dd7070Spatrick // implementation must accept any objects that the superclass
2486e5dd7070Spatrick // accepts, however it may also accept others.
2487e5dd7070Spatrick if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2488e5dd7070Spatrick return false;
2489e5dd7070Spatrick
2490e5dd7070Spatrick DiagID =
2491e5dd7070Spatrick IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2492e5dd7070Spatrick : diag::warn_non_contravariant_param_types;
2493e5dd7070Spatrick }
2494e5dd7070Spatrick }
2495e5dd7070Spatrick
2496e5dd7070Spatrick S.Diag(ImplVar->getLocation(), DiagID)
2497e5dd7070Spatrick << getTypeRange(ImplVar->getTypeSourceInfo())
2498e5dd7070Spatrick << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2499e5dd7070Spatrick S.Diag(IfaceVar->getLocation(),
2500e5dd7070Spatrick (IsOverridingMode ? diag::note_previous_declaration
2501e5dd7070Spatrick : diag::note_previous_definition))
2502e5dd7070Spatrick << getTypeRange(IfaceVar->getTypeSourceInfo());
2503e5dd7070Spatrick return false;
2504e5dd7070Spatrick }
2505e5dd7070Spatrick
2506e5dd7070Spatrick /// In ARC, check whether the conventional meanings of the two methods
2507e5dd7070Spatrick /// match. If they don't, it's a hard error.
checkMethodFamilyMismatch(Sema & S,ObjCMethodDecl * impl,ObjCMethodDecl * decl)2508e5dd7070Spatrick static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2509e5dd7070Spatrick ObjCMethodDecl *decl) {
2510e5dd7070Spatrick ObjCMethodFamily implFamily = impl->getMethodFamily();
2511e5dd7070Spatrick ObjCMethodFamily declFamily = decl->getMethodFamily();
2512e5dd7070Spatrick if (implFamily == declFamily) return false;
2513e5dd7070Spatrick
2514e5dd7070Spatrick // Since conventions are sorted by selector, the only possibility is
2515e5dd7070Spatrick // that the types differ enough to cause one selector or the other
2516e5dd7070Spatrick // to fall out of the family.
2517e5dd7070Spatrick assert(implFamily == OMF_None || declFamily == OMF_None);
2518e5dd7070Spatrick
2519e5dd7070Spatrick // No further diagnostics required on invalid declarations.
2520e5dd7070Spatrick if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2521e5dd7070Spatrick
2522e5dd7070Spatrick const ObjCMethodDecl *unmatched = impl;
2523e5dd7070Spatrick ObjCMethodFamily family = declFamily;
2524e5dd7070Spatrick unsigned errorID = diag::err_arc_lost_method_convention;
2525e5dd7070Spatrick unsigned noteID = diag::note_arc_lost_method_convention;
2526e5dd7070Spatrick if (declFamily == OMF_None) {
2527e5dd7070Spatrick unmatched = decl;
2528e5dd7070Spatrick family = implFamily;
2529e5dd7070Spatrick errorID = diag::err_arc_gained_method_convention;
2530e5dd7070Spatrick noteID = diag::note_arc_gained_method_convention;
2531e5dd7070Spatrick }
2532e5dd7070Spatrick
2533e5dd7070Spatrick // Indexes into a %select clause in the diagnostic.
2534e5dd7070Spatrick enum FamilySelector {
2535e5dd7070Spatrick F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2536e5dd7070Spatrick };
2537e5dd7070Spatrick FamilySelector familySelector = FamilySelector();
2538e5dd7070Spatrick
2539e5dd7070Spatrick switch (family) {
2540e5dd7070Spatrick case OMF_None: llvm_unreachable("logic error, no method convention");
2541e5dd7070Spatrick case OMF_retain:
2542e5dd7070Spatrick case OMF_release:
2543e5dd7070Spatrick case OMF_autorelease:
2544e5dd7070Spatrick case OMF_dealloc:
2545e5dd7070Spatrick case OMF_finalize:
2546e5dd7070Spatrick case OMF_retainCount:
2547e5dd7070Spatrick case OMF_self:
2548e5dd7070Spatrick case OMF_initialize:
2549e5dd7070Spatrick case OMF_performSelector:
2550e5dd7070Spatrick // Mismatches for these methods don't change ownership
2551e5dd7070Spatrick // conventions, so we don't care.
2552e5dd7070Spatrick return false;
2553e5dd7070Spatrick
2554e5dd7070Spatrick case OMF_init: familySelector = F_init; break;
2555e5dd7070Spatrick case OMF_alloc: familySelector = F_alloc; break;
2556e5dd7070Spatrick case OMF_copy: familySelector = F_copy; break;
2557e5dd7070Spatrick case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2558e5dd7070Spatrick case OMF_new: familySelector = F_new; break;
2559e5dd7070Spatrick }
2560e5dd7070Spatrick
2561e5dd7070Spatrick enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2562e5dd7070Spatrick ReasonSelector reasonSelector;
2563e5dd7070Spatrick
2564e5dd7070Spatrick // The only reason these methods don't fall within their families is
2565e5dd7070Spatrick // due to unusual result types.
2566e5dd7070Spatrick if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2567e5dd7070Spatrick reasonSelector = R_UnrelatedReturn;
2568e5dd7070Spatrick } else {
2569e5dd7070Spatrick reasonSelector = R_NonObjectReturn;
2570e5dd7070Spatrick }
2571e5dd7070Spatrick
2572e5dd7070Spatrick S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2573e5dd7070Spatrick S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2574e5dd7070Spatrick
2575e5dd7070Spatrick return true;
2576e5dd7070Spatrick }
2577e5dd7070Spatrick
WarnConflictingTypedMethods(ObjCMethodDecl * ImpMethodDecl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl)2578e5dd7070Spatrick void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2579e5dd7070Spatrick ObjCMethodDecl *MethodDecl,
2580e5dd7070Spatrick bool IsProtocolMethodDecl) {
2581e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount &&
2582e5dd7070Spatrick checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2583e5dd7070Spatrick return;
2584e5dd7070Spatrick
2585e5dd7070Spatrick CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2586e5dd7070Spatrick IsProtocolMethodDecl, false,
2587e5dd7070Spatrick true);
2588e5dd7070Spatrick
2589e5dd7070Spatrick for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2590e5dd7070Spatrick IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2591e5dd7070Spatrick EF = MethodDecl->param_end();
2592e5dd7070Spatrick IM != EM && IF != EF; ++IM, ++IF) {
2593e5dd7070Spatrick CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2594e5dd7070Spatrick IsProtocolMethodDecl, false, true);
2595e5dd7070Spatrick }
2596e5dd7070Spatrick
2597e5dd7070Spatrick if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2598e5dd7070Spatrick Diag(ImpMethodDecl->getLocation(),
2599e5dd7070Spatrick diag::warn_conflicting_variadic);
2600e5dd7070Spatrick Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2601e5dd7070Spatrick }
2602e5dd7070Spatrick }
2603e5dd7070Spatrick
CheckConflictingOverridingMethod(ObjCMethodDecl * Method,ObjCMethodDecl * Overridden,bool IsProtocolMethodDecl)2604e5dd7070Spatrick void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2605e5dd7070Spatrick ObjCMethodDecl *Overridden,
2606e5dd7070Spatrick bool IsProtocolMethodDecl) {
2607e5dd7070Spatrick
2608e5dd7070Spatrick CheckMethodOverrideReturn(*this, Method, Overridden,
2609e5dd7070Spatrick IsProtocolMethodDecl, true,
2610e5dd7070Spatrick true);
2611e5dd7070Spatrick
2612e5dd7070Spatrick for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2613e5dd7070Spatrick IF = Overridden->param_begin(), EM = Method->param_end(),
2614e5dd7070Spatrick EF = Overridden->param_end();
2615e5dd7070Spatrick IM != EM && IF != EF; ++IM, ++IF) {
2616e5dd7070Spatrick CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2617e5dd7070Spatrick IsProtocolMethodDecl, true, true);
2618e5dd7070Spatrick }
2619e5dd7070Spatrick
2620e5dd7070Spatrick if (Method->isVariadic() != Overridden->isVariadic()) {
2621e5dd7070Spatrick Diag(Method->getLocation(),
2622e5dd7070Spatrick diag::warn_conflicting_overriding_variadic);
2623e5dd7070Spatrick Diag(Overridden->getLocation(), diag::note_previous_declaration);
2624e5dd7070Spatrick }
2625e5dd7070Spatrick }
2626e5dd7070Spatrick
2627e5dd7070Spatrick /// WarnExactTypedMethods - This routine issues a warning if method
2628e5dd7070Spatrick /// implementation declaration matches exactly that of its declaration.
WarnExactTypedMethods(ObjCMethodDecl * ImpMethodDecl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl)2629e5dd7070Spatrick void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2630e5dd7070Spatrick ObjCMethodDecl *MethodDecl,
2631e5dd7070Spatrick bool IsProtocolMethodDecl) {
2632e5dd7070Spatrick // don't issue warning when protocol method is optional because primary
2633e5dd7070Spatrick // class is not required to implement it and it is safe for protocol
2634e5dd7070Spatrick // to implement it.
2635e5dd7070Spatrick if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2636e5dd7070Spatrick return;
2637e5dd7070Spatrick // don't issue warning when primary class's method is
2638*12c85518Srobert // deprecated/unavailable.
2639e5dd7070Spatrick if (MethodDecl->hasAttr<UnavailableAttr>() ||
2640e5dd7070Spatrick MethodDecl->hasAttr<DeprecatedAttr>())
2641e5dd7070Spatrick return;
2642e5dd7070Spatrick
2643e5dd7070Spatrick bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2644e5dd7070Spatrick IsProtocolMethodDecl, false, false);
2645e5dd7070Spatrick if (match)
2646e5dd7070Spatrick for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2647e5dd7070Spatrick IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2648e5dd7070Spatrick EF = MethodDecl->param_end();
2649e5dd7070Spatrick IM != EM && IF != EF; ++IM, ++IF) {
2650e5dd7070Spatrick match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2651e5dd7070Spatrick *IM, *IF,
2652e5dd7070Spatrick IsProtocolMethodDecl, false, false);
2653e5dd7070Spatrick if (!match)
2654e5dd7070Spatrick break;
2655e5dd7070Spatrick }
2656e5dd7070Spatrick if (match)
2657e5dd7070Spatrick match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2658e5dd7070Spatrick if (match)
2659e5dd7070Spatrick match = !(MethodDecl->isClassMethod() &&
2660e5dd7070Spatrick MethodDecl->getSelector() == GetNullarySelector("load", Context));
2661e5dd7070Spatrick
2662e5dd7070Spatrick if (match) {
2663e5dd7070Spatrick Diag(ImpMethodDecl->getLocation(),
2664e5dd7070Spatrick diag::warn_category_method_impl_match);
2665e5dd7070Spatrick Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2666e5dd7070Spatrick << MethodDecl->getDeclName();
2667e5dd7070Spatrick }
2668e5dd7070Spatrick }
2669e5dd7070Spatrick
2670e5dd7070Spatrick /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2671e5dd7070Spatrick /// improve the efficiency of selector lookups and type checking by associating
2672e5dd7070Spatrick /// with each protocol / interface / category the flattened instance tables. If
2673e5dd7070Spatrick /// we used an immutable set to keep the table then it wouldn't add significant
2674e5dd7070Spatrick /// memory cost and it would be handy for lookups.
2675e5dd7070Spatrick
2676e5dd7070Spatrick typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2677e5dd7070Spatrick typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2678e5dd7070Spatrick
findProtocolsWithExplicitImpls(const ObjCProtocolDecl * PDecl,ProtocolNameSet & PNS)2679e5dd7070Spatrick static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2680e5dd7070Spatrick ProtocolNameSet &PNS) {
2681e5dd7070Spatrick if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2682e5dd7070Spatrick PNS.insert(PDecl->getIdentifier());
2683e5dd7070Spatrick for (const auto *PI : PDecl->protocols())
2684e5dd7070Spatrick findProtocolsWithExplicitImpls(PI, PNS);
2685e5dd7070Spatrick }
2686e5dd7070Spatrick
2687e5dd7070Spatrick /// Recursively populates a set with all conformed protocols in a class
2688e5dd7070Spatrick /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2689e5dd7070Spatrick /// attribute.
findProtocolsWithExplicitImpls(const ObjCInterfaceDecl * Super,ProtocolNameSet & PNS)2690e5dd7070Spatrick static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2691e5dd7070Spatrick ProtocolNameSet &PNS) {
2692e5dd7070Spatrick if (!Super)
2693e5dd7070Spatrick return;
2694e5dd7070Spatrick
2695e5dd7070Spatrick for (const auto *I : Super->all_referenced_protocols())
2696e5dd7070Spatrick findProtocolsWithExplicitImpls(I, PNS);
2697e5dd7070Spatrick
2698e5dd7070Spatrick findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2699e5dd7070Spatrick }
2700e5dd7070Spatrick
2701e5dd7070Spatrick /// CheckProtocolMethodDefs - This routine checks unimplemented methods
2702e5dd7070Spatrick /// Declared in protocol, and those referenced by it.
CheckProtocolMethodDefs(Sema & S,ObjCImplDecl * Impl,ObjCProtocolDecl * PDecl,bool & IncompleteImpl,const Sema::SelectorSet & InsMap,const Sema::SelectorSet & ClsMap,ObjCContainerDecl * CDecl,LazyProtocolNameSet & ProtocolsExplictImpl)2703*12c85518Srobert static void CheckProtocolMethodDefs(
2704*12c85518Srobert Sema &S, ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool &IncompleteImpl,
2705*12c85518Srobert const Sema::SelectorSet &InsMap, const Sema::SelectorSet &ClsMap,
2706*12c85518Srobert ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) {
2707e5dd7070Spatrick ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2708e5dd7070Spatrick ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2709e5dd7070Spatrick : dyn_cast<ObjCInterfaceDecl>(CDecl);
2710e5dd7070Spatrick assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2711e5dd7070Spatrick
2712e5dd7070Spatrick ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2713e5dd7070Spatrick ObjCInterfaceDecl *NSIDecl = nullptr;
2714e5dd7070Spatrick
2715e5dd7070Spatrick // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2716e5dd7070Spatrick // then we should check if any class in the super class hierarchy also
2717e5dd7070Spatrick // conforms to this protocol, either directly or via protocol inheritance.
2718e5dd7070Spatrick // If so, we can skip checking this protocol completely because we
2719e5dd7070Spatrick // know that a parent class already satisfies this protocol.
2720e5dd7070Spatrick //
2721e5dd7070Spatrick // Note: we could generalize this logic for all protocols, and merely
2722e5dd7070Spatrick // add the limit on looking at the super class chain for just
2723e5dd7070Spatrick // specially marked protocols. This may be a good optimization. This
2724e5dd7070Spatrick // change is restricted to 'objc_protocol_requires_explicit_implementation'
2725e5dd7070Spatrick // protocols for now for controlled evaluation.
2726e5dd7070Spatrick if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2727e5dd7070Spatrick if (!ProtocolsExplictImpl) {
2728e5dd7070Spatrick ProtocolsExplictImpl.reset(new ProtocolNameSet);
2729e5dd7070Spatrick findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2730e5dd7070Spatrick }
2731*12c85518Srobert if (ProtocolsExplictImpl->contains(PDecl->getIdentifier()))
2732e5dd7070Spatrick return;
2733e5dd7070Spatrick
2734e5dd7070Spatrick // If no super class conforms to the protocol, we should not search
2735e5dd7070Spatrick // for methods in the super class to implicitly satisfy the protocol.
2736e5dd7070Spatrick Super = nullptr;
2737e5dd7070Spatrick }
2738e5dd7070Spatrick
2739e5dd7070Spatrick if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2740e5dd7070Spatrick // check to see if class implements forwardInvocation method and objects
2741e5dd7070Spatrick // of this class are derived from 'NSProxy' so that to forward requests
2742e5dd7070Spatrick // from one object to another.
2743e5dd7070Spatrick // Under such conditions, which means that every method possible is
2744e5dd7070Spatrick // implemented in the class, we should not issue "Method definition not
2745e5dd7070Spatrick // found" warnings.
2746e5dd7070Spatrick // FIXME: Use a general GetUnarySelector method for this.
2747e5dd7070Spatrick IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2748e5dd7070Spatrick Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2749e5dd7070Spatrick if (InsMap.count(fISelector))
2750e5dd7070Spatrick // Is IDecl derived from 'NSProxy'? If so, no instance methods
2751e5dd7070Spatrick // need be implemented in the implementation.
2752e5dd7070Spatrick NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2753e5dd7070Spatrick }
2754e5dd7070Spatrick
2755e5dd7070Spatrick // If this is a forward protocol declaration, get its definition.
2756e5dd7070Spatrick if (!PDecl->isThisDeclarationADefinition() &&
2757e5dd7070Spatrick PDecl->getDefinition())
2758e5dd7070Spatrick PDecl = PDecl->getDefinition();
2759e5dd7070Spatrick
2760e5dd7070Spatrick // If a method lookup fails locally we still need to look and see if
2761e5dd7070Spatrick // the method was implemented by a base class or an inherited
2762e5dd7070Spatrick // protocol. This lookup is slow, but occurs rarely in correct code
2763e5dd7070Spatrick // and otherwise would terminate in a warning.
2764e5dd7070Spatrick
2765e5dd7070Spatrick // check unimplemented instance methods.
2766e5dd7070Spatrick if (!NSIDecl)
2767e5dd7070Spatrick for (auto *method : PDecl->instance_methods()) {
2768e5dd7070Spatrick if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2769e5dd7070Spatrick !method->isPropertyAccessor() &&
2770e5dd7070Spatrick !InsMap.count(method->getSelector()) &&
2771e5dd7070Spatrick (!Super || !Super->lookupMethod(method->getSelector(),
2772e5dd7070Spatrick true /* instance */,
2773e5dd7070Spatrick false /* shallowCategory */,
2774e5dd7070Spatrick true /* followsSuper */,
2775e5dd7070Spatrick nullptr /* category */))) {
2776e5dd7070Spatrick // If a method is not implemented in the category implementation but
2777e5dd7070Spatrick // has been declared in its primary class, superclass,
2778e5dd7070Spatrick // or in one of their protocols, no need to issue the warning.
2779e5dd7070Spatrick // This is because method will be implemented in the primary class
2780e5dd7070Spatrick // or one of its super class implementation.
2781e5dd7070Spatrick
2782e5dd7070Spatrick // Ugly, but necessary. Method declared in protocol might have
2783e5dd7070Spatrick // have been synthesized due to a property declared in the class which
2784e5dd7070Spatrick // uses the protocol.
2785e5dd7070Spatrick if (ObjCMethodDecl *MethodInClass =
2786e5dd7070Spatrick IDecl->lookupMethod(method->getSelector(),
2787e5dd7070Spatrick true /* instance */,
2788e5dd7070Spatrick true /* shallowCategoryLookup */,
2789e5dd7070Spatrick false /* followSuper */))
2790e5dd7070Spatrick if (C || MethodInClass->isPropertyAccessor())
2791e5dd7070Spatrick continue;
2792e5dd7070Spatrick unsigned DIAG = diag::warn_unimplemented_protocol_method;
2793*12c85518Srobert if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2794*12c85518Srobert WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2795e5dd7070Spatrick }
2796e5dd7070Spatrick }
2797e5dd7070Spatrick }
2798e5dd7070Spatrick // check unimplemented class methods
2799e5dd7070Spatrick for (auto *method : PDecl->class_methods()) {
2800e5dd7070Spatrick if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2801e5dd7070Spatrick !ClsMap.count(method->getSelector()) &&
2802e5dd7070Spatrick (!Super || !Super->lookupMethod(method->getSelector(),
2803e5dd7070Spatrick false /* class method */,
2804e5dd7070Spatrick false /* shallowCategoryLookup */,
2805e5dd7070Spatrick true /* followSuper */,
2806e5dd7070Spatrick nullptr /* category */))) {
2807e5dd7070Spatrick // See above comment for instance method lookups.
2808e5dd7070Spatrick if (C && IDecl->lookupMethod(method->getSelector(),
2809e5dd7070Spatrick false /* class */,
2810e5dd7070Spatrick true /* shallowCategoryLookup */,
2811e5dd7070Spatrick false /* followSuper */))
2812e5dd7070Spatrick continue;
2813e5dd7070Spatrick
2814e5dd7070Spatrick unsigned DIAG = diag::warn_unimplemented_protocol_method;
2815*12c85518Srobert if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2816*12c85518Srobert WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2817e5dd7070Spatrick }
2818e5dd7070Spatrick }
2819e5dd7070Spatrick }
2820e5dd7070Spatrick // Check on this protocols's referenced protocols, recursively.
2821e5dd7070Spatrick for (auto *PI : PDecl->protocols())
2822*12c85518Srobert CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
2823*12c85518Srobert ProtocolsExplictImpl);
2824e5dd7070Spatrick }
2825e5dd7070Spatrick
2826e5dd7070Spatrick /// MatchAllMethodDeclarations - Check methods declared in interface
2827e5dd7070Spatrick /// or protocol against those declared in their implementations.
2828e5dd7070Spatrick ///
MatchAllMethodDeclarations(const SelectorSet & InsMap,const SelectorSet & ClsMap,SelectorSet & InsMapSeen,SelectorSet & ClsMapSeen,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,bool & IncompleteImpl,bool ImmediateClass,bool WarnCategoryMethodImpl)2829e5dd7070Spatrick void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2830e5dd7070Spatrick const SelectorSet &ClsMap,
2831e5dd7070Spatrick SelectorSet &InsMapSeen,
2832e5dd7070Spatrick SelectorSet &ClsMapSeen,
2833e5dd7070Spatrick ObjCImplDecl* IMPDecl,
2834e5dd7070Spatrick ObjCContainerDecl* CDecl,
2835e5dd7070Spatrick bool &IncompleteImpl,
2836e5dd7070Spatrick bool ImmediateClass,
2837e5dd7070Spatrick bool WarnCategoryMethodImpl) {
2838e5dd7070Spatrick // Check and see if instance methods in class interface have been
2839e5dd7070Spatrick // implemented in the implementation class. If so, their types match.
2840e5dd7070Spatrick for (auto *I : CDecl->instance_methods()) {
2841e5dd7070Spatrick if (!InsMapSeen.insert(I->getSelector()).second)
2842e5dd7070Spatrick continue;
2843e5dd7070Spatrick if (!I->isPropertyAccessor() &&
2844e5dd7070Spatrick !InsMap.count(I->getSelector())) {
2845e5dd7070Spatrick if (ImmediateClass)
2846*12c85518Srobert WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
2847e5dd7070Spatrick diag::warn_undef_method_impl);
2848e5dd7070Spatrick continue;
2849e5dd7070Spatrick } else {
2850e5dd7070Spatrick ObjCMethodDecl *ImpMethodDecl =
2851e5dd7070Spatrick IMPDecl->getInstanceMethod(I->getSelector());
2852e5dd7070Spatrick assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2853e5dd7070Spatrick "Expected to find the method through lookup as well");
2854e5dd7070Spatrick // ImpMethodDecl may be null as in a @dynamic property.
2855e5dd7070Spatrick if (ImpMethodDecl) {
2856e5dd7070Spatrick // Skip property accessor function stubs.
2857e5dd7070Spatrick if (ImpMethodDecl->isSynthesizedAccessorStub())
2858e5dd7070Spatrick continue;
2859e5dd7070Spatrick if (!WarnCategoryMethodImpl)
2860e5dd7070Spatrick WarnConflictingTypedMethods(ImpMethodDecl, I,
2861e5dd7070Spatrick isa<ObjCProtocolDecl>(CDecl));
2862e5dd7070Spatrick else if (!I->isPropertyAccessor())
2863e5dd7070Spatrick WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2864e5dd7070Spatrick }
2865e5dd7070Spatrick }
2866e5dd7070Spatrick }
2867e5dd7070Spatrick
2868e5dd7070Spatrick // Check and see if class methods in class interface have been
2869e5dd7070Spatrick // implemented in the implementation class. If so, their types match.
2870e5dd7070Spatrick for (auto *I : CDecl->class_methods()) {
2871e5dd7070Spatrick if (!ClsMapSeen.insert(I->getSelector()).second)
2872e5dd7070Spatrick continue;
2873e5dd7070Spatrick if (!I->isPropertyAccessor() &&
2874e5dd7070Spatrick !ClsMap.count(I->getSelector())) {
2875e5dd7070Spatrick if (ImmediateClass)
2876*12c85518Srobert WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
2877e5dd7070Spatrick diag::warn_undef_method_impl);
2878e5dd7070Spatrick } else {
2879e5dd7070Spatrick ObjCMethodDecl *ImpMethodDecl =
2880e5dd7070Spatrick IMPDecl->getClassMethod(I->getSelector());
2881e5dd7070Spatrick assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2882e5dd7070Spatrick "Expected to find the method through lookup as well");
2883e5dd7070Spatrick // ImpMethodDecl may be null as in a @dynamic property.
2884e5dd7070Spatrick if (ImpMethodDecl) {
2885e5dd7070Spatrick // Skip property accessor function stubs.
2886e5dd7070Spatrick if (ImpMethodDecl->isSynthesizedAccessorStub())
2887e5dd7070Spatrick continue;
2888e5dd7070Spatrick if (!WarnCategoryMethodImpl)
2889e5dd7070Spatrick WarnConflictingTypedMethods(ImpMethodDecl, I,
2890e5dd7070Spatrick isa<ObjCProtocolDecl>(CDecl));
2891e5dd7070Spatrick else if (!I->isPropertyAccessor())
2892e5dd7070Spatrick WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2893e5dd7070Spatrick }
2894e5dd7070Spatrick }
2895e5dd7070Spatrick }
2896e5dd7070Spatrick
2897e5dd7070Spatrick if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2898e5dd7070Spatrick // Also, check for methods declared in protocols inherited by
2899e5dd7070Spatrick // this protocol.
2900e5dd7070Spatrick for (auto *PI : PD->protocols())
2901e5dd7070Spatrick MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2902e5dd7070Spatrick IMPDecl, PI, IncompleteImpl, false,
2903e5dd7070Spatrick WarnCategoryMethodImpl);
2904e5dd7070Spatrick }
2905e5dd7070Spatrick
2906e5dd7070Spatrick if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2907e5dd7070Spatrick // when checking that methods in implementation match their declaration,
2908e5dd7070Spatrick // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2909e5dd7070Spatrick // extension; as well as those in categories.
2910e5dd7070Spatrick if (!WarnCategoryMethodImpl) {
2911e5dd7070Spatrick for (auto *Cat : I->visible_categories())
2912e5dd7070Spatrick MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2913e5dd7070Spatrick IMPDecl, Cat, IncompleteImpl,
2914e5dd7070Spatrick ImmediateClass && Cat->IsClassExtension(),
2915e5dd7070Spatrick WarnCategoryMethodImpl);
2916e5dd7070Spatrick } else {
2917e5dd7070Spatrick // Also methods in class extensions need be looked at next.
2918e5dd7070Spatrick for (auto *Ext : I->visible_extensions())
2919e5dd7070Spatrick MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2920e5dd7070Spatrick IMPDecl, Ext, IncompleteImpl, false,
2921e5dd7070Spatrick WarnCategoryMethodImpl);
2922e5dd7070Spatrick }
2923e5dd7070Spatrick
2924e5dd7070Spatrick // Check for any implementation of a methods declared in protocol.
2925e5dd7070Spatrick for (auto *PI : I->all_referenced_protocols())
2926e5dd7070Spatrick MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2927e5dd7070Spatrick IMPDecl, PI, IncompleteImpl, false,
2928e5dd7070Spatrick WarnCategoryMethodImpl);
2929e5dd7070Spatrick
2930e5dd7070Spatrick // FIXME. For now, we are not checking for exact match of methods
2931e5dd7070Spatrick // in category implementation and its primary class's super class.
2932e5dd7070Spatrick if (!WarnCategoryMethodImpl && I->getSuperClass())
2933e5dd7070Spatrick MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2934e5dd7070Spatrick IMPDecl,
2935e5dd7070Spatrick I->getSuperClass(), IncompleteImpl, false);
2936e5dd7070Spatrick }
2937e5dd7070Spatrick }
2938e5dd7070Spatrick
2939e5dd7070Spatrick /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2940e5dd7070Spatrick /// category matches with those implemented in its primary class and
2941e5dd7070Spatrick /// warns each time an exact match is found.
CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl * CatIMPDecl)2942e5dd7070Spatrick void Sema::CheckCategoryVsClassMethodMatches(
2943e5dd7070Spatrick ObjCCategoryImplDecl *CatIMPDecl) {
2944e5dd7070Spatrick // Get category's primary class.
2945e5dd7070Spatrick ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2946e5dd7070Spatrick if (!CatDecl)
2947e5dd7070Spatrick return;
2948e5dd7070Spatrick ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2949e5dd7070Spatrick if (!IDecl)
2950e5dd7070Spatrick return;
2951e5dd7070Spatrick ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2952e5dd7070Spatrick SelectorSet InsMap, ClsMap;
2953e5dd7070Spatrick
2954e5dd7070Spatrick for (const auto *I : CatIMPDecl->instance_methods()) {
2955e5dd7070Spatrick Selector Sel = I->getSelector();
2956e5dd7070Spatrick // When checking for methods implemented in the category, skip over
2957e5dd7070Spatrick // those declared in category class's super class. This is because
2958e5dd7070Spatrick // the super class must implement the method.
2959e5dd7070Spatrick if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2960e5dd7070Spatrick continue;
2961e5dd7070Spatrick InsMap.insert(Sel);
2962e5dd7070Spatrick }
2963e5dd7070Spatrick
2964e5dd7070Spatrick for (const auto *I : CatIMPDecl->class_methods()) {
2965e5dd7070Spatrick Selector Sel = I->getSelector();
2966e5dd7070Spatrick if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2967e5dd7070Spatrick continue;
2968e5dd7070Spatrick ClsMap.insert(Sel);
2969e5dd7070Spatrick }
2970e5dd7070Spatrick if (InsMap.empty() && ClsMap.empty())
2971e5dd7070Spatrick return;
2972e5dd7070Spatrick
2973e5dd7070Spatrick SelectorSet InsMapSeen, ClsMapSeen;
2974e5dd7070Spatrick bool IncompleteImpl = false;
2975e5dd7070Spatrick MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2976e5dd7070Spatrick CatIMPDecl, IDecl,
2977e5dd7070Spatrick IncompleteImpl, false,
2978e5dd7070Spatrick true /*WarnCategoryMethodImpl*/);
2979e5dd7070Spatrick }
2980e5dd7070Spatrick
ImplMethodsVsClassMethods(Scope * S,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,bool IncompleteImpl)2981e5dd7070Spatrick void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2982e5dd7070Spatrick ObjCContainerDecl* CDecl,
2983e5dd7070Spatrick bool IncompleteImpl) {
2984e5dd7070Spatrick SelectorSet InsMap;
2985e5dd7070Spatrick // Check and see if instance methods in class interface have been
2986e5dd7070Spatrick // implemented in the implementation class.
2987e5dd7070Spatrick for (const auto *I : IMPDecl->instance_methods())
2988e5dd7070Spatrick InsMap.insert(I->getSelector());
2989e5dd7070Spatrick
2990e5dd7070Spatrick // Add the selectors for getters/setters of @dynamic properties.
2991e5dd7070Spatrick for (const auto *PImpl : IMPDecl->property_impls()) {
2992e5dd7070Spatrick // We only care about @dynamic implementations.
2993e5dd7070Spatrick if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2994e5dd7070Spatrick continue;
2995e5dd7070Spatrick
2996e5dd7070Spatrick const auto *P = PImpl->getPropertyDecl();
2997e5dd7070Spatrick if (!P) continue;
2998e5dd7070Spatrick
2999e5dd7070Spatrick InsMap.insert(P->getGetterName());
3000e5dd7070Spatrick if (!P->getSetterName().isNull())
3001e5dd7070Spatrick InsMap.insert(P->getSetterName());
3002e5dd7070Spatrick }
3003e5dd7070Spatrick
3004e5dd7070Spatrick // Check and see if properties declared in the interface have either 1)
3005e5dd7070Spatrick // an implementation or 2) there is a @synthesize/@dynamic implementation
3006e5dd7070Spatrick // of the property in the @implementation.
3007e5dd7070Spatrick if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
3008e5dd7070Spatrick bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
3009e5dd7070Spatrick LangOpts.ObjCRuntime.isNonFragile() &&
3010e5dd7070Spatrick !IDecl->isObjCRequiresPropertyDefs();
3011e5dd7070Spatrick DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
3012e5dd7070Spatrick }
3013e5dd7070Spatrick
3014e5dd7070Spatrick // Diagnose null-resettable synthesized setters.
3015e5dd7070Spatrick diagnoseNullResettableSynthesizedSetters(IMPDecl);
3016e5dd7070Spatrick
3017e5dd7070Spatrick SelectorSet ClsMap;
3018e5dd7070Spatrick for (const auto *I : IMPDecl->class_methods())
3019e5dd7070Spatrick ClsMap.insert(I->getSelector());
3020e5dd7070Spatrick
3021e5dd7070Spatrick // Check for type conflict of methods declared in a class/protocol and
3022e5dd7070Spatrick // its implementation; if any.
3023e5dd7070Spatrick SelectorSet InsMapSeen, ClsMapSeen;
3024e5dd7070Spatrick MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3025e5dd7070Spatrick IMPDecl, CDecl,
3026e5dd7070Spatrick IncompleteImpl, true);
3027e5dd7070Spatrick
3028e5dd7070Spatrick // check all methods implemented in category against those declared
3029e5dd7070Spatrick // in its primary class.
3030e5dd7070Spatrick if (ObjCCategoryImplDecl *CatDecl =
3031e5dd7070Spatrick dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3032e5dd7070Spatrick CheckCategoryVsClassMethodMatches(CatDecl);
3033e5dd7070Spatrick
3034e5dd7070Spatrick // Check the protocol list for unimplemented methods in the @implementation
3035e5dd7070Spatrick // class.
3036e5dd7070Spatrick // Check and see if class methods in class interface have been
3037e5dd7070Spatrick // implemented in the implementation class.
3038e5dd7070Spatrick
3039e5dd7070Spatrick LazyProtocolNameSet ExplicitImplProtocols;
3040e5dd7070Spatrick
3041e5dd7070Spatrick if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3042e5dd7070Spatrick for (auto *PI : I->all_referenced_protocols())
3043*12c85518Srobert CheckProtocolMethodDefs(*this, IMPDecl, PI, IncompleteImpl, InsMap,
3044*12c85518Srobert ClsMap, I, ExplicitImplProtocols);
3045e5dd7070Spatrick } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3046e5dd7070Spatrick // For extended class, unimplemented methods in its protocols will
3047e5dd7070Spatrick // be reported in the primary class.
3048e5dd7070Spatrick if (!C->IsClassExtension()) {
3049e5dd7070Spatrick for (auto *P : C->protocols())
3050*12c85518Srobert CheckProtocolMethodDefs(*this, IMPDecl, P, IncompleteImpl, InsMap,
3051*12c85518Srobert ClsMap, CDecl, ExplicitImplProtocols);
3052e5dd7070Spatrick DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3053e5dd7070Spatrick /*SynthesizeProperties=*/false);
3054e5dd7070Spatrick }
3055e5dd7070Spatrick } else
3056e5dd7070Spatrick llvm_unreachable("invalid ObjCContainerDecl type.");
3057e5dd7070Spatrick }
3058e5dd7070Spatrick
3059e5dd7070Spatrick Sema::DeclGroupPtrTy
ActOnForwardClassDeclaration(SourceLocation AtClassLoc,IdentifierInfo ** IdentList,SourceLocation * IdentLocs,ArrayRef<ObjCTypeParamList * > TypeParamLists,unsigned NumElts)3060e5dd7070Spatrick Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
3061e5dd7070Spatrick IdentifierInfo **IdentList,
3062e5dd7070Spatrick SourceLocation *IdentLocs,
3063e5dd7070Spatrick ArrayRef<ObjCTypeParamList *> TypeParamLists,
3064e5dd7070Spatrick unsigned NumElts) {
3065e5dd7070Spatrick SmallVector<Decl *, 8> DeclsInGroup;
3066e5dd7070Spatrick for (unsigned i = 0; i != NumElts; ++i) {
3067e5dd7070Spatrick // Check for another declaration kind with the same name.
3068e5dd7070Spatrick NamedDecl *PrevDecl
3069e5dd7070Spatrick = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
3070e5dd7070Spatrick LookupOrdinaryName, forRedeclarationInCurContext());
3071e5dd7070Spatrick if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3072e5dd7070Spatrick // GCC apparently allows the following idiom:
3073e5dd7070Spatrick //
3074e5dd7070Spatrick // typedef NSObject < XCElementTogglerP > XCElementToggler;
3075e5dd7070Spatrick // @class XCElementToggler;
3076e5dd7070Spatrick //
3077e5dd7070Spatrick // Here we have chosen to ignore the forward class declaration
3078e5dd7070Spatrick // with a warning. Since this is the implied behavior.
3079e5dd7070Spatrick TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3080e5dd7070Spatrick if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3081e5dd7070Spatrick Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3082e5dd7070Spatrick Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3083e5dd7070Spatrick } else {
3084e5dd7070Spatrick // a forward class declaration matching a typedef name of a class refers
3085e5dd7070Spatrick // to the underlying class. Just ignore the forward class with a warning
3086e5dd7070Spatrick // as this will force the intended behavior which is to lookup the
3087e5dd7070Spatrick // typedef name.
3088e5dd7070Spatrick if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3089e5dd7070Spatrick Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3090e5dd7070Spatrick << IdentList[i];
3091e5dd7070Spatrick Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3092e5dd7070Spatrick continue;
3093e5dd7070Spatrick }
3094e5dd7070Spatrick }
3095e5dd7070Spatrick }
3096e5dd7070Spatrick
3097e5dd7070Spatrick // Create a declaration to describe this forward declaration.
3098e5dd7070Spatrick ObjCInterfaceDecl *PrevIDecl
3099e5dd7070Spatrick = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3100e5dd7070Spatrick
3101e5dd7070Spatrick IdentifierInfo *ClassName = IdentList[i];
3102e5dd7070Spatrick if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3103e5dd7070Spatrick // A previous decl with a different name is because of
3104e5dd7070Spatrick // @compatibility_alias, for example:
3105e5dd7070Spatrick // \code
3106e5dd7070Spatrick // @class NewImage;
3107e5dd7070Spatrick // @compatibility_alias OldImage NewImage;
3108e5dd7070Spatrick // \endcode
3109e5dd7070Spatrick // A lookup for 'OldImage' will return the 'NewImage' decl.
3110e5dd7070Spatrick //
3111e5dd7070Spatrick // In such a case use the real declaration name, instead of the alias one,
3112e5dd7070Spatrick // otherwise we will break IdentifierResolver and redecls-chain invariants.
3113e5dd7070Spatrick // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3114e5dd7070Spatrick // has been aliased.
3115e5dd7070Spatrick ClassName = PrevIDecl->getIdentifier();
3116e5dd7070Spatrick }
3117e5dd7070Spatrick
3118e5dd7070Spatrick // If this forward declaration has type parameters, compare them with the
3119e5dd7070Spatrick // type parameters of the previous declaration.
3120e5dd7070Spatrick ObjCTypeParamList *TypeParams = TypeParamLists[i];
3121e5dd7070Spatrick if (PrevIDecl && TypeParams) {
3122e5dd7070Spatrick if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3123e5dd7070Spatrick // Check for consistency with the previous declaration.
3124e5dd7070Spatrick if (checkTypeParamListConsistency(
3125e5dd7070Spatrick *this, PrevTypeParams, TypeParams,
3126e5dd7070Spatrick TypeParamListContext::ForwardDeclaration)) {
3127e5dd7070Spatrick TypeParams = nullptr;
3128e5dd7070Spatrick }
3129e5dd7070Spatrick } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3130e5dd7070Spatrick // The @interface does not have type parameters. Complain.
3131e5dd7070Spatrick Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3132e5dd7070Spatrick << ClassName
3133e5dd7070Spatrick << TypeParams->getSourceRange();
3134e5dd7070Spatrick Diag(Def->getLocation(), diag::note_defined_here)
3135e5dd7070Spatrick << ClassName;
3136e5dd7070Spatrick
3137e5dd7070Spatrick TypeParams = nullptr;
3138e5dd7070Spatrick }
3139e5dd7070Spatrick }
3140e5dd7070Spatrick
3141e5dd7070Spatrick ObjCInterfaceDecl *IDecl
3142e5dd7070Spatrick = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3143e5dd7070Spatrick ClassName, TypeParams, PrevIDecl,
3144e5dd7070Spatrick IdentLocs[i]);
3145e5dd7070Spatrick IDecl->setAtEndRange(IdentLocs[i]);
3146e5dd7070Spatrick
3147a9ac8606Spatrick if (PrevIDecl)
3148a9ac8606Spatrick mergeDeclAttributes(IDecl, PrevIDecl);
3149a9ac8606Spatrick
3150e5dd7070Spatrick PushOnScopeChains(IDecl, TUScope);
3151e5dd7070Spatrick CheckObjCDeclScope(IDecl);
3152e5dd7070Spatrick DeclsInGroup.push_back(IDecl);
3153e5dd7070Spatrick }
3154e5dd7070Spatrick
3155e5dd7070Spatrick return BuildDeclaratorGroup(DeclsInGroup);
3156e5dd7070Spatrick }
3157e5dd7070Spatrick
3158e5dd7070Spatrick static bool tryMatchRecordTypes(ASTContext &Context,
3159e5dd7070Spatrick Sema::MethodMatchStrategy strategy,
3160e5dd7070Spatrick const Type *left, const Type *right);
3161e5dd7070Spatrick
matchTypes(ASTContext & Context,Sema::MethodMatchStrategy strategy,QualType leftQT,QualType rightQT)3162e5dd7070Spatrick static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3163e5dd7070Spatrick QualType leftQT, QualType rightQT) {
3164e5dd7070Spatrick const Type *left =
3165e5dd7070Spatrick Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3166e5dd7070Spatrick const Type *right =
3167e5dd7070Spatrick Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3168e5dd7070Spatrick
3169e5dd7070Spatrick if (left == right) return true;
3170e5dd7070Spatrick
3171e5dd7070Spatrick // If we're doing a strict match, the types have to match exactly.
3172e5dd7070Spatrick if (strategy == Sema::MMS_strict) return false;
3173e5dd7070Spatrick
3174e5dd7070Spatrick if (left->isIncompleteType() || right->isIncompleteType()) return false;
3175e5dd7070Spatrick
3176e5dd7070Spatrick // Otherwise, use this absurdly complicated algorithm to try to
3177e5dd7070Spatrick // validate the basic, low-level compatibility of the two types.
3178e5dd7070Spatrick
3179e5dd7070Spatrick // As a minimum, require the sizes and alignments to match.
3180e5dd7070Spatrick TypeInfo LeftTI = Context.getTypeInfo(left);
3181e5dd7070Spatrick TypeInfo RightTI = Context.getTypeInfo(right);
3182e5dd7070Spatrick if (LeftTI.Width != RightTI.Width)
3183e5dd7070Spatrick return false;
3184e5dd7070Spatrick
3185e5dd7070Spatrick if (LeftTI.Align != RightTI.Align)
3186e5dd7070Spatrick return false;
3187e5dd7070Spatrick
3188e5dd7070Spatrick // Consider all the kinds of non-dependent canonical types:
3189e5dd7070Spatrick // - functions and arrays aren't possible as return and parameter types
3190e5dd7070Spatrick
3191e5dd7070Spatrick // - vector types of equal size can be arbitrarily mixed
3192e5dd7070Spatrick if (isa<VectorType>(left)) return isa<VectorType>(right);
3193e5dd7070Spatrick if (isa<VectorType>(right)) return false;
3194e5dd7070Spatrick
3195e5dd7070Spatrick // - references should only match references of identical type
3196e5dd7070Spatrick // - structs, unions, and Objective-C objects must match more-or-less
3197e5dd7070Spatrick // exactly
3198e5dd7070Spatrick // - everything else should be a scalar
3199e5dd7070Spatrick if (!left->isScalarType() || !right->isScalarType())
3200e5dd7070Spatrick return tryMatchRecordTypes(Context, strategy, left, right);
3201e5dd7070Spatrick
3202e5dd7070Spatrick // Make scalars agree in kind, except count bools as chars, and group
3203e5dd7070Spatrick // all non-member pointers together.
3204e5dd7070Spatrick Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3205e5dd7070Spatrick Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3206e5dd7070Spatrick if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3207e5dd7070Spatrick if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3208e5dd7070Spatrick if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3209e5dd7070Spatrick leftSK = Type::STK_ObjCObjectPointer;
3210e5dd7070Spatrick if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3211e5dd7070Spatrick rightSK = Type::STK_ObjCObjectPointer;
3212e5dd7070Spatrick
3213e5dd7070Spatrick // Note that data member pointers and function member pointers don't
3214e5dd7070Spatrick // intermix because of the size differences.
3215e5dd7070Spatrick
3216e5dd7070Spatrick return (leftSK == rightSK);
3217e5dd7070Spatrick }
3218e5dd7070Spatrick
tryMatchRecordTypes(ASTContext & Context,Sema::MethodMatchStrategy strategy,const Type * lt,const Type * rt)3219e5dd7070Spatrick static bool tryMatchRecordTypes(ASTContext &Context,
3220e5dd7070Spatrick Sema::MethodMatchStrategy strategy,
3221e5dd7070Spatrick const Type *lt, const Type *rt) {
3222e5dd7070Spatrick assert(lt && rt && lt != rt);
3223e5dd7070Spatrick
3224e5dd7070Spatrick if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3225e5dd7070Spatrick RecordDecl *left = cast<RecordType>(lt)->getDecl();
3226e5dd7070Spatrick RecordDecl *right = cast<RecordType>(rt)->getDecl();
3227e5dd7070Spatrick
3228e5dd7070Spatrick // Require union-hood to match.
3229e5dd7070Spatrick if (left->isUnion() != right->isUnion()) return false;
3230e5dd7070Spatrick
3231e5dd7070Spatrick // Require an exact match if either is non-POD.
3232e5dd7070Spatrick if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3233e5dd7070Spatrick (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3234e5dd7070Spatrick return false;
3235e5dd7070Spatrick
3236e5dd7070Spatrick // Require size and alignment to match.
3237e5dd7070Spatrick TypeInfo LeftTI = Context.getTypeInfo(lt);
3238e5dd7070Spatrick TypeInfo RightTI = Context.getTypeInfo(rt);
3239e5dd7070Spatrick if (LeftTI.Width != RightTI.Width)
3240e5dd7070Spatrick return false;
3241e5dd7070Spatrick
3242e5dd7070Spatrick if (LeftTI.Align != RightTI.Align)
3243e5dd7070Spatrick return false;
3244e5dd7070Spatrick
3245e5dd7070Spatrick // Require fields to match.
3246e5dd7070Spatrick RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3247e5dd7070Spatrick RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3248e5dd7070Spatrick for (; li != le && ri != re; ++li, ++ri) {
3249e5dd7070Spatrick if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3250e5dd7070Spatrick return false;
3251e5dd7070Spatrick }
3252e5dd7070Spatrick return (li == le && ri == re);
3253e5dd7070Spatrick }
3254e5dd7070Spatrick
3255e5dd7070Spatrick /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3256e5dd7070Spatrick /// returns true, or false, accordingly.
3257e5dd7070Spatrick /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
MatchTwoMethodDeclarations(const ObjCMethodDecl * left,const ObjCMethodDecl * right,MethodMatchStrategy strategy)3258e5dd7070Spatrick bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3259e5dd7070Spatrick const ObjCMethodDecl *right,
3260e5dd7070Spatrick MethodMatchStrategy strategy) {
3261e5dd7070Spatrick if (!matchTypes(Context, strategy, left->getReturnType(),
3262e5dd7070Spatrick right->getReturnType()))
3263e5dd7070Spatrick return false;
3264e5dd7070Spatrick
3265e5dd7070Spatrick // If either is hidden, it is not considered to match.
3266ec727ea7Spatrick if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible())
3267e5dd7070Spatrick return false;
3268e5dd7070Spatrick
3269e5dd7070Spatrick if (left->isDirectMethod() != right->isDirectMethod())
3270e5dd7070Spatrick return false;
3271e5dd7070Spatrick
3272e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount &&
3273e5dd7070Spatrick (left->hasAttr<NSReturnsRetainedAttr>()
3274e5dd7070Spatrick != right->hasAttr<NSReturnsRetainedAttr>() ||
3275e5dd7070Spatrick left->hasAttr<NSConsumesSelfAttr>()
3276e5dd7070Spatrick != right->hasAttr<NSConsumesSelfAttr>()))
3277e5dd7070Spatrick return false;
3278e5dd7070Spatrick
3279e5dd7070Spatrick ObjCMethodDecl::param_const_iterator
3280e5dd7070Spatrick li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3281e5dd7070Spatrick re = right->param_end();
3282e5dd7070Spatrick
3283e5dd7070Spatrick for (; li != le && ri != re; ++li, ++ri) {
3284e5dd7070Spatrick assert(ri != right->param_end() && "Param mismatch");
3285e5dd7070Spatrick const ParmVarDecl *lparm = *li, *rparm = *ri;
3286e5dd7070Spatrick
3287e5dd7070Spatrick if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3288e5dd7070Spatrick return false;
3289e5dd7070Spatrick
3290e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount &&
3291e5dd7070Spatrick lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3292e5dd7070Spatrick return false;
3293e5dd7070Spatrick }
3294e5dd7070Spatrick return true;
3295e5dd7070Spatrick }
3296e5dd7070Spatrick
isMethodContextSameForKindofLookup(ObjCMethodDecl * Method,ObjCMethodDecl * MethodInList)3297e5dd7070Spatrick static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3298e5dd7070Spatrick ObjCMethodDecl *MethodInList) {
3299e5dd7070Spatrick auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3300e5dd7070Spatrick auto *MethodInListProtocol =
3301e5dd7070Spatrick dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3302e5dd7070Spatrick // If this method belongs to a protocol but the method in list does not, or
3303e5dd7070Spatrick // vice versa, we say the context is not the same.
3304e5dd7070Spatrick if ((MethodProtocol && !MethodInListProtocol) ||
3305e5dd7070Spatrick (!MethodProtocol && MethodInListProtocol))
3306e5dd7070Spatrick return false;
3307e5dd7070Spatrick
3308e5dd7070Spatrick if (MethodProtocol && MethodInListProtocol)
3309e5dd7070Spatrick return true;
3310e5dd7070Spatrick
3311e5dd7070Spatrick ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3312e5dd7070Spatrick ObjCInterfaceDecl *MethodInListInterface =
3313e5dd7070Spatrick MethodInList->getClassInterface();
3314e5dd7070Spatrick return MethodInterface == MethodInListInterface;
3315e5dd7070Spatrick }
3316e5dd7070Spatrick
addMethodToGlobalList(ObjCMethodList * List,ObjCMethodDecl * Method)3317e5dd7070Spatrick void Sema::addMethodToGlobalList(ObjCMethodList *List,
3318e5dd7070Spatrick ObjCMethodDecl *Method) {
3319e5dd7070Spatrick // Record at the head of the list whether there were 0, 1, or >= 2 methods
3320e5dd7070Spatrick // inside categories.
3321e5dd7070Spatrick if (ObjCCategoryDecl *CD =
3322e5dd7070Spatrick dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3323e5dd7070Spatrick if (!CD->IsClassExtension() && List->getBits() < 2)
3324e5dd7070Spatrick List->setBits(List->getBits() + 1);
3325e5dd7070Spatrick
3326e5dd7070Spatrick // If the list is empty, make it a singleton list.
3327e5dd7070Spatrick if (List->getMethod() == nullptr) {
3328e5dd7070Spatrick List->setMethod(Method);
3329e5dd7070Spatrick List->setNext(nullptr);
3330e5dd7070Spatrick return;
3331e5dd7070Spatrick }
3332e5dd7070Spatrick
3333e5dd7070Spatrick // We've seen a method with this name, see if we have already seen this type
3334e5dd7070Spatrick // signature.
3335e5dd7070Spatrick ObjCMethodList *Previous = List;
3336e5dd7070Spatrick ObjCMethodList *ListWithSameDeclaration = nullptr;
3337e5dd7070Spatrick for (; List; Previous = List, List = List->getNext()) {
3338e5dd7070Spatrick // If we are building a module, keep all of the methods.
3339e5dd7070Spatrick if (getLangOpts().isCompilingModule())
3340e5dd7070Spatrick continue;
3341e5dd7070Spatrick
3342e5dd7070Spatrick bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3343e5dd7070Spatrick List->getMethod());
3344e5dd7070Spatrick // Looking for method with a type bound requires the correct context exists.
3345e5dd7070Spatrick // We need to insert a method into the list if the context is different.
3346e5dd7070Spatrick // If the method's declaration matches the list
3347e5dd7070Spatrick // a> the method belongs to a different context: we need to insert it, in
3348e5dd7070Spatrick // order to emit the availability message, we need to prioritize over
3349e5dd7070Spatrick // availability among the methods with the same declaration.
3350e5dd7070Spatrick // b> the method belongs to the same context: there is no need to insert a
3351e5dd7070Spatrick // new entry.
3352e5dd7070Spatrick // If the method's declaration does not match the list, we insert it to the
3353e5dd7070Spatrick // end.
3354e5dd7070Spatrick if (!SameDeclaration ||
3355e5dd7070Spatrick !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3356e5dd7070Spatrick // Even if two method types do not match, we would like to say
3357e5dd7070Spatrick // there is more than one declaration so unavailability/deprecated
3358e5dd7070Spatrick // warning is not too noisy.
3359e5dd7070Spatrick if (!Method->isDefined())
3360e5dd7070Spatrick List->setHasMoreThanOneDecl(true);
3361e5dd7070Spatrick
3362e5dd7070Spatrick // For methods with the same declaration, the one that is deprecated
3363e5dd7070Spatrick // should be put in the front for better diagnostics.
3364e5dd7070Spatrick if (Method->isDeprecated() && SameDeclaration &&
3365e5dd7070Spatrick !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3366e5dd7070Spatrick ListWithSameDeclaration = List;
3367e5dd7070Spatrick
3368e5dd7070Spatrick if (Method->isUnavailable() && SameDeclaration &&
3369e5dd7070Spatrick !ListWithSameDeclaration &&
3370e5dd7070Spatrick List->getMethod()->getAvailability() < AR_Deprecated)
3371e5dd7070Spatrick ListWithSameDeclaration = List;
3372e5dd7070Spatrick continue;
3373e5dd7070Spatrick }
3374e5dd7070Spatrick
3375e5dd7070Spatrick ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3376e5dd7070Spatrick
3377e5dd7070Spatrick // Propagate the 'defined' bit.
3378e5dd7070Spatrick if (Method->isDefined())
3379e5dd7070Spatrick PrevObjCMethod->setDefined(true);
3380e5dd7070Spatrick else {
3381e5dd7070Spatrick // Objective-C doesn't allow an @interface for a class after its
3382e5dd7070Spatrick // @implementation. So if Method is not defined and there already is
3383e5dd7070Spatrick // an entry for this type signature, Method has to be for a different
3384e5dd7070Spatrick // class than PrevObjCMethod.
3385e5dd7070Spatrick List->setHasMoreThanOneDecl(true);
3386e5dd7070Spatrick }
3387e5dd7070Spatrick
3388e5dd7070Spatrick // If a method is deprecated, push it in the global pool.
3389e5dd7070Spatrick // This is used for better diagnostics.
3390e5dd7070Spatrick if (Method->isDeprecated()) {
3391e5dd7070Spatrick if (!PrevObjCMethod->isDeprecated())
3392e5dd7070Spatrick List->setMethod(Method);
3393e5dd7070Spatrick }
3394e5dd7070Spatrick // If the new method is unavailable, push it into global pool
3395e5dd7070Spatrick // unless previous one is deprecated.
3396e5dd7070Spatrick if (Method->isUnavailable()) {
3397e5dd7070Spatrick if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3398e5dd7070Spatrick List->setMethod(Method);
3399e5dd7070Spatrick }
3400e5dd7070Spatrick
3401e5dd7070Spatrick return;
3402e5dd7070Spatrick }
3403e5dd7070Spatrick
3404e5dd7070Spatrick // We have a new signature for an existing method - add it.
3405e5dd7070Spatrick // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3406e5dd7070Spatrick ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3407e5dd7070Spatrick
3408e5dd7070Spatrick // We insert it right before ListWithSameDeclaration.
3409e5dd7070Spatrick if (ListWithSameDeclaration) {
3410e5dd7070Spatrick auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3411e5dd7070Spatrick // FIXME: should we clear the other bits in ListWithSameDeclaration?
3412e5dd7070Spatrick ListWithSameDeclaration->setMethod(Method);
3413e5dd7070Spatrick ListWithSameDeclaration->setNext(List);
3414e5dd7070Spatrick return;
3415e5dd7070Spatrick }
3416e5dd7070Spatrick
3417e5dd7070Spatrick Previous->setNext(new (Mem) ObjCMethodList(Method));
3418e5dd7070Spatrick }
3419e5dd7070Spatrick
3420e5dd7070Spatrick /// Read the contents of the method pool for a given selector from
3421e5dd7070Spatrick /// external storage.
ReadMethodPool(Selector Sel)3422e5dd7070Spatrick void Sema::ReadMethodPool(Selector Sel) {
3423e5dd7070Spatrick assert(ExternalSource && "We need an external AST source");
3424e5dd7070Spatrick ExternalSource->ReadMethodPool(Sel);
3425e5dd7070Spatrick }
3426e5dd7070Spatrick
updateOutOfDateSelector(Selector Sel)3427e5dd7070Spatrick void Sema::updateOutOfDateSelector(Selector Sel) {
3428e5dd7070Spatrick if (!ExternalSource)
3429e5dd7070Spatrick return;
3430e5dd7070Spatrick ExternalSource->updateOutOfDateSelector(Sel);
3431e5dd7070Spatrick }
3432e5dd7070Spatrick
AddMethodToGlobalPool(ObjCMethodDecl * Method,bool impl,bool instance)3433e5dd7070Spatrick void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3434e5dd7070Spatrick bool instance) {
3435e5dd7070Spatrick // Ignore methods of invalid containers.
3436e5dd7070Spatrick if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3437e5dd7070Spatrick return;
3438e5dd7070Spatrick
3439e5dd7070Spatrick if (ExternalSource)
3440e5dd7070Spatrick ReadMethodPool(Method->getSelector());
3441e5dd7070Spatrick
3442e5dd7070Spatrick GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3443e5dd7070Spatrick if (Pos == MethodPool.end())
3444*12c85518Srobert Pos = MethodPool
3445*12c85518Srobert .insert(std::make_pair(Method->getSelector(),
3446*12c85518Srobert GlobalMethodPool::Lists()))
3447*12c85518Srobert .first;
3448e5dd7070Spatrick
3449e5dd7070Spatrick Method->setDefined(impl);
3450e5dd7070Spatrick
3451e5dd7070Spatrick ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3452e5dd7070Spatrick addMethodToGlobalList(&Entry, Method);
3453e5dd7070Spatrick }
3454e5dd7070Spatrick
3455e5dd7070Spatrick /// Determines if this is an "acceptable" loose mismatch in the global
3456e5dd7070Spatrick /// method pool. This exists mostly as a hack to get around certain
3457e5dd7070Spatrick /// global mismatches which we can't afford to make warnings / errors.
3458e5dd7070Spatrick /// Really, what we want is a way to take a method out of the global
3459e5dd7070Spatrick /// method pool.
isAcceptableMethodMismatch(ObjCMethodDecl * chosen,ObjCMethodDecl * other)3460e5dd7070Spatrick static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3461e5dd7070Spatrick ObjCMethodDecl *other) {
3462e5dd7070Spatrick if (!chosen->isInstanceMethod())
3463e5dd7070Spatrick return false;
3464e5dd7070Spatrick
3465e5dd7070Spatrick if (chosen->isDirectMethod() != other->isDirectMethod())
3466e5dd7070Spatrick return false;
3467e5dd7070Spatrick
3468e5dd7070Spatrick Selector sel = chosen->getSelector();
3469e5dd7070Spatrick if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3470e5dd7070Spatrick return false;
3471e5dd7070Spatrick
3472e5dd7070Spatrick // Don't complain about mismatches for -length if the method we
3473e5dd7070Spatrick // chose has an integral result type.
3474e5dd7070Spatrick return (chosen->getReturnType()->isIntegerType());
3475e5dd7070Spatrick }
3476e5dd7070Spatrick
3477e5dd7070Spatrick /// Return true if the given method is wthin the type bound.
FilterMethodsByTypeBound(ObjCMethodDecl * Method,const ObjCObjectType * TypeBound)3478e5dd7070Spatrick static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3479e5dd7070Spatrick const ObjCObjectType *TypeBound) {
3480e5dd7070Spatrick if (!TypeBound)
3481e5dd7070Spatrick return true;
3482e5dd7070Spatrick
3483e5dd7070Spatrick if (TypeBound->isObjCId())
3484e5dd7070Spatrick // FIXME: should we handle the case of bounding to id<A, B> differently?
3485e5dd7070Spatrick return true;
3486e5dd7070Spatrick
3487e5dd7070Spatrick auto *BoundInterface = TypeBound->getInterface();
3488e5dd7070Spatrick assert(BoundInterface && "unexpected object type!");
3489e5dd7070Spatrick
3490e5dd7070Spatrick // Check if the Method belongs to a protocol. We should allow any method
3491e5dd7070Spatrick // defined in any protocol, because any subclass could adopt the protocol.
3492e5dd7070Spatrick auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3493e5dd7070Spatrick if (MethodProtocol) {
3494e5dd7070Spatrick return true;
3495e5dd7070Spatrick }
3496e5dd7070Spatrick
3497e5dd7070Spatrick // If the Method belongs to a class, check if it belongs to the class
3498e5dd7070Spatrick // hierarchy of the class bound.
3499e5dd7070Spatrick if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3500e5dd7070Spatrick // We allow methods declared within classes that are part of the hierarchy
3501e5dd7070Spatrick // of the class bound (superclass of, subclass of, or the same as the class
3502e5dd7070Spatrick // bound).
3503e5dd7070Spatrick return MethodInterface == BoundInterface ||
3504e5dd7070Spatrick MethodInterface->isSuperClassOf(BoundInterface) ||
3505e5dd7070Spatrick BoundInterface->isSuperClassOf(MethodInterface);
3506e5dd7070Spatrick }
3507e5dd7070Spatrick llvm_unreachable("unknown method context");
3508e5dd7070Spatrick }
3509e5dd7070Spatrick
3510e5dd7070Spatrick /// We first select the type of the method: Instance or Factory, then collect
3511e5dd7070Spatrick /// all methods with that type.
CollectMultipleMethodsInGlobalPool(Selector Sel,SmallVectorImpl<ObjCMethodDecl * > & Methods,bool InstanceFirst,bool CheckTheOther,const ObjCObjectType * TypeBound)3512e5dd7070Spatrick bool Sema::CollectMultipleMethodsInGlobalPool(
3513e5dd7070Spatrick Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3514e5dd7070Spatrick bool InstanceFirst, bool CheckTheOther,
3515e5dd7070Spatrick const ObjCObjectType *TypeBound) {
3516e5dd7070Spatrick if (ExternalSource)
3517e5dd7070Spatrick ReadMethodPool(Sel);
3518e5dd7070Spatrick
3519e5dd7070Spatrick GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3520e5dd7070Spatrick if (Pos == MethodPool.end())
3521e5dd7070Spatrick return false;
3522e5dd7070Spatrick
3523e5dd7070Spatrick // Gather the non-hidden methods.
3524e5dd7070Spatrick ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3525e5dd7070Spatrick Pos->second.second;
3526e5dd7070Spatrick for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3527ec727ea7Spatrick if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3528e5dd7070Spatrick if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3529e5dd7070Spatrick Methods.push_back(M->getMethod());
3530e5dd7070Spatrick }
3531e5dd7070Spatrick
3532e5dd7070Spatrick // Return if we find any method with the desired kind.
3533e5dd7070Spatrick if (!Methods.empty())
3534e5dd7070Spatrick return Methods.size() > 1;
3535e5dd7070Spatrick
3536e5dd7070Spatrick if (!CheckTheOther)
3537e5dd7070Spatrick return false;
3538e5dd7070Spatrick
3539e5dd7070Spatrick // Gather the other kind.
3540e5dd7070Spatrick ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3541e5dd7070Spatrick Pos->second.first;
3542e5dd7070Spatrick for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3543ec727ea7Spatrick if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3544e5dd7070Spatrick if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3545e5dd7070Spatrick Methods.push_back(M->getMethod());
3546e5dd7070Spatrick }
3547e5dd7070Spatrick
3548e5dd7070Spatrick return Methods.size() > 1;
3549e5dd7070Spatrick }
3550e5dd7070Spatrick
AreMultipleMethodsInGlobalPool(Selector Sel,ObjCMethodDecl * BestMethod,SourceRange R,bool receiverIdOrClass,SmallVectorImpl<ObjCMethodDecl * > & Methods)3551e5dd7070Spatrick bool Sema::AreMultipleMethodsInGlobalPool(
3552e5dd7070Spatrick Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3553e5dd7070Spatrick bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3554e5dd7070Spatrick // Diagnose finding more than one method in global pool.
3555e5dd7070Spatrick SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3556e5dd7070Spatrick FilteredMethods.push_back(BestMethod);
3557e5dd7070Spatrick
3558e5dd7070Spatrick for (auto *M : Methods)
3559e5dd7070Spatrick if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3560e5dd7070Spatrick FilteredMethods.push_back(M);
3561e5dd7070Spatrick
3562e5dd7070Spatrick if (FilteredMethods.size() > 1)
3563e5dd7070Spatrick DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3564e5dd7070Spatrick receiverIdOrClass);
3565e5dd7070Spatrick
3566e5dd7070Spatrick GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3567e5dd7070Spatrick // Test for no method in the pool which should not trigger any warning by
3568e5dd7070Spatrick // caller.
3569e5dd7070Spatrick if (Pos == MethodPool.end())
3570e5dd7070Spatrick return true;
3571e5dd7070Spatrick ObjCMethodList &MethList =
3572e5dd7070Spatrick BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3573e5dd7070Spatrick return MethList.hasMoreThanOneDecl();
3574e5dd7070Spatrick }
3575e5dd7070Spatrick
LookupMethodInGlobalPool(Selector Sel,SourceRange R,bool receiverIdOrClass,bool instance)3576e5dd7070Spatrick ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3577e5dd7070Spatrick bool receiverIdOrClass,
3578e5dd7070Spatrick bool instance) {
3579e5dd7070Spatrick if (ExternalSource)
3580e5dd7070Spatrick ReadMethodPool(Sel);
3581e5dd7070Spatrick
3582e5dd7070Spatrick GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3583e5dd7070Spatrick if (Pos == MethodPool.end())
3584e5dd7070Spatrick return nullptr;
3585e5dd7070Spatrick
3586e5dd7070Spatrick // Gather the non-hidden methods.
3587e5dd7070Spatrick ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3588e5dd7070Spatrick SmallVector<ObjCMethodDecl *, 4> Methods;
3589e5dd7070Spatrick for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3590ec727ea7Spatrick if (M->getMethod() && M->getMethod()->isUnconditionallyVisible())
3591e5dd7070Spatrick return M->getMethod();
3592e5dd7070Spatrick }
3593e5dd7070Spatrick return nullptr;
3594e5dd7070Spatrick }
3595e5dd7070Spatrick
DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl * > & Methods,Selector Sel,SourceRange R,bool receiverIdOrClass)3596e5dd7070Spatrick void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3597e5dd7070Spatrick Selector Sel, SourceRange R,
3598e5dd7070Spatrick bool receiverIdOrClass) {
3599e5dd7070Spatrick // We found multiple methods, so we may have to complain.
3600e5dd7070Spatrick bool issueDiagnostic = false, issueError = false;
3601e5dd7070Spatrick
3602e5dd7070Spatrick // We support a warning which complains about *any* difference in
3603e5dd7070Spatrick // method signature.
3604e5dd7070Spatrick bool strictSelectorMatch =
3605e5dd7070Spatrick receiverIdOrClass &&
3606e5dd7070Spatrick !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3607e5dd7070Spatrick if (strictSelectorMatch) {
3608e5dd7070Spatrick for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3609e5dd7070Spatrick if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3610e5dd7070Spatrick issueDiagnostic = true;
3611e5dd7070Spatrick break;
3612e5dd7070Spatrick }
3613e5dd7070Spatrick }
3614e5dd7070Spatrick }
3615e5dd7070Spatrick
3616e5dd7070Spatrick // If we didn't see any strict differences, we won't see any loose
3617e5dd7070Spatrick // differences. In ARC, however, we also need to check for loose
3618e5dd7070Spatrick // mismatches, because most of them are errors.
3619e5dd7070Spatrick if (!strictSelectorMatch ||
3620e5dd7070Spatrick (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3621e5dd7070Spatrick for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3622e5dd7070Spatrick // This checks if the methods differ in type mismatch.
3623e5dd7070Spatrick if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3624e5dd7070Spatrick !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3625e5dd7070Spatrick issueDiagnostic = true;
3626e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount)
3627e5dd7070Spatrick issueError = true;
3628e5dd7070Spatrick break;
3629e5dd7070Spatrick }
3630e5dd7070Spatrick }
3631e5dd7070Spatrick
3632e5dd7070Spatrick if (issueDiagnostic) {
3633e5dd7070Spatrick if (issueError)
3634e5dd7070Spatrick Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3635e5dd7070Spatrick else if (strictSelectorMatch)
3636e5dd7070Spatrick Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3637e5dd7070Spatrick else
3638e5dd7070Spatrick Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3639e5dd7070Spatrick
3640e5dd7070Spatrick Diag(Methods[0]->getBeginLoc(),
3641e5dd7070Spatrick issueError ? diag::note_possibility : diag::note_using)
3642e5dd7070Spatrick << Methods[0]->getSourceRange();
3643e5dd7070Spatrick for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3644e5dd7070Spatrick Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3645e5dd7070Spatrick << Methods[I]->getSourceRange();
3646e5dd7070Spatrick }
3647e5dd7070Spatrick }
3648e5dd7070Spatrick }
3649e5dd7070Spatrick
LookupImplementedMethodInGlobalPool(Selector Sel)3650e5dd7070Spatrick ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3651e5dd7070Spatrick GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3652e5dd7070Spatrick if (Pos == MethodPool.end())
3653e5dd7070Spatrick return nullptr;
3654e5dd7070Spatrick
3655*12c85518Srobert GlobalMethodPool::Lists &Methods = Pos->second;
3656e5dd7070Spatrick for (const ObjCMethodList *Method = &Methods.first; Method;
3657e5dd7070Spatrick Method = Method->getNext())
3658e5dd7070Spatrick if (Method->getMethod() &&
3659e5dd7070Spatrick (Method->getMethod()->isDefined() ||
3660e5dd7070Spatrick Method->getMethod()->isPropertyAccessor()))
3661e5dd7070Spatrick return Method->getMethod();
3662e5dd7070Spatrick
3663e5dd7070Spatrick for (const ObjCMethodList *Method = &Methods.second; Method;
3664e5dd7070Spatrick Method = Method->getNext())
3665e5dd7070Spatrick if (Method->getMethod() &&
3666e5dd7070Spatrick (Method->getMethod()->isDefined() ||
3667e5dd7070Spatrick Method->getMethod()->isPropertyAccessor()))
3668e5dd7070Spatrick return Method->getMethod();
3669e5dd7070Spatrick return nullptr;
3670e5dd7070Spatrick }
3671e5dd7070Spatrick
3672e5dd7070Spatrick static void
HelperSelectorsForTypoCorrection(SmallVectorImpl<const ObjCMethodDecl * > & BestMethod,StringRef Typo,const ObjCMethodDecl * Method)3673e5dd7070Spatrick HelperSelectorsForTypoCorrection(
3674e5dd7070Spatrick SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3675e5dd7070Spatrick StringRef Typo, const ObjCMethodDecl * Method) {
3676e5dd7070Spatrick const unsigned MaxEditDistance = 1;
3677e5dd7070Spatrick unsigned BestEditDistance = MaxEditDistance + 1;
3678e5dd7070Spatrick std::string MethodName = Method->getSelector().getAsString();
3679e5dd7070Spatrick
3680e5dd7070Spatrick unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3681e5dd7070Spatrick if (MinPossibleEditDistance > 0 &&
3682e5dd7070Spatrick Typo.size() / MinPossibleEditDistance < 1)
3683e5dd7070Spatrick return;
3684e5dd7070Spatrick unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3685e5dd7070Spatrick if (EditDistance > MaxEditDistance)
3686e5dd7070Spatrick return;
3687e5dd7070Spatrick if (EditDistance == BestEditDistance)
3688e5dd7070Spatrick BestMethod.push_back(Method);
3689e5dd7070Spatrick else if (EditDistance < BestEditDistance) {
3690e5dd7070Spatrick BestMethod.clear();
3691e5dd7070Spatrick BestMethod.push_back(Method);
3692e5dd7070Spatrick }
3693e5dd7070Spatrick }
3694e5dd7070Spatrick
HelperIsMethodInObjCType(Sema & S,Selector Sel,QualType ObjectType)3695e5dd7070Spatrick static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3696e5dd7070Spatrick QualType ObjectType) {
3697e5dd7070Spatrick if (ObjectType.isNull())
3698e5dd7070Spatrick return true;
3699e5dd7070Spatrick if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3700e5dd7070Spatrick return true;
3701e5dd7070Spatrick return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3702e5dd7070Spatrick nullptr;
3703e5dd7070Spatrick }
3704e5dd7070Spatrick
3705e5dd7070Spatrick const ObjCMethodDecl *
SelectorsForTypoCorrection(Selector Sel,QualType ObjectType)3706e5dd7070Spatrick Sema::SelectorsForTypoCorrection(Selector Sel,
3707e5dd7070Spatrick QualType ObjectType) {
3708e5dd7070Spatrick unsigned NumArgs = Sel.getNumArgs();
3709e5dd7070Spatrick SmallVector<const ObjCMethodDecl *, 8> Methods;
3710e5dd7070Spatrick bool ObjectIsId = true, ObjectIsClass = true;
3711e5dd7070Spatrick if (ObjectType.isNull())
3712e5dd7070Spatrick ObjectIsId = ObjectIsClass = false;
3713e5dd7070Spatrick else if (!ObjectType->isObjCObjectPointerType())
3714e5dd7070Spatrick return nullptr;
3715e5dd7070Spatrick else if (const ObjCObjectPointerType *ObjCPtr =
3716e5dd7070Spatrick ObjectType->getAsObjCInterfacePointerType()) {
3717e5dd7070Spatrick ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3718e5dd7070Spatrick ObjectIsId = ObjectIsClass = false;
3719e5dd7070Spatrick }
3720e5dd7070Spatrick else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3721e5dd7070Spatrick ObjectIsClass = false;
3722e5dd7070Spatrick else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3723e5dd7070Spatrick ObjectIsId = false;
3724e5dd7070Spatrick else
3725e5dd7070Spatrick return nullptr;
3726e5dd7070Spatrick
3727e5dd7070Spatrick for (GlobalMethodPool::iterator b = MethodPool.begin(),
3728e5dd7070Spatrick e = MethodPool.end(); b != e; b++) {
3729e5dd7070Spatrick // instance methods
3730e5dd7070Spatrick for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3731e5dd7070Spatrick if (M->getMethod() &&
3732e5dd7070Spatrick (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3733e5dd7070Spatrick (M->getMethod()->getSelector() != Sel)) {
3734e5dd7070Spatrick if (ObjectIsId)
3735e5dd7070Spatrick Methods.push_back(M->getMethod());
3736e5dd7070Spatrick else if (!ObjectIsClass &&
3737e5dd7070Spatrick HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3738e5dd7070Spatrick ObjectType))
3739e5dd7070Spatrick Methods.push_back(M->getMethod());
3740e5dd7070Spatrick }
3741e5dd7070Spatrick // class methods
3742e5dd7070Spatrick for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3743e5dd7070Spatrick if (M->getMethod() &&
3744e5dd7070Spatrick (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3745e5dd7070Spatrick (M->getMethod()->getSelector() != Sel)) {
3746e5dd7070Spatrick if (ObjectIsClass)
3747e5dd7070Spatrick Methods.push_back(M->getMethod());
3748e5dd7070Spatrick else if (!ObjectIsId &&
3749e5dd7070Spatrick HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3750e5dd7070Spatrick ObjectType))
3751e5dd7070Spatrick Methods.push_back(M->getMethod());
3752e5dd7070Spatrick }
3753e5dd7070Spatrick }
3754e5dd7070Spatrick
3755e5dd7070Spatrick SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3756e5dd7070Spatrick for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3757e5dd7070Spatrick HelperSelectorsForTypoCorrection(SelectedMethods,
3758e5dd7070Spatrick Sel.getAsString(), Methods[i]);
3759e5dd7070Spatrick }
3760e5dd7070Spatrick return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3761e5dd7070Spatrick }
3762e5dd7070Spatrick
3763e5dd7070Spatrick /// DiagnoseDuplicateIvars -
3764e5dd7070Spatrick /// Check for duplicate ivars in the entire class at the start of
3765*12c85518Srobert /// \@implementation. This becomes necessary because class extension can
3766e5dd7070Spatrick /// add ivars to a class in random order which will not be known until
3767e5dd7070Spatrick /// class's \@implementation is seen.
DiagnoseDuplicateIvars(ObjCInterfaceDecl * ID,ObjCInterfaceDecl * SID)3768e5dd7070Spatrick void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3769e5dd7070Spatrick ObjCInterfaceDecl *SID) {
3770e5dd7070Spatrick for (auto *Ivar : ID->ivars()) {
3771e5dd7070Spatrick if (Ivar->isInvalidDecl())
3772e5dd7070Spatrick continue;
3773e5dd7070Spatrick if (IdentifierInfo *II = Ivar->getIdentifier()) {
3774e5dd7070Spatrick ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3775e5dd7070Spatrick if (prevIvar) {
3776e5dd7070Spatrick Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3777e5dd7070Spatrick Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3778e5dd7070Spatrick Ivar->setInvalidDecl();
3779e5dd7070Spatrick }
3780e5dd7070Spatrick }
3781e5dd7070Spatrick }
3782e5dd7070Spatrick }
3783e5dd7070Spatrick
3784e5dd7070Spatrick /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
DiagnoseWeakIvars(Sema & S,ObjCImplementationDecl * ID)3785e5dd7070Spatrick static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3786e5dd7070Spatrick if (S.getLangOpts().ObjCWeak) return;
3787e5dd7070Spatrick
3788e5dd7070Spatrick for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3789e5dd7070Spatrick ivar; ivar = ivar->getNextIvar()) {
3790e5dd7070Spatrick if (ivar->isInvalidDecl()) continue;
3791e5dd7070Spatrick if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3792e5dd7070Spatrick if (S.getLangOpts().ObjCWeakRuntime) {
3793e5dd7070Spatrick S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3794e5dd7070Spatrick } else {
3795e5dd7070Spatrick S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3796e5dd7070Spatrick }
3797e5dd7070Spatrick }
3798e5dd7070Spatrick }
3799e5dd7070Spatrick }
3800e5dd7070Spatrick
3801e5dd7070Spatrick /// Diagnose attempts to use flexible array member with retainable object type.
DiagnoseRetainableFlexibleArrayMember(Sema & S,ObjCInterfaceDecl * ID)3802e5dd7070Spatrick static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3803e5dd7070Spatrick ObjCInterfaceDecl *ID) {
3804e5dd7070Spatrick if (!S.getLangOpts().ObjCAutoRefCount)
3805e5dd7070Spatrick return;
3806e5dd7070Spatrick
3807e5dd7070Spatrick for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3808e5dd7070Spatrick ivar = ivar->getNextIvar()) {
3809e5dd7070Spatrick if (ivar->isInvalidDecl())
3810e5dd7070Spatrick continue;
3811e5dd7070Spatrick QualType IvarTy = ivar->getType();
3812e5dd7070Spatrick if (IvarTy->isIncompleteArrayType() &&
3813e5dd7070Spatrick (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3814e5dd7070Spatrick IvarTy->isObjCLifetimeType()) {
3815e5dd7070Spatrick S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3816e5dd7070Spatrick ivar->setInvalidDecl();
3817e5dd7070Spatrick }
3818e5dd7070Spatrick }
3819e5dd7070Spatrick }
3820e5dd7070Spatrick
getObjCContainerKind() const3821e5dd7070Spatrick Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3822e5dd7070Spatrick switch (CurContext->getDeclKind()) {
3823e5dd7070Spatrick case Decl::ObjCInterface:
3824e5dd7070Spatrick return Sema::OCK_Interface;
3825e5dd7070Spatrick case Decl::ObjCProtocol:
3826e5dd7070Spatrick return Sema::OCK_Protocol;
3827e5dd7070Spatrick case Decl::ObjCCategory:
3828e5dd7070Spatrick if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3829e5dd7070Spatrick return Sema::OCK_ClassExtension;
3830e5dd7070Spatrick return Sema::OCK_Category;
3831e5dd7070Spatrick case Decl::ObjCImplementation:
3832e5dd7070Spatrick return Sema::OCK_Implementation;
3833e5dd7070Spatrick case Decl::ObjCCategoryImpl:
3834e5dd7070Spatrick return Sema::OCK_CategoryImplementation;
3835e5dd7070Spatrick
3836e5dd7070Spatrick default:
3837e5dd7070Spatrick return Sema::OCK_None;
3838e5dd7070Spatrick }
3839e5dd7070Spatrick }
3840e5dd7070Spatrick
IsVariableSizedType(QualType T)3841e5dd7070Spatrick static bool IsVariableSizedType(QualType T) {
3842e5dd7070Spatrick if (T->isIncompleteArrayType())
3843e5dd7070Spatrick return true;
3844e5dd7070Spatrick const auto *RecordTy = T->getAs<RecordType>();
3845e5dd7070Spatrick return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3846e5dd7070Spatrick }
3847e5dd7070Spatrick
DiagnoseVariableSizedIvars(Sema & S,ObjCContainerDecl * OCD)3848e5dd7070Spatrick static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3849e5dd7070Spatrick ObjCInterfaceDecl *IntfDecl = nullptr;
3850e5dd7070Spatrick ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3851e5dd7070Spatrick ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3852e5dd7070Spatrick if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3853e5dd7070Spatrick Ivars = IntfDecl->ivars();
3854e5dd7070Spatrick } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3855e5dd7070Spatrick IntfDecl = ImplDecl->getClassInterface();
3856e5dd7070Spatrick Ivars = ImplDecl->ivars();
3857e5dd7070Spatrick } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3858e5dd7070Spatrick if (CategoryDecl->IsClassExtension()) {
3859e5dd7070Spatrick IntfDecl = CategoryDecl->getClassInterface();
3860e5dd7070Spatrick Ivars = CategoryDecl->ivars();
3861e5dd7070Spatrick }
3862e5dd7070Spatrick }
3863e5dd7070Spatrick
3864e5dd7070Spatrick // Check if variable sized ivar is in interface and visible to subclasses.
3865e5dd7070Spatrick if (!isa<ObjCInterfaceDecl>(OCD)) {
3866*12c85518Srobert for (auto *ivar : Ivars) {
3867e5dd7070Spatrick if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3868e5dd7070Spatrick S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3869e5dd7070Spatrick << ivar->getDeclName() << ivar->getType();
3870e5dd7070Spatrick }
3871e5dd7070Spatrick }
3872e5dd7070Spatrick }
3873e5dd7070Spatrick
3874e5dd7070Spatrick // Subsequent checks require interface decl.
3875e5dd7070Spatrick if (!IntfDecl)
3876e5dd7070Spatrick return;
3877e5dd7070Spatrick
3878e5dd7070Spatrick // Check if variable sized ivar is followed by another ivar.
3879e5dd7070Spatrick for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3880e5dd7070Spatrick ivar = ivar->getNextIvar()) {
3881e5dd7070Spatrick if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3882e5dd7070Spatrick continue;
3883e5dd7070Spatrick QualType IvarTy = ivar->getType();
3884e5dd7070Spatrick bool IsInvalidIvar = false;
3885e5dd7070Spatrick if (IvarTy->isIncompleteArrayType()) {
3886e5dd7070Spatrick S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3887e5dd7070Spatrick << ivar->getDeclName() << IvarTy
3888e5dd7070Spatrick << TTK_Class; // Use "class" for Obj-C.
3889e5dd7070Spatrick IsInvalidIvar = true;
3890e5dd7070Spatrick } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3891e5dd7070Spatrick if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3892e5dd7070Spatrick S.Diag(ivar->getLocation(),
3893e5dd7070Spatrick diag::err_objc_variable_sized_type_not_at_end)
3894e5dd7070Spatrick << ivar->getDeclName() << IvarTy;
3895e5dd7070Spatrick IsInvalidIvar = true;
3896e5dd7070Spatrick }
3897e5dd7070Spatrick }
3898e5dd7070Spatrick if (IsInvalidIvar) {
3899e5dd7070Spatrick S.Diag(ivar->getNextIvar()->getLocation(),
3900e5dd7070Spatrick diag::note_next_ivar_declaration)
3901e5dd7070Spatrick << ivar->getNextIvar()->getSynthesize();
3902e5dd7070Spatrick ivar->setInvalidDecl();
3903e5dd7070Spatrick }
3904e5dd7070Spatrick }
3905e5dd7070Spatrick
3906e5dd7070Spatrick // Check if ObjC container adds ivars after variable sized ivar in superclass.
3907e5dd7070Spatrick // Perform the check only if OCD is the first container to declare ivars to
3908e5dd7070Spatrick // avoid multiple warnings for the same ivar.
3909e5dd7070Spatrick ObjCIvarDecl *FirstIvar =
3910e5dd7070Spatrick (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3911e5dd7070Spatrick if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3912e5dd7070Spatrick const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3913e5dd7070Spatrick while (SuperClass && SuperClass->ivar_empty())
3914e5dd7070Spatrick SuperClass = SuperClass->getSuperClass();
3915e5dd7070Spatrick if (SuperClass) {
3916e5dd7070Spatrick auto IvarIter = SuperClass->ivar_begin();
3917e5dd7070Spatrick std::advance(IvarIter, SuperClass->ivar_size() - 1);
3918e5dd7070Spatrick const ObjCIvarDecl *LastIvar = *IvarIter;
3919e5dd7070Spatrick if (IsVariableSizedType(LastIvar->getType())) {
3920e5dd7070Spatrick S.Diag(FirstIvar->getLocation(),
3921e5dd7070Spatrick diag::warn_superclass_variable_sized_type_not_at_end)
3922e5dd7070Spatrick << FirstIvar->getDeclName() << LastIvar->getDeclName()
3923e5dd7070Spatrick << LastIvar->getType() << SuperClass->getDeclName();
3924e5dd7070Spatrick S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3925e5dd7070Spatrick << LastIvar->getDeclName();
3926e5dd7070Spatrick }
3927e5dd7070Spatrick }
3928e5dd7070Spatrick }
3929e5dd7070Spatrick }
3930e5dd7070Spatrick
3931a9ac8606Spatrick static void DiagnoseCategoryDirectMembersProtocolConformance(
3932a9ac8606Spatrick Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
3933a9ac8606Spatrick
DiagnoseCategoryDirectMembersProtocolConformance(Sema & S,ObjCCategoryDecl * CDecl,const llvm::iterator_range<ObjCProtocolList::iterator> & Protocols)3934a9ac8606Spatrick static void DiagnoseCategoryDirectMembersProtocolConformance(
3935a9ac8606Spatrick Sema &S, ObjCCategoryDecl *CDecl,
3936a9ac8606Spatrick const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
3937a9ac8606Spatrick for (auto *PI : Protocols)
3938a9ac8606Spatrick DiagnoseCategoryDirectMembersProtocolConformance(S, PI, CDecl);
3939a9ac8606Spatrick }
3940a9ac8606Spatrick
DiagnoseCategoryDirectMembersProtocolConformance(Sema & S,ObjCProtocolDecl * PDecl,ObjCCategoryDecl * CDecl)3941a9ac8606Spatrick static void DiagnoseCategoryDirectMembersProtocolConformance(
3942a9ac8606Spatrick Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
3943a9ac8606Spatrick if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
3944a9ac8606Spatrick PDecl = PDecl->getDefinition();
3945a9ac8606Spatrick
3946a9ac8606Spatrick llvm::SmallVector<const Decl *, 4> DirectMembers;
3947a9ac8606Spatrick const auto *IDecl = CDecl->getClassInterface();
3948a9ac8606Spatrick for (auto *MD : PDecl->methods()) {
3949a9ac8606Spatrick if (!MD->isPropertyAccessor()) {
3950a9ac8606Spatrick if (const auto *CMD =
3951a9ac8606Spatrick IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
3952a9ac8606Spatrick if (CMD->isDirectMethod())
3953a9ac8606Spatrick DirectMembers.push_back(CMD);
3954a9ac8606Spatrick }
3955a9ac8606Spatrick }
3956a9ac8606Spatrick }
3957a9ac8606Spatrick for (auto *PD : PDecl->properties()) {
3958a9ac8606Spatrick if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
3959a9ac8606Spatrick PD->getIdentifier(),
3960a9ac8606Spatrick PD->isClassProperty()
3961a9ac8606Spatrick ? ObjCPropertyQueryKind::OBJC_PR_query_class
3962a9ac8606Spatrick : ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
3963a9ac8606Spatrick if (CPD->isDirectProperty())
3964a9ac8606Spatrick DirectMembers.push_back(CPD);
3965a9ac8606Spatrick }
3966a9ac8606Spatrick }
3967a9ac8606Spatrick if (!DirectMembers.empty()) {
3968a9ac8606Spatrick S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
3969a9ac8606Spatrick << CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
3970a9ac8606Spatrick for (const auto *MD : DirectMembers)
3971a9ac8606Spatrick S.Diag(MD->getLocation(), diag::note_direct_member_here);
3972a9ac8606Spatrick return;
3973a9ac8606Spatrick }
3974a9ac8606Spatrick
3975a9ac8606Spatrick // Check on this protocols's referenced protocols, recursively.
3976a9ac8606Spatrick DiagnoseCategoryDirectMembersProtocolConformance(S, CDecl,
3977a9ac8606Spatrick PDecl->protocols());
3978a9ac8606Spatrick }
3979a9ac8606Spatrick
3980e5dd7070Spatrick // Note: For class/category implementations, allMethods is always null.
ActOnAtEnd(Scope * S,SourceRange AtEnd,ArrayRef<Decl * > allMethods,ArrayRef<DeclGroupPtrTy> allTUVars)3981e5dd7070Spatrick Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3982e5dd7070Spatrick ArrayRef<DeclGroupPtrTy> allTUVars) {
3983e5dd7070Spatrick if (getObjCContainerKind() == Sema::OCK_None)
3984e5dd7070Spatrick return nullptr;
3985e5dd7070Spatrick
3986e5dd7070Spatrick assert(AtEnd.isValid() && "Invalid location for '@end'");
3987e5dd7070Spatrick
3988e5dd7070Spatrick auto *OCD = cast<ObjCContainerDecl>(CurContext);
3989e5dd7070Spatrick Decl *ClassDecl = OCD;
3990e5dd7070Spatrick
3991e5dd7070Spatrick bool isInterfaceDeclKind =
3992e5dd7070Spatrick isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3993e5dd7070Spatrick || isa<ObjCProtocolDecl>(ClassDecl);
3994e5dd7070Spatrick bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3995e5dd7070Spatrick
3996e5dd7070Spatrick // Make synthesized accessor stub functions visible.
3997e5dd7070Spatrick // ActOnPropertyImplDecl() creates them as not visible in case
3998e5dd7070Spatrick // they are overridden by an explicit method that is encountered
3999e5dd7070Spatrick // later.
4000e5dd7070Spatrick if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) {
4001*12c85518Srobert for (auto *PropImpl : OID->property_impls()) {
4002e5dd7070Spatrick if (auto *Getter = PropImpl->getGetterMethodDecl())
4003a9ac8606Spatrick if (Getter->isSynthesizedAccessorStub())
4004e5dd7070Spatrick OID->addDecl(Getter);
4005e5dd7070Spatrick if (auto *Setter = PropImpl->getSetterMethodDecl())
4006a9ac8606Spatrick if (Setter->isSynthesizedAccessorStub())
4007e5dd7070Spatrick OID->addDecl(Setter);
4008e5dd7070Spatrick }
4009e5dd7070Spatrick }
4010e5dd7070Spatrick
4011e5dd7070Spatrick // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
4012e5dd7070Spatrick llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
4013e5dd7070Spatrick llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
4014e5dd7070Spatrick
4015e5dd7070Spatrick for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
4016e5dd7070Spatrick ObjCMethodDecl *Method =
4017e5dd7070Spatrick cast_or_null<ObjCMethodDecl>(allMethods[i]);
4018e5dd7070Spatrick
4019e5dd7070Spatrick if (!Method) continue; // Already issued a diagnostic.
4020e5dd7070Spatrick if (Method->isInstanceMethod()) {
4021e5dd7070Spatrick /// Check for instance method of the same name with incompatible types
4022e5dd7070Spatrick const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
4023e5dd7070Spatrick bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4024e5dd7070Spatrick : false;
4025e5dd7070Spatrick if ((isInterfaceDeclKind && PrevMethod && !match)
4026e5dd7070Spatrick || (checkIdenticalMethods && match)) {
4027e5dd7070Spatrick Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4028e5dd7070Spatrick << Method->getDeclName();
4029e5dd7070Spatrick Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4030e5dd7070Spatrick Method->setInvalidDecl();
4031e5dd7070Spatrick } else {
4032e5dd7070Spatrick if (PrevMethod) {
4033e5dd7070Spatrick Method->setAsRedeclaration(PrevMethod);
4034e5dd7070Spatrick if (!Context.getSourceManager().isInSystemHeader(
4035e5dd7070Spatrick Method->getLocation()))
4036e5dd7070Spatrick Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4037e5dd7070Spatrick << Method->getDeclName();
4038e5dd7070Spatrick Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4039e5dd7070Spatrick }
4040e5dd7070Spatrick InsMap[Method->getSelector()] = Method;
4041e5dd7070Spatrick /// The following allows us to typecheck messages to "id".
4042e5dd7070Spatrick AddInstanceMethodToGlobalPool(Method);
4043e5dd7070Spatrick }
4044e5dd7070Spatrick } else {
4045e5dd7070Spatrick /// Check for class method of the same name with incompatible types
4046e5dd7070Spatrick const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
4047e5dd7070Spatrick bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4048e5dd7070Spatrick : false;
4049e5dd7070Spatrick if ((isInterfaceDeclKind && PrevMethod && !match)
4050e5dd7070Spatrick || (checkIdenticalMethods && match)) {
4051e5dd7070Spatrick Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4052e5dd7070Spatrick << Method->getDeclName();
4053e5dd7070Spatrick Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4054e5dd7070Spatrick Method->setInvalidDecl();
4055e5dd7070Spatrick } else {
4056e5dd7070Spatrick if (PrevMethod) {
4057e5dd7070Spatrick Method->setAsRedeclaration(PrevMethod);
4058e5dd7070Spatrick if (!Context.getSourceManager().isInSystemHeader(
4059e5dd7070Spatrick Method->getLocation()))
4060e5dd7070Spatrick Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4061e5dd7070Spatrick << Method->getDeclName();
4062e5dd7070Spatrick Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4063e5dd7070Spatrick }
4064e5dd7070Spatrick ClsMap[Method->getSelector()] = Method;
4065e5dd7070Spatrick AddFactoryMethodToGlobalPool(Method);
4066e5dd7070Spatrick }
4067e5dd7070Spatrick }
4068e5dd7070Spatrick }
4069e5dd7070Spatrick if (isa<ObjCInterfaceDecl>(ClassDecl)) {
4070e5dd7070Spatrick // Nothing to do here.
4071e5dd7070Spatrick } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
4072e5dd7070Spatrick // Categories are used to extend the class by declaring new methods.
4073e5dd7070Spatrick // By the same token, they are also used to add new properties. No
4074e5dd7070Spatrick // need to compare the added property to those in the class.
4075e5dd7070Spatrick
4076e5dd7070Spatrick if (C->IsClassExtension()) {
4077e5dd7070Spatrick ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
4078e5dd7070Spatrick DiagnoseClassExtensionDupMethods(C, CCPrimary);
4079e5dd7070Spatrick }
4080a9ac8606Spatrick
4081a9ac8606Spatrick DiagnoseCategoryDirectMembersProtocolConformance(*this, C, C->protocols());
4082e5dd7070Spatrick }
4083e5dd7070Spatrick if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
4084e5dd7070Spatrick if (CDecl->getIdentifier())
4085e5dd7070Spatrick // ProcessPropertyDecl is responsible for diagnosing conflicts with any
4086e5dd7070Spatrick // user-defined setter/getter. It also synthesizes setter/getter methods
4087e5dd7070Spatrick // and adds them to the DeclContext and global method pools.
4088e5dd7070Spatrick for (auto *I : CDecl->properties())
4089e5dd7070Spatrick ProcessPropertyDecl(I);
4090e5dd7070Spatrick CDecl->setAtEndRange(AtEnd);
4091e5dd7070Spatrick }
4092e5dd7070Spatrick if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
4093e5dd7070Spatrick IC->setAtEndRange(AtEnd);
4094e5dd7070Spatrick if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
4095e5dd7070Spatrick // Any property declared in a class extension might have user
4096e5dd7070Spatrick // declared setter or getter in current class extension or one
4097e5dd7070Spatrick // of the other class extensions. Mark them as synthesized as
4098e5dd7070Spatrick // property will be synthesized when property with same name is
4099e5dd7070Spatrick // seen in the @implementation.
4100e5dd7070Spatrick for (const auto *Ext : IDecl->visible_extensions()) {
4101e5dd7070Spatrick for (const auto *Property : Ext->instance_properties()) {
4102e5dd7070Spatrick // Skip over properties declared @dynamic
4103e5dd7070Spatrick if (const ObjCPropertyImplDecl *PIDecl
4104e5dd7070Spatrick = IC->FindPropertyImplDecl(Property->getIdentifier(),
4105e5dd7070Spatrick Property->getQueryKind()))
4106e5dd7070Spatrick if (PIDecl->getPropertyImplementation()
4107e5dd7070Spatrick == ObjCPropertyImplDecl::Dynamic)
4108e5dd7070Spatrick continue;
4109e5dd7070Spatrick
4110e5dd7070Spatrick for (const auto *Ext : IDecl->visible_extensions()) {
4111e5dd7070Spatrick if (ObjCMethodDecl *GetterMethod =
4112e5dd7070Spatrick Ext->getInstanceMethod(Property->getGetterName()))
4113e5dd7070Spatrick GetterMethod->setPropertyAccessor(true);
4114e5dd7070Spatrick if (!Property->isReadOnly())
4115e5dd7070Spatrick if (ObjCMethodDecl *SetterMethod
4116e5dd7070Spatrick = Ext->getInstanceMethod(Property->getSetterName()))
4117e5dd7070Spatrick SetterMethod->setPropertyAccessor(true);
4118e5dd7070Spatrick }
4119e5dd7070Spatrick }
4120e5dd7070Spatrick }
4121e5dd7070Spatrick ImplMethodsVsClassMethods(S, IC, IDecl);
4122e5dd7070Spatrick AtomicPropertySetterGetterRules(IC, IDecl);
4123e5dd7070Spatrick DiagnoseOwningPropertyGetterSynthesis(IC);
4124e5dd7070Spatrick DiagnoseUnusedBackingIvarInAccessor(S, IC);
4125e5dd7070Spatrick if (IDecl->hasDesignatedInitializers())
4126e5dd7070Spatrick DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
4127e5dd7070Spatrick DiagnoseWeakIvars(*this, IC);
4128e5dd7070Spatrick DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
4129e5dd7070Spatrick
4130e5dd7070Spatrick bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4131e5dd7070Spatrick if (IDecl->getSuperClass() == nullptr) {
4132e5dd7070Spatrick // This class has no superclass, so check that it has been marked with
4133e5dd7070Spatrick // __attribute((objc_root_class)).
4134e5dd7070Spatrick if (!HasRootClassAttr) {
4135e5dd7070Spatrick SourceLocation DeclLoc(IDecl->getLocation());
4136e5dd7070Spatrick SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
4137e5dd7070Spatrick Diag(DeclLoc, diag::warn_objc_root_class_missing)
4138e5dd7070Spatrick << IDecl->getIdentifier();
4139e5dd7070Spatrick // See if NSObject is in the current scope, and if it is, suggest
4140e5dd7070Spatrick // adding " : NSObject " to the class declaration.
4141e5dd7070Spatrick NamedDecl *IF = LookupSingleName(TUScope,
4142e5dd7070Spatrick NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4143e5dd7070Spatrick DeclLoc, LookupOrdinaryName);
4144e5dd7070Spatrick ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4145e5dd7070Spatrick if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4146e5dd7070Spatrick Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4147e5dd7070Spatrick << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4148e5dd7070Spatrick } else {
4149e5dd7070Spatrick Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4150e5dd7070Spatrick }
4151e5dd7070Spatrick }
4152e5dd7070Spatrick } else if (HasRootClassAttr) {
4153e5dd7070Spatrick // Complain that only root classes may have this attribute.
4154e5dd7070Spatrick Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4155e5dd7070Spatrick }
4156e5dd7070Spatrick
4157e5dd7070Spatrick if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4158e5dd7070Spatrick // An interface can subclass another interface with a
4159e5dd7070Spatrick // objc_subclassing_restricted attribute when it has that attribute as
4160e5dd7070Spatrick // well (because of interfaces imported from Swift). Therefore we have
4161e5dd7070Spatrick // to check if we can subclass in the implementation as well.
4162e5dd7070Spatrick if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4163e5dd7070Spatrick Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4164e5dd7070Spatrick Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4165e5dd7070Spatrick Diag(Super->getLocation(), diag::note_class_declared);
4166e5dd7070Spatrick }
4167e5dd7070Spatrick }
4168e5dd7070Spatrick
4169e5dd7070Spatrick if (IDecl->hasAttr<ObjCClassStubAttr>())
4170e5dd7070Spatrick Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4171e5dd7070Spatrick
4172e5dd7070Spatrick if (LangOpts.ObjCRuntime.isNonFragile()) {
4173e5dd7070Spatrick while (IDecl->getSuperClass()) {
4174e5dd7070Spatrick DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4175e5dd7070Spatrick IDecl = IDecl->getSuperClass();
4176e5dd7070Spatrick }
4177e5dd7070Spatrick }
4178e5dd7070Spatrick }
4179e5dd7070Spatrick SetIvarInitializers(IC);
4180e5dd7070Spatrick } else if (ObjCCategoryImplDecl* CatImplClass =
4181e5dd7070Spatrick dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4182e5dd7070Spatrick CatImplClass->setAtEndRange(AtEnd);
4183e5dd7070Spatrick
4184e5dd7070Spatrick // Find category interface decl and then check that all methods declared
4185e5dd7070Spatrick // in this interface are implemented in the category @implementation.
4186e5dd7070Spatrick if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4187e5dd7070Spatrick if (ObjCCategoryDecl *Cat
4188e5dd7070Spatrick = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4189e5dd7070Spatrick ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4190e5dd7070Spatrick }
4191e5dd7070Spatrick }
4192e5dd7070Spatrick } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4193e5dd7070Spatrick if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4194e5dd7070Spatrick if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4195e5dd7070Spatrick Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4196e5dd7070Spatrick Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4197e5dd7070Spatrick Diag(Super->getLocation(), diag::note_class_declared);
4198e5dd7070Spatrick }
4199e5dd7070Spatrick }
4200e5dd7070Spatrick
4201e5dd7070Spatrick if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4202e5dd7070Spatrick !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
4203e5dd7070Spatrick Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
4204e5dd7070Spatrick }
4205e5dd7070Spatrick DiagnoseVariableSizedIvars(*this, OCD);
4206e5dd7070Spatrick if (isInterfaceDeclKind) {
4207e5dd7070Spatrick // Reject invalid vardecls.
4208e5dd7070Spatrick for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4209e5dd7070Spatrick DeclGroupRef DG = allTUVars[i].get();
4210e5dd7070Spatrick for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4211e5dd7070Spatrick if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4212e5dd7070Spatrick if (!VDecl->hasExternalStorage())
4213e5dd7070Spatrick Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4214e5dd7070Spatrick }
4215e5dd7070Spatrick }
4216e5dd7070Spatrick }
4217e5dd7070Spatrick ActOnObjCContainerFinishDefinition();
4218e5dd7070Spatrick
4219e5dd7070Spatrick for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4220e5dd7070Spatrick DeclGroupRef DG = allTUVars[i].get();
4221e5dd7070Spatrick for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4222e5dd7070Spatrick (*I)->setTopLevelDeclInObjCContainer();
4223e5dd7070Spatrick Consumer.HandleTopLevelDeclInObjCContainer(DG);
4224e5dd7070Spatrick }
4225e5dd7070Spatrick
4226e5dd7070Spatrick ActOnDocumentableDecl(ClassDecl);
4227e5dd7070Spatrick return ClassDecl;
4228e5dd7070Spatrick }
4229e5dd7070Spatrick
4230e5dd7070Spatrick /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4231e5dd7070Spatrick /// objective-c's type qualifier from the parser version of the same info.
4232e5dd7070Spatrick static Decl::ObjCDeclQualifier
CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal)4233e5dd7070Spatrick CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
4234e5dd7070Spatrick return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4235e5dd7070Spatrick }
4236e5dd7070Spatrick
4237e5dd7070Spatrick /// Check whether the declared result type of the given Objective-C
4238e5dd7070Spatrick /// method declaration is compatible with the method's class.
4239e5dd7070Spatrick ///
4240e5dd7070Spatrick static Sema::ResultTypeCompatibilityKind
CheckRelatedResultTypeCompatibility(Sema & S,ObjCMethodDecl * Method,ObjCInterfaceDecl * CurrentClass)4241e5dd7070Spatrick CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4242e5dd7070Spatrick ObjCInterfaceDecl *CurrentClass) {
4243e5dd7070Spatrick QualType ResultType = Method->getReturnType();
4244e5dd7070Spatrick
4245e5dd7070Spatrick // If an Objective-C method inherits its related result type, then its
4246e5dd7070Spatrick // declared result type must be compatible with its own class type. The
4247e5dd7070Spatrick // declared result type is compatible if:
4248e5dd7070Spatrick if (const ObjCObjectPointerType *ResultObjectType
4249e5dd7070Spatrick = ResultType->getAs<ObjCObjectPointerType>()) {
4250e5dd7070Spatrick // - it is id or qualified id, or
4251e5dd7070Spatrick if (ResultObjectType->isObjCIdType() ||
4252e5dd7070Spatrick ResultObjectType->isObjCQualifiedIdType())
4253e5dd7070Spatrick return Sema::RTC_Compatible;
4254e5dd7070Spatrick
4255e5dd7070Spatrick if (CurrentClass) {
4256e5dd7070Spatrick if (ObjCInterfaceDecl *ResultClass
4257e5dd7070Spatrick = ResultObjectType->getInterfaceDecl()) {
4258e5dd7070Spatrick // - it is the same as the method's class type, or
4259e5dd7070Spatrick if (declaresSameEntity(CurrentClass, ResultClass))
4260e5dd7070Spatrick return Sema::RTC_Compatible;
4261e5dd7070Spatrick
4262e5dd7070Spatrick // - it is a superclass of the method's class type
4263e5dd7070Spatrick if (ResultClass->isSuperClassOf(CurrentClass))
4264e5dd7070Spatrick return Sema::RTC_Compatible;
4265e5dd7070Spatrick }
4266e5dd7070Spatrick } else {
4267e5dd7070Spatrick // Any Objective-C pointer type might be acceptable for a protocol
4268e5dd7070Spatrick // method; we just don't know.
4269e5dd7070Spatrick return Sema::RTC_Unknown;
4270e5dd7070Spatrick }
4271e5dd7070Spatrick }
4272e5dd7070Spatrick
4273e5dd7070Spatrick return Sema::RTC_Incompatible;
4274e5dd7070Spatrick }
4275e5dd7070Spatrick
4276e5dd7070Spatrick namespace {
4277e5dd7070Spatrick /// A helper class for searching for methods which a particular method
4278e5dd7070Spatrick /// overrides.
4279e5dd7070Spatrick class OverrideSearch {
4280e5dd7070Spatrick public:
4281e5dd7070Spatrick const ObjCMethodDecl *Method;
4282e5dd7070Spatrick llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4283e5dd7070Spatrick bool Recursive;
4284e5dd7070Spatrick
4285e5dd7070Spatrick public:
OverrideSearch(Sema & S,const ObjCMethodDecl * method)4286e5dd7070Spatrick OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4287e5dd7070Spatrick Selector selector = method->getSelector();
4288e5dd7070Spatrick
4289e5dd7070Spatrick // Bypass this search if we've never seen an instance/class method
4290e5dd7070Spatrick // with this selector before.
4291e5dd7070Spatrick Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4292e5dd7070Spatrick if (it == S.MethodPool.end()) {
4293e5dd7070Spatrick if (!S.getExternalSource()) return;
4294e5dd7070Spatrick S.ReadMethodPool(selector);
4295e5dd7070Spatrick
4296e5dd7070Spatrick it = S.MethodPool.find(selector);
4297e5dd7070Spatrick if (it == S.MethodPool.end())
4298e5dd7070Spatrick return;
4299e5dd7070Spatrick }
4300e5dd7070Spatrick const ObjCMethodList &list =
4301e5dd7070Spatrick method->isInstanceMethod() ? it->second.first : it->second.second;
4302e5dd7070Spatrick if (!list.getMethod()) return;
4303e5dd7070Spatrick
4304e5dd7070Spatrick const ObjCContainerDecl *container
4305e5dd7070Spatrick = cast<ObjCContainerDecl>(method->getDeclContext());
4306e5dd7070Spatrick
4307e5dd7070Spatrick // Prevent the search from reaching this container again. This is
4308e5dd7070Spatrick // important with categories, which override methods from the
4309e5dd7070Spatrick // interface and each other.
4310e5dd7070Spatrick if (const ObjCCategoryDecl *Category =
4311e5dd7070Spatrick dyn_cast<ObjCCategoryDecl>(container)) {
4312e5dd7070Spatrick searchFromContainer(container);
4313e5dd7070Spatrick if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4314e5dd7070Spatrick searchFromContainer(Interface);
4315e5dd7070Spatrick } else {
4316e5dd7070Spatrick searchFromContainer(container);
4317e5dd7070Spatrick }
4318e5dd7070Spatrick }
4319e5dd7070Spatrick
4320e5dd7070Spatrick typedef decltype(Overridden)::iterator iterator;
begin() const4321e5dd7070Spatrick iterator begin() const { return Overridden.begin(); }
end() const4322e5dd7070Spatrick iterator end() const { return Overridden.end(); }
4323e5dd7070Spatrick
4324e5dd7070Spatrick private:
searchFromContainer(const ObjCContainerDecl * container)4325e5dd7070Spatrick void searchFromContainer(const ObjCContainerDecl *container) {
4326e5dd7070Spatrick if (container->isInvalidDecl()) return;
4327e5dd7070Spatrick
4328e5dd7070Spatrick switch (container->getDeclKind()) {
4329e5dd7070Spatrick #define OBJCCONTAINER(type, base) \
4330e5dd7070Spatrick case Decl::type: \
4331e5dd7070Spatrick searchFrom(cast<type##Decl>(container)); \
4332e5dd7070Spatrick break;
4333e5dd7070Spatrick #define ABSTRACT_DECL(expansion)
4334e5dd7070Spatrick #define DECL(type, base) \
4335e5dd7070Spatrick case Decl::type:
4336e5dd7070Spatrick #include "clang/AST/DeclNodes.inc"
4337e5dd7070Spatrick llvm_unreachable("not an ObjC container!");
4338e5dd7070Spatrick }
4339e5dd7070Spatrick }
4340e5dd7070Spatrick
searchFrom(const ObjCProtocolDecl * protocol)4341e5dd7070Spatrick void searchFrom(const ObjCProtocolDecl *protocol) {
4342e5dd7070Spatrick if (!protocol->hasDefinition())
4343e5dd7070Spatrick return;
4344e5dd7070Spatrick
4345e5dd7070Spatrick // A method in a protocol declaration overrides declarations from
4346e5dd7070Spatrick // referenced ("parent") protocols.
4347e5dd7070Spatrick search(protocol->getReferencedProtocols());
4348e5dd7070Spatrick }
4349e5dd7070Spatrick
searchFrom(const ObjCCategoryDecl * category)4350e5dd7070Spatrick void searchFrom(const ObjCCategoryDecl *category) {
4351e5dd7070Spatrick // A method in a category declaration overrides declarations from
4352e5dd7070Spatrick // the main class and from protocols the category references.
4353e5dd7070Spatrick // The main class is handled in the constructor.
4354e5dd7070Spatrick search(category->getReferencedProtocols());
4355e5dd7070Spatrick }
4356e5dd7070Spatrick
searchFrom(const ObjCCategoryImplDecl * impl)4357e5dd7070Spatrick void searchFrom(const ObjCCategoryImplDecl *impl) {
4358e5dd7070Spatrick // A method in a category definition that has a category
4359e5dd7070Spatrick // declaration overrides declarations from the category
4360e5dd7070Spatrick // declaration.
4361e5dd7070Spatrick if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4362e5dd7070Spatrick search(category);
4363e5dd7070Spatrick if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4364e5dd7070Spatrick search(Interface);
4365e5dd7070Spatrick
4366e5dd7070Spatrick // Otherwise it overrides declarations from the class.
4367e5dd7070Spatrick } else if (const auto *Interface = impl->getClassInterface()) {
4368e5dd7070Spatrick search(Interface);
4369e5dd7070Spatrick }
4370e5dd7070Spatrick }
4371e5dd7070Spatrick
searchFrom(const ObjCInterfaceDecl * iface)4372e5dd7070Spatrick void searchFrom(const ObjCInterfaceDecl *iface) {
4373e5dd7070Spatrick // A method in a class declaration overrides declarations from
4374e5dd7070Spatrick if (!iface->hasDefinition())
4375e5dd7070Spatrick return;
4376e5dd7070Spatrick
4377e5dd7070Spatrick // - categories,
4378e5dd7070Spatrick for (auto *Cat : iface->known_categories())
4379e5dd7070Spatrick search(Cat);
4380e5dd7070Spatrick
4381e5dd7070Spatrick // - the super class, and
4382e5dd7070Spatrick if (ObjCInterfaceDecl *super = iface->getSuperClass())
4383e5dd7070Spatrick search(super);
4384e5dd7070Spatrick
4385e5dd7070Spatrick // - any referenced protocols.
4386e5dd7070Spatrick search(iface->getReferencedProtocols());
4387e5dd7070Spatrick }
4388e5dd7070Spatrick
searchFrom(const ObjCImplementationDecl * impl)4389e5dd7070Spatrick void searchFrom(const ObjCImplementationDecl *impl) {
4390e5dd7070Spatrick // A method in a class implementation overrides declarations from
4391e5dd7070Spatrick // the class interface.
4392e5dd7070Spatrick if (const auto *Interface = impl->getClassInterface())
4393e5dd7070Spatrick search(Interface);
4394e5dd7070Spatrick }
4395e5dd7070Spatrick
search(const ObjCProtocolList & protocols)4396e5dd7070Spatrick void search(const ObjCProtocolList &protocols) {
4397e5dd7070Spatrick for (const auto *Proto : protocols)
4398e5dd7070Spatrick search(Proto);
4399e5dd7070Spatrick }
4400e5dd7070Spatrick
search(const ObjCContainerDecl * container)4401e5dd7070Spatrick void search(const ObjCContainerDecl *container) {
4402e5dd7070Spatrick // Check for a method in this container which matches this selector.
4403e5dd7070Spatrick ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4404e5dd7070Spatrick Method->isInstanceMethod(),
4405e5dd7070Spatrick /*AllowHidden=*/true);
4406e5dd7070Spatrick
4407e5dd7070Spatrick // If we find one, record it and bail out.
4408e5dd7070Spatrick if (meth) {
4409e5dd7070Spatrick Overridden.insert(meth);
4410e5dd7070Spatrick return;
4411e5dd7070Spatrick }
4412e5dd7070Spatrick
4413e5dd7070Spatrick // Otherwise, search for methods that a hypothetical method here
4414e5dd7070Spatrick // would have overridden.
4415e5dd7070Spatrick
4416e5dd7070Spatrick // Note that we're now in a recursive case.
4417e5dd7070Spatrick Recursive = true;
4418e5dd7070Spatrick
4419e5dd7070Spatrick searchFromContainer(container);
4420e5dd7070Spatrick }
4421e5dd7070Spatrick };
4422e5dd7070Spatrick } // end anonymous namespace
4423e5dd7070Spatrick
CheckObjCMethodDirectOverrides(ObjCMethodDecl * method,ObjCMethodDecl * overridden)4424e5dd7070Spatrick void Sema::CheckObjCMethodDirectOverrides(ObjCMethodDecl *method,
4425e5dd7070Spatrick ObjCMethodDecl *overridden) {
4426a9ac8606Spatrick if (overridden->isDirectMethod()) {
4427a9ac8606Spatrick const auto *attr = overridden->getAttr<ObjCDirectAttr>();
4428e5dd7070Spatrick Diag(method->getLocation(), diag::err_objc_override_direct_method);
4429e5dd7070Spatrick Diag(attr->getLocation(), diag::note_previous_declaration);
4430a9ac8606Spatrick } else if (method->isDirectMethod()) {
4431a9ac8606Spatrick const auto *attr = method->getAttr<ObjCDirectAttr>();
4432e5dd7070Spatrick Diag(attr->getLocation(), diag::err_objc_direct_on_override)
4433e5dd7070Spatrick << isa<ObjCProtocolDecl>(overridden->getDeclContext());
4434e5dd7070Spatrick Diag(overridden->getLocation(), diag::note_previous_declaration);
4435e5dd7070Spatrick }
4436e5dd7070Spatrick }
4437e5dd7070Spatrick
CheckObjCMethodOverrides(ObjCMethodDecl * ObjCMethod,ObjCInterfaceDecl * CurrentClass,ResultTypeCompatibilityKind RTC)4438e5dd7070Spatrick void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4439e5dd7070Spatrick ObjCInterfaceDecl *CurrentClass,
4440e5dd7070Spatrick ResultTypeCompatibilityKind RTC) {
4441e5dd7070Spatrick if (!ObjCMethod)
4442e5dd7070Spatrick return;
4443*12c85518Srobert auto IsMethodInCurrentClass = [CurrentClass](const ObjCMethodDecl *M) {
4444*12c85518Srobert // Checking canonical decl works across modules.
4445*12c85518Srobert return M->getClassInterface()->getCanonicalDecl() ==
4446*12c85518Srobert CurrentClass->getCanonicalDecl();
4447*12c85518Srobert };
4448e5dd7070Spatrick // Search for overridden methods and merge information down from them.
4449e5dd7070Spatrick OverrideSearch overrides(*this, ObjCMethod);
4450e5dd7070Spatrick // Keep track if the method overrides any method in the class's base classes,
4451e5dd7070Spatrick // its protocols, or its categories' protocols; we will keep that info
4452e5dd7070Spatrick // in the ObjCMethodDecl.
4453e5dd7070Spatrick // For this info, a method in an implementation is not considered as
4454e5dd7070Spatrick // overriding the same method in the interface or its categories.
4455e5dd7070Spatrick bool hasOverriddenMethodsInBaseOrProtocol = false;
4456e5dd7070Spatrick for (ObjCMethodDecl *overridden : overrides) {
4457e5dd7070Spatrick if (!hasOverriddenMethodsInBaseOrProtocol) {
4458e5dd7070Spatrick if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4459*12c85518Srobert !IsMethodInCurrentClass(overridden) || overridden->isOverriding()) {
4460e5dd7070Spatrick CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
4461e5dd7070Spatrick hasOverriddenMethodsInBaseOrProtocol = true;
4462e5dd7070Spatrick } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4463e5dd7070Spatrick // OverrideSearch will return as "overridden" the same method in the
4464e5dd7070Spatrick // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4465e5dd7070Spatrick // check whether a category of a base class introduced a method with the
4466e5dd7070Spatrick // same selector, after the interface method declaration.
4467e5dd7070Spatrick // To avoid unnecessary lookups in the majority of cases, we use the
4468e5dd7070Spatrick // extra info bits in GlobalMethodPool to check whether there were any
4469e5dd7070Spatrick // category methods with this selector.
4470e5dd7070Spatrick GlobalMethodPool::iterator It =
4471e5dd7070Spatrick MethodPool.find(ObjCMethod->getSelector());
4472e5dd7070Spatrick if (It != MethodPool.end()) {
4473e5dd7070Spatrick ObjCMethodList &List =
4474e5dd7070Spatrick ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4475e5dd7070Spatrick unsigned CategCount = List.getBits();
4476e5dd7070Spatrick if (CategCount > 0) {
4477e5dd7070Spatrick // If the method is in a category we'll do lookup if there were at
4478e5dd7070Spatrick // least 2 category methods recorded, otherwise only one will do.
4479e5dd7070Spatrick if (CategCount > 1 ||
4480e5dd7070Spatrick !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4481e5dd7070Spatrick OverrideSearch overrides(*this, overridden);
4482e5dd7070Spatrick for (ObjCMethodDecl *SuperOverridden : overrides) {
4483e5dd7070Spatrick if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4484*12c85518Srobert !IsMethodInCurrentClass(SuperOverridden)) {
4485e5dd7070Spatrick CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
4486e5dd7070Spatrick hasOverriddenMethodsInBaseOrProtocol = true;
4487e5dd7070Spatrick overridden->setOverriding(true);
4488e5dd7070Spatrick break;
4489e5dd7070Spatrick }
4490e5dd7070Spatrick }
4491e5dd7070Spatrick }
4492e5dd7070Spatrick }
4493e5dd7070Spatrick }
4494e5dd7070Spatrick }
4495e5dd7070Spatrick }
4496e5dd7070Spatrick
4497e5dd7070Spatrick // Propagate down the 'related result type' bit from overridden methods.
4498e5dd7070Spatrick if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4499e5dd7070Spatrick ObjCMethod->setRelatedResultType();
4500e5dd7070Spatrick
4501e5dd7070Spatrick // Then merge the declarations.
4502e5dd7070Spatrick mergeObjCMethodDecls(ObjCMethod, overridden);
4503e5dd7070Spatrick
4504e5dd7070Spatrick if (ObjCMethod->isImplicit() && overridden->isImplicit())
4505e5dd7070Spatrick continue; // Conflicting properties are detected elsewhere.
4506e5dd7070Spatrick
4507e5dd7070Spatrick // Check for overriding methods
4508e5dd7070Spatrick if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4509e5dd7070Spatrick isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4510e5dd7070Spatrick CheckConflictingOverridingMethod(ObjCMethod, overridden,
4511e5dd7070Spatrick isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4512e5dd7070Spatrick
4513e5dd7070Spatrick if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4514e5dd7070Spatrick isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4515e5dd7070Spatrick !overridden->isImplicit() /* not meant for properties */) {
4516e5dd7070Spatrick ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4517e5dd7070Spatrick E = ObjCMethod->param_end();
4518e5dd7070Spatrick ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4519e5dd7070Spatrick PrevE = overridden->param_end();
4520e5dd7070Spatrick for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4521e5dd7070Spatrick assert(PrevI != overridden->param_end() && "Param mismatch");
4522e5dd7070Spatrick QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4523e5dd7070Spatrick QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4524e5dd7070Spatrick // If type of argument of method in this class does not match its
4525e5dd7070Spatrick // respective argument type in the super class method, issue warning;
4526e5dd7070Spatrick if (!Context.typesAreCompatible(T1, T2)) {
4527e5dd7070Spatrick Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4528e5dd7070Spatrick << T1 << T2;
4529e5dd7070Spatrick Diag(overridden->getLocation(), diag::note_previous_declaration);
4530e5dd7070Spatrick break;
4531e5dd7070Spatrick }
4532e5dd7070Spatrick }
4533e5dd7070Spatrick }
4534e5dd7070Spatrick }
4535e5dd7070Spatrick
4536e5dd7070Spatrick ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4537e5dd7070Spatrick }
4538e5dd7070Spatrick
4539e5dd7070Spatrick /// Merge type nullability from for a redeclaration of the same entity,
4540e5dd7070Spatrick /// producing the updated type of the redeclared entity.
mergeTypeNullabilityForRedecl(Sema & S,SourceLocation loc,QualType type,bool usesCSKeyword,SourceLocation prevLoc,QualType prevType,bool prevUsesCSKeyword)4541e5dd7070Spatrick static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4542e5dd7070Spatrick QualType type,
4543e5dd7070Spatrick bool usesCSKeyword,
4544e5dd7070Spatrick SourceLocation prevLoc,
4545e5dd7070Spatrick QualType prevType,
4546e5dd7070Spatrick bool prevUsesCSKeyword) {
4547e5dd7070Spatrick // Determine the nullability of both types.
4548*12c85518Srobert auto nullability = type->getNullability();
4549*12c85518Srobert auto prevNullability = prevType->getNullability();
4550e5dd7070Spatrick
4551e5dd7070Spatrick // Easy case: both have nullability.
4552*12c85518Srobert if (nullability.has_value() == prevNullability.has_value()) {
4553e5dd7070Spatrick // Neither has nullability; continue.
4554e5dd7070Spatrick if (!nullability)
4555e5dd7070Spatrick return type;
4556e5dd7070Spatrick
4557e5dd7070Spatrick // The nullabilities are equivalent; do nothing.
4558e5dd7070Spatrick if (*nullability == *prevNullability)
4559e5dd7070Spatrick return type;
4560e5dd7070Spatrick
4561e5dd7070Spatrick // Complain about mismatched nullability.
4562e5dd7070Spatrick S.Diag(loc, diag::err_nullability_conflicting)
4563e5dd7070Spatrick << DiagNullabilityKind(*nullability, usesCSKeyword)
4564e5dd7070Spatrick << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4565e5dd7070Spatrick return type;
4566e5dd7070Spatrick }
4567e5dd7070Spatrick
4568e5dd7070Spatrick // If it's the redeclaration that has nullability, don't change anything.
4569e5dd7070Spatrick if (nullability)
4570e5dd7070Spatrick return type;
4571e5dd7070Spatrick
4572e5dd7070Spatrick // Otherwise, provide the result with the same nullability.
4573e5dd7070Spatrick return S.Context.getAttributedType(
4574e5dd7070Spatrick AttributedType::getNullabilityAttrKind(*prevNullability),
4575e5dd7070Spatrick type, type);
4576e5dd7070Spatrick }
4577e5dd7070Spatrick
4578e5dd7070Spatrick /// Merge information from the declaration of a method in the \@interface
4579e5dd7070Spatrick /// (or a category/extension) into the corresponding method in the
4580e5dd7070Spatrick /// @implementation (for a class or category).
mergeInterfaceMethodToImpl(Sema & S,ObjCMethodDecl * method,ObjCMethodDecl * prevMethod)4581e5dd7070Spatrick static void mergeInterfaceMethodToImpl(Sema &S,
4582e5dd7070Spatrick ObjCMethodDecl *method,
4583e5dd7070Spatrick ObjCMethodDecl *prevMethod) {
4584e5dd7070Spatrick // Merge the objc_requires_super attribute.
4585e5dd7070Spatrick if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4586e5dd7070Spatrick !method->hasAttr<ObjCRequiresSuperAttr>()) {
4587e5dd7070Spatrick // merge the attribute into implementation.
4588e5dd7070Spatrick method->addAttr(
4589e5dd7070Spatrick ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4590e5dd7070Spatrick method->getLocation()));
4591e5dd7070Spatrick }
4592e5dd7070Spatrick
4593e5dd7070Spatrick // Merge nullability of the result type.
4594e5dd7070Spatrick QualType newReturnType
4595e5dd7070Spatrick = mergeTypeNullabilityForRedecl(
4596e5dd7070Spatrick S, method->getReturnTypeSourceRange().getBegin(),
4597e5dd7070Spatrick method->getReturnType(),
4598e5dd7070Spatrick method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4599e5dd7070Spatrick prevMethod->getReturnTypeSourceRange().getBegin(),
4600e5dd7070Spatrick prevMethod->getReturnType(),
4601e5dd7070Spatrick prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4602e5dd7070Spatrick method->setReturnType(newReturnType);
4603e5dd7070Spatrick
4604e5dd7070Spatrick // Handle each of the parameters.
4605e5dd7070Spatrick unsigned numParams = method->param_size();
4606e5dd7070Spatrick unsigned numPrevParams = prevMethod->param_size();
4607e5dd7070Spatrick for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4608e5dd7070Spatrick ParmVarDecl *param = method->param_begin()[i];
4609e5dd7070Spatrick ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4610e5dd7070Spatrick
4611e5dd7070Spatrick // Merge nullability.
4612e5dd7070Spatrick QualType newParamType
4613e5dd7070Spatrick = mergeTypeNullabilityForRedecl(
4614e5dd7070Spatrick S, param->getLocation(), param->getType(),
4615e5dd7070Spatrick param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4616e5dd7070Spatrick prevParam->getLocation(), prevParam->getType(),
4617e5dd7070Spatrick prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4618e5dd7070Spatrick param->setType(newParamType);
4619e5dd7070Spatrick }
4620e5dd7070Spatrick }
4621e5dd7070Spatrick
4622e5dd7070Spatrick /// Verify that the method parameters/return value have types that are supported
4623e5dd7070Spatrick /// by the x86 target.
checkObjCMethodX86VectorTypes(Sema & SemaRef,const ObjCMethodDecl * Method)4624e5dd7070Spatrick static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4625e5dd7070Spatrick const ObjCMethodDecl *Method) {
4626e5dd7070Spatrick assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4627e5dd7070Spatrick llvm::Triple::x86 &&
4628e5dd7070Spatrick "x86-specific check invoked for a different target");
4629e5dd7070Spatrick SourceLocation Loc;
4630e5dd7070Spatrick QualType T;
4631e5dd7070Spatrick for (const ParmVarDecl *P : Method->parameters()) {
4632e5dd7070Spatrick if (P->getType()->isVectorType()) {
4633e5dd7070Spatrick Loc = P->getBeginLoc();
4634e5dd7070Spatrick T = P->getType();
4635e5dd7070Spatrick break;
4636e5dd7070Spatrick }
4637e5dd7070Spatrick }
4638e5dd7070Spatrick if (Loc.isInvalid()) {
4639e5dd7070Spatrick if (Method->getReturnType()->isVectorType()) {
4640e5dd7070Spatrick Loc = Method->getReturnTypeSourceRange().getBegin();
4641e5dd7070Spatrick T = Method->getReturnType();
4642e5dd7070Spatrick } else
4643e5dd7070Spatrick return;
4644e5dd7070Spatrick }
4645e5dd7070Spatrick
4646e5dd7070Spatrick // Vector parameters/return values are not supported by objc_msgSend on x86 in
4647e5dd7070Spatrick // iOS < 9 and macOS < 10.11.
4648e5dd7070Spatrick const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4649e5dd7070Spatrick VersionTuple AcceptedInVersion;
4650e5dd7070Spatrick if (Triple.getOS() == llvm::Triple::IOS)
4651e5dd7070Spatrick AcceptedInVersion = VersionTuple(/*Major=*/9);
4652e5dd7070Spatrick else if (Triple.isMacOSX())
4653e5dd7070Spatrick AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4654e5dd7070Spatrick else
4655e5dd7070Spatrick return;
4656e5dd7070Spatrick if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
4657e5dd7070Spatrick AcceptedInVersion)
4658e5dd7070Spatrick return;
4659e5dd7070Spatrick SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4660e5dd7070Spatrick << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4661e5dd7070Spatrick : /*parameter*/ 0)
4662e5dd7070Spatrick << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4663e5dd7070Spatrick }
4664e5dd7070Spatrick
mergeObjCDirectMembers(Sema & S,Decl * CD,ObjCMethodDecl * Method)4665ec727ea7Spatrick static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4666ec727ea7Spatrick if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
4667ec727ea7Spatrick CD->hasAttr<ObjCDirectMembersAttr>()) {
4668ec727ea7Spatrick Method->addAttr(
4669ec727ea7Spatrick ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4670ec727ea7Spatrick }
4671ec727ea7Spatrick }
4672ec727ea7Spatrick
checkObjCDirectMethodClashes(Sema & S,ObjCInterfaceDecl * IDecl,ObjCMethodDecl * Method,ObjCImplDecl * ImpDecl=nullptr)4673ec727ea7Spatrick static void checkObjCDirectMethodClashes(Sema &S, ObjCInterfaceDecl *IDecl,
4674ec727ea7Spatrick ObjCMethodDecl *Method,
4675ec727ea7Spatrick ObjCImplDecl *ImpDecl = nullptr) {
4676ec727ea7Spatrick auto Sel = Method->getSelector();
4677ec727ea7Spatrick bool isInstance = Method->isInstanceMethod();
4678ec727ea7Spatrick bool diagnosed = false;
4679ec727ea7Spatrick
4680ec727ea7Spatrick auto diagClash = [&](const ObjCMethodDecl *IMD) {
4681ec727ea7Spatrick if (diagnosed || IMD->isImplicit())
4682ec727ea7Spatrick return;
4683ec727ea7Spatrick if (Method->isDirectMethod() || IMD->isDirectMethod()) {
4684ec727ea7Spatrick S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
4685ec727ea7Spatrick << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod()
4686ec727ea7Spatrick << Method->getDeclName();
4687ec727ea7Spatrick S.Diag(IMD->getLocation(), diag::note_previous_declaration);
4688ec727ea7Spatrick diagnosed = true;
4689ec727ea7Spatrick }
4690ec727ea7Spatrick };
4691ec727ea7Spatrick
4692ec727ea7Spatrick // Look for any other declaration of this method anywhere we can see in this
4693ec727ea7Spatrick // compilation unit.
4694ec727ea7Spatrick //
4695ec727ea7Spatrick // We do not use IDecl->lookupMethod() because we have specific needs:
4696ec727ea7Spatrick //
4697ec727ea7Spatrick // - we absolutely do not need to walk protocols, because
4698ec727ea7Spatrick // diag::err_objc_direct_on_protocol has already been emitted
4699ec727ea7Spatrick // during parsing if there's a conflict,
4700ec727ea7Spatrick //
4701ec727ea7Spatrick // - when we do not find a match in a given @interface container,
4702ec727ea7Spatrick // we need to attempt looking it up in the @implementation block if the
4703ec727ea7Spatrick // translation unit sees it to find more clashes.
4704ec727ea7Spatrick
4705ec727ea7Spatrick if (auto *IMD = IDecl->getMethod(Sel, isInstance))
4706ec727ea7Spatrick diagClash(IMD);
4707ec727ea7Spatrick else if (auto *Impl = IDecl->getImplementation())
4708ec727ea7Spatrick if (Impl != ImpDecl)
4709ec727ea7Spatrick if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
4710ec727ea7Spatrick diagClash(IMD);
4711ec727ea7Spatrick
4712ec727ea7Spatrick for (const auto *Cat : IDecl->visible_categories())
4713ec727ea7Spatrick if (auto *IMD = Cat->getMethod(Sel, isInstance))
4714ec727ea7Spatrick diagClash(IMD);
4715ec727ea7Spatrick else if (auto CatImpl = Cat->getImplementation())
4716ec727ea7Spatrick if (CatImpl != ImpDecl)
4717ec727ea7Spatrick if (auto *IMD = Cat->getMethod(Sel, isInstance))
4718ec727ea7Spatrick diagClash(IMD);
4719ec727ea7Spatrick }
4720ec727ea7Spatrick
ActOnMethodDeclaration(Scope * S,SourceLocation MethodLoc,SourceLocation EndLoc,tok::TokenKind MethodType,ObjCDeclSpec & ReturnQT,ParsedType ReturnType,ArrayRef<SourceLocation> SelectorLocs,Selector Sel,ObjCArgInfo * ArgInfo,DeclaratorChunk::ParamInfo * CParamInfo,unsigned CNumArgs,const ParsedAttributesView & AttrList,tok::ObjCKeywordKind MethodDeclKind,bool isVariadic,bool MethodDefinition)4721e5dd7070Spatrick Decl *Sema::ActOnMethodDeclaration(
4722e5dd7070Spatrick Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4723e5dd7070Spatrick tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4724e5dd7070Spatrick ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4725e5dd7070Spatrick // optional arguments. The number of types/arguments is obtained
4726e5dd7070Spatrick // from the Sel.getNumArgs().
4727e5dd7070Spatrick ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4728e5dd7070Spatrick unsigned CNumArgs, // c-style args
4729e5dd7070Spatrick const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4730e5dd7070Spatrick bool isVariadic, bool MethodDefinition) {
4731e5dd7070Spatrick // Make sure we can establish a context for the method.
4732e5dd7070Spatrick if (!CurContext->isObjCContainer()) {
4733e5dd7070Spatrick Diag(MethodLoc, diag::err_missing_method_context);
4734e5dd7070Spatrick return nullptr;
4735e5dd7070Spatrick }
4736e5dd7070Spatrick
4737e5dd7070Spatrick Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
4738e5dd7070Spatrick QualType resultDeclType;
4739e5dd7070Spatrick
4740e5dd7070Spatrick bool HasRelatedResultType = false;
4741e5dd7070Spatrick TypeSourceInfo *ReturnTInfo = nullptr;
4742e5dd7070Spatrick if (ReturnType) {
4743e5dd7070Spatrick resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4744e5dd7070Spatrick
4745e5dd7070Spatrick if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4746e5dd7070Spatrick return nullptr;
4747e5dd7070Spatrick
4748e5dd7070Spatrick QualType bareResultType = resultDeclType;
4749e5dd7070Spatrick (void)AttributedType::stripOuterNullability(bareResultType);
4750e5dd7070Spatrick HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4751e5dd7070Spatrick } else { // get the type for "id".
4752e5dd7070Spatrick resultDeclType = Context.getObjCIdType();
4753e5dd7070Spatrick Diag(MethodLoc, diag::warn_missing_method_return_type)
4754e5dd7070Spatrick << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4755e5dd7070Spatrick }
4756e5dd7070Spatrick
4757e5dd7070Spatrick ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4758e5dd7070Spatrick Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4759e5dd7070Spatrick MethodType == tok::minus, isVariadic,
4760e5dd7070Spatrick /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4761e5dd7070Spatrick /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4762e5dd7070Spatrick MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4763e5dd7070Spatrick : ObjCMethodDecl::Required,
4764e5dd7070Spatrick HasRelatedResultType);
4765e5dd7070Spatrick
4766e5dd7070Spatrick SmallVector<ParmVarDecl*, 16> Params;
4767e5dd7070Spatrick
4768e5dd7070Spatrick for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4769e5dd7070Spatrick QualType ArgType;
4770e5dd7070Spatrick TypeSourceInfo *DI;
4771e5dd7070Spatrick
4772e5dd7070Spatrick if (!ArgInfo[i].Type) {
4773e5dd7070Spatrick ArgType = Context.getObjCIdType();
4774e5dd7070Spatrick DI = nullptr;
4775e5dd7070Spatrick } else {
4776e5dd7070Spatrick ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4777e5dd7070Spatrick }
4778e5dd7070Spatrick
4779e5dd7070Spatrick LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4780e5dd7070Spatrick LookupOrdinaryName, forRedeclarationInCurContext());
4781e5dd7070Spatrick LookupName(R, S);
4782e5dd7070Spatrick if (R.isSingleResult()) {
4783e5dd7070Spatrick NamedDecl *PrevDecl = R.getFoundDecl();
4784e5dd7070Spatrick if (S->isDeclScope(PrevDecl)) {
4785e5dd7070Spatrick Diag(ArgInfo[i].NameLoc,
4786e5dd7070Spatrick (MethodDefinition ? diag::warn_method_param_redefinition
4787e5dd7070Spatrick : diag::warn_method_param_declaration))
4788e5dd7070Spatrick << ArgInfo[i].Name;
4789e5dd7070Spatrick Diag(PrevDecl->getLocation(),
4790e5dd7070Spatrick diag::note_previous_declaration);
4791e5dd7070Spatrick }
4792e5dd7070Spatrick }
4793e5dd7070Spatrick
4794e5dd7070Spatrick SourceLocation StartLoc = DI
4795e5dd7070Spatrick ? DI->getTypeLoc().getBeginLoc()
4796e5dd7070Spatrick : ArgInfo[i].NameLoc;
4797e5dd7070Spatrick
4798e5dd7070Spatrick ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4799e5dd7070Spatrick ArgInfo[i].NameLoc, ArgInfo[i].Name,
4800e5dd7070Spatrick ArgType, DI, SC_None);
4801e5dd7070Spatrick
4802e5dd7070Spatrick Param->setObjCMethodScopeInfo(i);
4803e5dd7070Spatrick
4804e5dd7070Spatrick Param->setObjCDeclQualifier(
4805e5dd7070Spatrick CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4806e5dd7070Spatrick
4807e5dd7070Spatrick // Apply the attributes to the parameter.
4808e5dd7070Spatrick ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4809e5dd7070Spatrick AddPragmaAttributes(TUScope, Param);
4810e5dd7070Spatrick
4811e5dd7070Spatrick if (Param->hasAttr<BlocksAttr>()) {
4812e5dd7070Spatrick Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4813e5dd7070Spatrick Param->setInvalidDecl();
4814e5dd7070Spatrick }
4815e5dd7070Spatrick S->AddDecl(Param);
4816e5dd7070Spatrick IdResolver.AddDecl(Param);
4817e5dd7070Spatrick
4818e5dd7070Spatrick Params.push_back(Param);
4819e5dd7070Spatrick }
4820e5dd7070Spatrick
4821e5dd7070Spatrick for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4822e5dd7070Spatrick ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4823e5dd7070Spatrick QualType ArgType = Param->getType();
4824e5dd7070Spatrick if (ArgType.isNull())
4825e5dd7070Spatrick ArgType = Context.getObjCIdType();
4826e5dd7070Spatrick else
4827e5dd7070Spatrick // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4828e5dd7070Spatrick ArgType = Context.getAdjustedParameterType(ArgType);
4829e5dd7070Spatrick
4830e5dd7070Spatrick Param->setDeclContext(ObjCMethod);
4831e5dd7070Spatrick Params.push_back(Param);
4832e5dd7070Spatrick }
4833e5dd7070Spatrick
4834e5dd7070Spatrick ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4835e5dd7070Spatrick ObjCMethod->setObjCDeclQualifier(
4836e5dd7070Spatrick CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4837e5dd7070Spatrick
4838e5dd7070Spatrick ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4839e5dd7070Spatrick AddPragmaAttributes(TUScope, ObjCMethod);
4840e5dd7070Spatrick
4841e5dd7070Spatrick // Add the method now.
4842e5dd7070Spatrick const ObjCMethodDecl *PrevMethod = nullptr;
4843e5dd7070Spatrick if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4844e5dd7070Spatrick if (MethodType == tok::minus) {
4845e5dd7070Spatrick PrevMethod = ImpDecl->getInstanceMethod(Sel);
4846e5dd7070Spatrick ImpDecl->addInstanceMethod(ObjCMethod);
4847e5dd7070Spatrick } else {
4848e5dd7070Spatrick PrevMethod = ImpDecl->getClassMethod(Sel);
4849e5dd7070Spatrick ImpDecl->addClassMethod(ObjCMethod);
4850e5dd7070Spatrick }
4851e5dd7070Spatrick
4852e5dd7070Spatrick // If this method overrides a previous @synthesize declaration,
4853e5dd7070Spatrick // register it with the property. Linear search through all
4854e5dd7070Spatrick // properties here, because the autosynthesized stub hasn't been
4855*12c85518Srobert // made visible yet, so it can be overridden by a later
4856e5dd7070Spatrick // user-specified implementation.
4857e5dd7070Spatrick for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4858e5dd7070Spatrick if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4859e5dd7070Spatrick if (Setter->getSelector() == Sel &&
4860e5dd7070Spatrick Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4861e5dd7070Spatrick assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4862e5dd7070Spatrick PropertyImpl->setSetterMethodDecl(ObjCMethod);
4863e5dd7070Spatrick }
4864e5dd7070Spatrick if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4865e5dd7070Spatrick if (Getter->getSelector() == Sel &&
4866e5dd7070Spatrick Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4867e5dd7070Spatrick assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4868e5dd7070Spatrick PropertyImpl->setGetterMethodDecl(ObjCMethod);
4869e5dd7070Spatrick break;
4870e5dd7070Spatrick }
4871e5dd7070Spatrick }
4872e5dd7070Spatrick
4873e5dd7070Spatrick // A method is either tagged direct explicitly, or inherits it from its
4874e5dd7070Spatrick // canonical declaration.
4875e5dd7070Spatrick //
4876e5dd7070Spatrick // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4877e5dd7070Spatrick // because IDecl->lookupMethod() returns more possible matches than just
4878e5dd7070Spatrick // the canonical declaration.
4879e5dd7070Spatrick if (!ObjCMethod->isDirectMethod()) {
4880e5dd7070Spatrick const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4881a9ac8606Spatrick if (CanonicalMD->isDirectMethod()) {
4882a9ac8606Spatrick const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4883e5dd7070Spatrick ObjCMethod->addAttr(
4884e5dd7070Spatrick ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4885e5dd7070Spatrick }
4886e5dd7070Spatrick }
4887e5dd7070Spatrick
4888e5dd7070Spatrick // Merge information from the @interface declaration into the
4889e5dd7070Spatrick // @implementation.
4890e5dd7070Spatrick if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4891e5dd7070Spatrick if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4892e5dd7070Spatrick ObjCMethod->isInstanceMethod())) {
4893e5dd7070Spatrick mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4894e5dd7070Spatrick
4895e5dd7070Spatrick // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4896e5dd7070Spatrick // in one of these places:
4897e5dd7070Spatrick //
4898e5dd7070Spatrick // (1) the canonical declaration in an @interface container paired
4899e5dd7070Spatrick // with the ImplDecl,
4900e5dd7070Spatrick // (2) non canonical declarations in @interface not paired with the
4901e5dd7070Spatrick // ImplDecl for the same Class,
4902e5dd7070Spatrick // (3) any superclass container.
4903e5dd7070Spatrick //
4904e5dd7070Spatrick // Direct methods only allow for canonical declarations in the matching
4905e5dd7070Spatrick // container (case 1).
4906e5dd7070Spatrick //
4907e5dd7070Spatrick // Direct methods overriding a superclass declaration (case 3) is
4908e5dd7070Spatrick // handled during overrides checks in CheckObjCMethodOverrides().
4909e5dd7070Spatrick //
4910e5dd7070Spatrick // We deal with same-class container mismatches (Case 2) here.
4911e5dd7070Spatrick if (IDecl == IMD->getClassInterface()) {
4912e5dd7070Spatrick auto diagContainerMismatch = [&] {
4913e5dd7070Spatrick int decl = 0, impl = 0;
4914e5dd7070Spatrick
4915e5dd7070Spatrick if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4916e5dd7070Spatrick decl = Cat->IsClassExtension() ? 1 : 2;
4917e5dd7070Spatrick
4918e5dd7070Spatrick if (isa<ObjCCategoryImplDecl>(ImpDecl))
4919e5dd7070Spatrick impl = 1 + (decl != 0);
4920e5dd7070Spatrick
4921e5dd7070Spatrick Diag(ObjCMethod->getLocation(),
4922e5dd7070Spatrick diag::err_objc_direct_impl_decl_mismatch)
4923e5dd7070Spatrick << decl << impl;
4924e5dd7070Spatrick Diag(IMD->getLocation(), diag::note_previous_declaration);
4925e5dd7070Spatrick };
4926e5dd7070Spatrick
4927a9ac8606Spatrick if (ObjCMethod->isDirectMethod()) {
4928a9ac8606Spatrick const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4929e5dd7070Spatrick if (ObjCMethod->getCanonicalDecl() != IMD) {
4930e5dd7070Spatrick diagContainerMismatch();
4931e5dd7070Spatrick } else if (!IMD->isDirectMethod()) {
4932e5dd7070Spatrick Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4933e5dd7070Spatrick Diag(IMD->getLocation(), diag::note_previous_declaration);
4934e5dd7070Spatrick }
4935a9ac8606Spatrick } else if (IMD->isDirectMethod()) {
4936a9ac8606Spatrick const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4937e5dd7070Spatrick if (ObjCMethod->getCanonicalDecl() != IMD) {
4938e5dd7070Spatrick diagContainerMismatch();
4939e5dd7070Spatrick } else {
4940e5dd7070Spatrick ObjCMethod->addAttr(
4941e5dd7070Spatrick ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4942e5dd7070Spatrick }
4943e5dd7070Spatrick }
4944e5dd7070Spatrick }
4945e5dd7070Spatrick
4946e5dd7070Spatrick // Warn about defining -dealloc in a category.
4947e5dd7070Spatrick if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4948e5dd7070Spatrick ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4949e5dd7070Spatrick Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4950e5dd7070Spatrick << ObjCMethod->getDeclName();
4951e5dd7070Spatrick }
4952ec727ea7Spatrick } else {
4953ec727ea7Spatrick mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4954ec727ea7Spatrick checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl);
4955e5dd7070Spatrick }
4956e5dd7070Spatrick
4957e5dd7070Spatrick // Warn if a method declared in a protocol to which a category or
4958e5dd7070Spatrick // extension conforms is non-escaping and the implementation's method is
4959e5dd7070Spatrick // escaping.
4960e5dd7070Spatrick for (auto *C : IDecl->visible_categories())
4961e5dd7070Spatrick for (auto &P : C->protocols())
4962e5dd7070Spatrick if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4963e5dd7070Spatrick ObjCMethod->isInstanceMethod())) {
4964e5dd7070Spatrick assert(ObjCMethod->parameters().size() ==
4965e5dd7070Spatrick IMD->parameters().size() &&
4966e5dd7070Spatrick "Methods have different number of parameters");
4967e5dd7070Spatrick auto OI = IMD->param_begin(), OE = IMD->param_end();
4968e5dd7070Spatrick auto NI = ObjCMethod->param_begin();
4969e5dd7070Spatrick for (; OI != OE; ++OI, ++NI)
4970e5dd7070Spatrick diagnoseNoescape(*NI, *OI, C, P, *this);
4971e5dd7070Spatrick }
4972e5dd7070Spatrick }
4973e5dd7070Spatrick } else {
4974e5dd7070Spatrick if (!isa<ObjCProtocolDecl>(ClassDecl)) {
4975ec727ea7Spatrick mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4976e5dd7070Spatrick
4977e5dd7070Spatrick ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4978e5dd7070Spatrick if (!IDecl)
4979e5dd7070Spatrick IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
4980ec727ea7Spatrick // For valid code, we should always know the primary interface
4981ec727ea7Spatrick // declaration by now, however for invalid code we'll keep parsing
4982ec727ea7Spatrick // but we won't find the primary interface and IDecl will be nil.
4983e5dd7070Spatrick if (IDecl)
4984ec727ea7Spatrick checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod);
4985e5dd7070Spatrick }
4986e5dd7070Spatrick
4987e5dd7070Spatrick cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4988e5dd7070Spatrick }
4989e5dd7070Spatrick
4990e5dd7070Spatrick if (PrevMethod) {
4991e5dd7070Spatrick // You can never have two method definitions with the same name.
4992e5dd7070Spatrick Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4993e5dd7070Spatrick << ObjCMethod->getDeclName();
4994e5dd7070Spatrick Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4995e5dd7070Spatrick ObjCMethod->setInvalidDecl();
4996e5dd7070Spatrick return ObjCMethod;
4997e5dd7070Spatrick }
4998e5dd7070Spatrick
4999e5dd7070Spatrick // If this Objective-C method does not have a related result type, but we
5000e5dd7070Spatrick // are allowed to infer related result types, try to do so based on the
5001e5dd7070Spatrick // method family.
5002e5dd7070Spatrick ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
5003e5dd7070Spatrick if (!CurrentClass) {
5004e5dd7070Spatrick if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
5005e5dd7070Spatrick CurrentClass = Cat->getClassInterface();
5006e5dd7070Spatrick else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
5007e5dd7070Spatrick CurrentClass = Impl->getClassInterface();
5008e5dd7070Spatrick else if (ObjCCategoryImplDecl *CatImpl
5009e5dd7070Spatrick = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
5010e5dd7070Spatrick CurrentClass = CatImpl->getClassInterface();
5011e5dd7070Spatrick }
5012e5dd7070Spatrick
5013e5dd7070Spatrick ResultTypeCompatibilityKind RTC
5014e5dd7070Spatrick = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
5015e5dd7070Spatrick
5016e5dd7070Spatrick CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
5017e5dd7070Spatrick
5018e5dd7070Spatrick bool ARCError = false;
5019e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount)
5020e5dd7070Spatrick ARCError = CheckARCMethodDecl(ObjCMethod);
5021e5dd7070Spatrick
5022e5dd7070Spatrick // Infer the related result type when possible.
5023e5dd7070Spatrick if (!ARCError && RTC == Sema::RTC_Compatible &&
5024e5dd7070Spatrick !ObjCMethod->hasRelatedResultType() &&
5025e5dd7070Spatrick LangOpts.ObjCInferRelatedResultType) {
5026e5dd7070Spatrick bool InferRelatedResultType = false;
5027e5dd7070Spatrick switch (ObjCMethod->getMethodFamily()) {
5028e5dd7070Spatrick case OMF_None:
5029e5dd7070Spatrick case OMF_copy:
5030e5dd7070Spatrick case OMF_dealloc:
5031e5dd7070Spatrick case OMF_finalize:
5032e5dd7070Spatrick case OMF_mutableCopy:
5033e5dd7070Spatrick case OMF_release:
5034e5dd7070Spatrick case OMF_retainCount:
5035e5dd7070Spatrick case OMF_initialize:
5036e5dd7070Spatrick case OMF_performSelector:
5037e5dd7070Spatrick break;
5038e5dd7070Spatrick
5039e5dd7070Spatrick case OMF_alloc:
5040e5dd7070Spatrick case OMF_new:
5041e5dd7070Spatrick InferRelatedResultType = ObjCMethod->isClassMethod();
5042e5dd7070Spatrick break;
5043e5dd7070Spatrick
5044e5dd7070Spatrick case OMF_init:
5045e5dd7070Spatrick case OMF_autorelease:
5046e5dd7070Spatrick case OMF_retain:
5047e5dd7070Spatrick case OMF_self:
5048e5dd7070Spatrick InferRelatedResultType = ObjCMethod->isInstanceMethod();
5049e5dd7070Spatrick break;
5050e5dd7070Spatrick }
5051e5dd7070Spatrick
5052e5dd7070Spatrick if (InferRelatedResultType &&
5053e5dd7070Spatrick !ObjCMethod->getReturnType()->isObjCIndependentClassType())
5054e5dd7070Spatrick ObjCMethod->setRelatedResultType();
5055e5dd7070Spatrick }
5056e5dd7070Spatrick
5057e5dd7070Spatrick if (MethodDefinition &&
5058e5dd7070Spatrick Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5059e5dd7070Spatrick checkObjCMethodX86VectorTypes(*this, ObjCMethod);
5060e5dd7070Spatrick
5061e5dd7070Spatrick // + load method cannot have availability attributes. It get called on
5062e5dd7070Spatrick // startup, so it has to have the availability of the deployment target.
5063e5dd7070Spatrick if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
5064e5dd7070Spatrick if (ObjCMethod->isClassMethod() &&
5065e5dd7070Spatrick ObjCMethod->getSelector().getAsString() == "load") {
5066e5dd7070Spatrick Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
5067e5dd7070Spatrick << 0;
5068e5dd7070Spatrick ObjCMethod->dropAttr<AvailabilityAttr>();
5069e5dd7070Spatrick }
5070e5dd7070Spatrick }
5071e5dd7070Spatrick
5072e5dd7070Spatrick // Insert the invisible arguments, self and _cmd!
5073e5dd7070Spatrick ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
5074e5dd7070Spatrick
5075e5dd7070Spatrick ActOnDocumentableDecl(ObjCMethod);
5076e5dd7070Spatrick
5077e5dd7070Spatrick return ObjCMethod;
5078e5dd7070Spatrick }
5079e5dd7070Spatrick
CheckObjCDeclScope(Decl * D)5080e5dd7070Spatrick bool Sema::CheckObjCDeclScope(Decl *D) {
5081e5dd7070Spatrick // Following is also an error. But it is caused by a missing @end
5082e5dd7070Spatrick // and diagnostic is issued elsewhere.
5083e5dd7070Spatrick if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
5084e5dd7070Spatrick return false;
5085e5dd7070Spatrick
5086e5dd7070Spatrick // If we switched context to translation unit while we are still lexically in
5087e5dd7070Spatrick // an objc container, it means the parser missed emitting an error.
5088e5dd7070Spatrick if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
5089e5dd7070Spatrick return false;
5090e5dd7070Spatrick
5091e5dd7070Spatrick Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
5092e5dd7070Spatrick D->setInvalidDecl();
5093e5dd7070Spatrick
5094e5dd7070Spatrick return true;
5095e5dd7070Spatrick }
5096e5dd7070Spatrick
5097e5dd7070Spatrick /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
5098e5dd7070Spatrick /// instance variables of ClassName into Decls.
ActOnDefs(Scope * S,Decl * TagD,SourceLocation DeclStart,IdentifierInfo * ClassName,SmallVectorImpl<Decl * > & Decls)5099e5dd7070Spatrick void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
5100e5dd7070Spatrick IdentifierInfo *ClassName,
5101e5dd7070Spatrick SmallVectorImpl<Decl*> &Decls) {
5102e5dd7070Spatrick // Check that ClassName is a valid class
5103e5dd7070Spatrick ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
5104e5dd7070Spatrick if (!Class) {
5105e5dd7070Spatrick Diag(DeclStart, diag::err_undef_interface) << ClassName;
5106e5dd7070Spatrick return;
5107e5dd7070Spatrick }
5108e5dd7070Spatrick if (LangOpts.ObjCRuntime.isNonFragile()) {
5109e5dd7070Spatrick Diag(DeclStart, diag::err_atdef_nonfragile_interface);
5110e5dd7070Spatrick return;
5111e5dd7070Spatrick }
5112e5dd7070Spatrick
5113e5dd7070Spatrick // Collect the instance variables
5114e5dd7070Spatrick SmallVector<const ObjCIvarDecl*, 32> Ivars;
5115e5dd7070Spatrick Context.DeepCollectObjCIvars(Class, true, Ivars);
5116e5dd7070Spatrick // For each ivar, create a fresh ObjCAtDefsFieldDecl.
5117e5dd7070Spatrick for (unsigned i = 0; i < Ivars.size(); i++) {
5118e5dd7070Spatrick const FieldDecl* ID = Ivars[i];
5119e5dd7070Spatrick RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
5120e5dd7070Spatrick Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
5121e5dd7070Spatrick /*FIXME: StartL=*/ID->getLocation(),
5122e5dd7070Spatrick ID->getLocation(),
5123e5dd7070Spatrick ID->getIdentifier(), ID->getType(),
5124e5dd7070Spatrick ID->getBitWidth());
5125e5dd7070Spatrick Decls.push_back(FD);
5126e5dd7070Spatrick }
5127e5dd7070Spatrick
5128e5dd7070Spatrick // Introduce all of these fields into the appropriate scope.
5129e5dd7070Spatrick for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
5130e5dd7070Spatrick D != Decls.end(); ++D) {
5131e5dd7070Spatrick FieldDecl *FD = cast<FieldDecl>(*D);
5132e5dd7070Spatrick if (getLangOpts().CPlusPlus)
5133e5dd7070Spatrick PushOnScopeChains(FD, S);
5134e5dd7070Spatrick else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
5135e5dd7070Spatrick Record->addDecl(FD);
5136e5dd7070Spatrick }
5137e5dd7070Spatrick }
5138e5dd7070Spatrick
5139e5dd7070Spatrick /// Build a type-check a new Objective-C exception variable declaration.
BuildObjCExceptionDecl(TypeSourceInfo * TInfo,QualType T,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,bool Invalid)5140e5dd7070Spatrick VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
5141e5dd7070Spatrick SourceLocation StartLoc,
5142e5dd7070Spatrick SourceLocation IdLoc,
5143e5dd7070Spatrick IdentifierInfo *Id,
5144e5dd7070Spatrick bool Invalid) {
5145e5dd7070Spatrick // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5146e5dd7070Spatrick // duration shall not be qualified by an address-space qualifier."
5147e5dd7070Spatrick // Since all parameters have automatic store duration, they can not have
5148e5dd7070Spatrick // an address space.
5149e5dd7070Spatrick if (T.getAddressSpace() != LangAS::Default) {
5150e5dd7070Spatrick Diag(IdLoc, diag::err_arg_with_address_space);
5151e5dd7070Spatrick Invalid = true;
5152e5dd7070Spatrick }
5153e5dd7070Spatrick
5154e5dd7070Spatrick // An @catch parameter must be an unqualified object pointer type;
5155e5dd7070Spatrick // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
5156e5dd7070Spatrick if (Invalid) {
5157e5dd7070Spatrick // Don't do any further checking.
5158e5dd7070Spatrick } else if (T->isDependentType()) {
5159e5dd7070Spatrick // Okay: we don't know what this type will instantiate to.
5160e5dd7070Spatrick } else if (T->isObjCQualifiedIdType()) {
5161e5dd7070Spatrick Invalid = true;
5162e5dd7070Spatrick Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
5163e5dd7070Spatrick } else if (T->isObjCIdType()) {
5164e5dd7070Spatrick // Okay: we don't know what this type will instantiate to.
5165e5dd7070Spatrick } else if (!T->isObjCObjectPointerType()) {
5166e5dd7070Spatrick Invalid = true;
5167e5dd7070Spatrick Diag(IdLoc, diag::err_catch_param_not_objc_type);
5168e5dd7070Spatrick } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) {
5169e5dd7070Spatrick Invalid = true;
5170e5dd7070Spatrick Diag(IdLoc, diag::err_catch_param_not_objc_type);
5171e5dd7070Spatrick }
5172e5dd7070Spatrick
5173e5dd7070Spatrick VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
5174e5dd7070Spatrick T, TInfo, SC_None);
5175e5dd7070Spatrick New->setExceptionVariable(true);
5176e5dd7070Spatrick
5177e5dd7070Spatrick // In ARC, infer 'retaining' for variables of retainable type.
5178e5dd7070Spatrick if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
5179e5dd7070Spatrick Invalid = true;
5180e5dd7070Spatrick
5181e5dd7070Spatrick if (Invalid)
5182e5dd7070Spatrick New->setInvalidDecl();
5183e5dd7070Spatrick return New;
5184e5dd7070Spatrick }
5185e5dd7070Spatrick
ActOnObjCExceptionDecl(Scope * S,Declarator & D)5186e5dd7070Spatrick Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
5187e5dd7070Spatrick const DeclSpec &DS = D.getDeclSpec();
5188e5dd7070Spatrick
5189e5dd7070Spatrick // We allow the "register" storage class on exception variables because
5190e5dd7070Spatrick // GCC did, but we drop it completely. Any other storage class is an error.
5191e5dd7070Spatrick if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
5192e5dd7070Spatrick Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
5193e5dd7070Spatrick << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
5194e5dd7070Spatrick } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5195e5dd7070Spatrick Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
5196e5dd7070Spatrick << DeclSpec::getSpecifierName(SCS);
5197e5dd7070Spatrick }
5198e5dd7070Spatrick if (DS.isInlineSpecified())
5199e5dd7070Spatrick Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5200e5dd7070Spatrick << getLangOpts().CPlusPlus17;
5201e5dd7070Spatrick if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
5202e5dd7070Spatrick Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
5203e5dd7070Spatrick diag::err_invalid_thread)
5204e5dd7070Spatrick << DeclSpec::getSpecifierName(TSCS);
5205e5dd7070Spatrick D.getMutableDeclSpec().ClearStorageClassSpecs();
5206e5dd7070Spatrick
5207e5dd7070Spatrick DiagnoseFunctionSpecifiers(D.getDeclSpec());
5208e5dd7070Spatrick
5209e5dd7070Spatrick // Check that there are no default arguments inside the type of this
5210e5dd7070Spatrick // exception object (C++ only).
5211e5dd7070Spatrick if (getLangOpts().CPlusPlus)
5212e5dd7070Spatrick CheckExtraCXXDefaultArguments(D);
5213e5dd7070Spatrick
5214e5dd7070Spatrick TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
5215e5dd7070Spatrick QualType ExceptionType = TInfo->getType();
5216e5dd7070Spatrick
5217e5dd7070Spatrick VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
5218e5dd7070Spatrick D.getSourceRange().getBegin(),
5219e5dd7070Spatrick D.getIdentifierLoc(),
5220e5dd7070Spatrick D.getIdentifier(),
5221e5dd7070Spatrick D.isInvalidType());
5222e5dd7070Spatrick
5223e5dd7070Spatrick // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5224e5dd7070Spatrick if (D.getCXXScopeSpec().isSet()) {
5225e5dd7070Spatrick Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
5226e5dd7070Spatrick << D.getCXXScopeSpec().getRange();
5227e5dd7070Spatrick New->setInvalidDecl();
5228e5dd7070Spatrick }
5229e5dd7070Spatrick
5230e5dd7070Spatrick // Add the parameter declaration into this scope.
5231e5dd7070Spatrick S->AddDecl(New);
5232e5dd7070Spatrick if (D.getIdentifier())
5233e5dd7070Spatrick IdResolver.AddDecl(New);
5234e5dd7070Spatrick
5235e5dd7070Spatrick ProcessDeclAttributes(S, New, D);
5236e5dd7070Spatrick
5237e5dd7070Spatrick if (New->hasAttr<BlocksAttr>())
5238e5dd7070Spatrick Diag(New->getLocation(), diag::err_block_on_nonlocal);
5239e5dd7070Spatrick return New;
5240e5dd7070Spatrick }
5241e5dd7070Spatrick
5242e5dd7070Spatrick /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
5243e5dd7070Spatrick /// initialization.
CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl * OI,SmallVectorImpl<ObjCIvarDecl * > & Ivars)5244e5dd7070Spatrick void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
5245e5dd7070Spatrick SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
5246e5dd7070Spatrick for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
5247e5dd7070Spatrick Iv= Iv->getNextIvar()) {
5248e5dd7070Spatrick QualType QT = Context.getBaseElementType(Iv->getType());
5249e5dd7070Spatrick if (QT->isRecordType())
5250e5dd7070Spatrick Ivars.push_back(Iv);
5251e5dd7070Spatrick }
5252e5dd7070Spatrick }
5253e5dd7070Spatrick
DiagnoseUseOfUnimplementedSelectors()5254e5dd7070Spatrick void Sema::DiagnoseUseOfUnimplementedSelectors() {
5255e5dd7070Spatrick // Load referenced selectors from the external source.
5256e5dd7070Spatrick if (ExternalSource) {
5257e5dd7070Spatrick SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
5258e5dd7070Spatrick ExternalSource->ReadReferencedSelectors(Sels);
5259e5dd7070Spatrick for (unsigned I = 0, N = Sels.size(); I != N; ++I)
5260e5dd7070Spatrick ReferencedSelectors[Sels[I].first] = Sels[I].second;
5261e5dd7070Spatrick }
5262e5dd7070Spatrick
5263e5dd7070Spatrick // Warning will be issued only when selector table is
5264e5dd7070Spatrick // generated (which means there is at lease one implementation
5265e5dd7070Spatrick // in the TU). This is to match gcc's behavior.
5266e5dd7070Spatrick if (ReferencedSelectors.empty() ||
5267e5dd7070Spatrick !Context.AnyObjCImplementation())
5268e5dd7070Spatrick return;
5269e5dd7070Spatrick for (auto &SelectorAndLocation : ReferencedSelectors) {
5270e5dd7070Spatrick Selector Sel = SelectorAndLocation.first;
5271e5dd7070Spatrick SourceLocation Loc = SelectorAndLocation.second;
5272e5dd7070Spatrick if (!LookupImplementedMethodInGlobalPool(Sel))
5273e5dd7070Spatrick Diag(Loc, diag::warn_unimplemented_selector) << Sel;
5274e5dd7070Spatrick }
5275e5dd7070Spatrick }
5276e5dd7070Spatrick
5277e5dd7070Spatrick ObjCIvarDecl *
GetIvarBackingPropertyAccessor(const ObjCMethodDecl * Method,const ObjCPropertyDecl * & PDecl) const5278e5dd7070Spatrick Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
5279e5dd7070Spatrick const ObjCPropertyDecl *&PDecl) const {
5280e5dd7070Spatrick if (Method->isClassMethod())
5281e5dd7070Spatrick return nullptr;
5282e5dd7070Spatrick const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
5283e5dd7070Spatrick if (!IDecl)
5284e5dd7070Spatrick return nullptr;
5285e5dd7070Spatrick Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
5286e5dd7070Spatrick /*shallowCategoryLookup=*/false,
5287e5dd7070Spatrick /*followSuper=*/false);
5288e5dd7070Spatrick if (!Method || !Method->isPropertyAccessor())
5289e5dd7070Spatrick return nullptr;
5290e5dd7070Spatrick if ((PDecl = Method->findPropertyDecl()))
5291e5dd7070Spatrick if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5292e5dd7070Spatrick // property backing ivar must belong to property's class
5293e5dd7070Spatrick // or be a private ivar in class's implementation.
5294e5dd7070Spatrick // FIXME. fix the const-ness issue.
5295e5dd7070Spatrick IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5296e5dd7070Spatrick IV->getIdentifier());
5297e5dd7070Spatrick return IV;
5298e5dd7070Spatrick }
5299e5dd7070Spatrick return nullptr;
5300e5dd7070Spatrick }
5301e5dd7070Spatrick
5302e5dd7070Spatrick namespace {
5303e5dd7070Spatrick /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
5304e5dd7070Spatrick /// accessor references the backing ivar.
5305e5dd7070Spatrick class UnusedBackingIvarChecker :
5306e5dd7070Spatrick public RecursiveASTVisitor<UnusedBackingIvarChecker> {
5307e5dd7070Spatrick public:
5308e5dd7070Spatrick Sema &S;
5309e5dd7070Spatrick const ObjCMethodDecl *Method;
5310e5dd7070Spatrick const ObjCIvarDecl *IvarD;
5311e5dd7070Spatrick bool AccessedIvar;
5312e5dd7070Spatrick bool InvokedSelfMethod;
5313e5dd7070Spatrick
UnusedBackingIvarChecker(Sema & S,const ObjCMethodDecl * Method,const ObjCIvarDecl * IvarD)5314e5dd7070Spatrick UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5315e5dd7070Spatrick const ObjCIvarDecl *IvarD)
5316e5dd7070Spatrick : S(S), Method(Method), IvarD(IvarD),
5317e5dd7070Spatrick AccessedIvar(false), InvokedSelfMethod(false) {
5318e5dd7070Spatrick assert(IvarD);
5319e5dd7070Spatrick }
5320e5dd7070Spatrick
VisitObjCIvarRefExpr(ObjCIvarRefExpr * E)5321e5dd7070Spatrick bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5322e5dd7070Spatrick if (E->getDecl() == IvarD) {
5323e5dd7070Spatrick AccessedIvar = true;
5324e5dd7070Spatrick return false;
5325e5dd7070Spatrick }
5326e5dd7070Spatrick return true;
5327e5dd7070Spatrick }
5328e5dd7070Spatrick
VisitObjCMessageExpr(ObjCMessageExpr * E)5329e5dd7070Spatrick bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5330e5dd7070Spatrick if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5331e5dd7070Spatrick S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5332e5dd7070Spatrick InvokedSelfMethod = true;
5333e5dd7070Spatrick }
5334e5dd7070Spatrick return true;
5335e5dd7070Spatrick }
5336e5dd7070Spatrick };
5337e5dd7070Spatrick } // end anonymous namespace
5338e5dd7070Spatrick
DiagnoseUnusedBackingIvarInAccessor(Scope * S,const ObjCImplementationDecl * ImplD)5339e5dd7070Spatrick void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5340e5dd7070Spatrick const ObjCImplementationDecl *ImplD) {
5341e5dd7070Spatrick if (S->hasUnrecoverableErrorOccurred())
5342e5dd7070Spatrick return;
5343e5dd7070Spatrick
5344e5dd7070Spatrick for (const auto *CurMethod : ImplD->instance_methods()) {
5345e5dd7070Spatrick unsigned DIAG = diag::warn_unused_property_backing_ivar;
5346e5dd7070Spatrick SourceLocation Loc = CurMethod->getLocation();
5347e5dd7070Spatrick if (Diags.isIgnored(DIAG, Loc))
5348e5dd7070Spatrick continue;
5349e5dd7070Spatrick
5350e5dd7070Spatrick const ObjCPropertyDecl *PDecl;
5351e5dd7070Spatrick const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5352e5dd7070Spatrick if (!IV)
5353e5dd7070Spatrick continue;
5354e5dd7070Spatrick
5355e5dd7070Spatrick if (CurMethod->isSynthesizedAccessorStub())
5356e5dd7070Spatrick continue;
5357e5dd7070Spatrick
5358e5dd7070Spatrick UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5359e5dd7070Spatrick Checker.TraverseStmt(CurMethod->getBody());
5360e5dd7070Spatrick if (Checker.AccessedIvar)
5361e5dd7070Spatrick continue;
5362e5dd7070Spatrick
5363e5dd7070Spatrick // Do not issue this warning if backing ivar is used somewhere and accessor
5364e5dd7070Spatrick // implementation makes a self call. This is to prevent false positive in
5365e5dd7070Spatrick // cases where the ivar is accessed by another method that the accessor
5366e5dd7070Spatrick // delegates to.
5367e5dd7070Spatrick if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5368e5dd7070Spatrick Diag(Loc, DIAG) << IV;
5369e5dd7070Spatrick Diag(PDecl->getLocation(), diag::note_property_declare);
5370e5dd7070Spatrick }
5371e5dd7070Spatrick }
5372e5dd7070Spatrick }
5373