blob: 748285b73e840c21942e5309087853a4f89a9ebd [file] [log] [blame]
Chris Lattnerda463fe2007-12-12 07:09:47 +00001//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerda463fe2007-12-12 07:09:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
Mehdi Amini9670f842016-07-18 19:02:11 +000014#include "TypeLocBuilder.h"
John McCall31168b02011-06-15 23:02:42 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclObjC.h"
Steve Naroff157599f2009-03-03 14:49:36 +000019#include "clang/AST/Expr.h"
John McCall31168b02011-06-15 23:02:42 +000020#include "clang/AST/ExprObjC.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/AST/RecursiveASTVisitor.h"
John McCall31168b02011-06-15 23:02:42 +000022#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Lookup.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000027#include "clang/Sema/SemaInternal.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000028#include "llvm/ADT/DenseMap.h"
John McCalla1e130b2010-08-25 07:03:20 +000029#include "llvm/ADT/DenseSet.h"
30
Chris Lattnerda463fe2007-12-12 07:09:47 +000031using namespace clang;
32
John McCall31168b02011-06-15 23:02:42 +000033/// Check whether the given method, which must be in the 'init'
34/// family, is a valid member of that family.
35///
36/// \param receiverTypeIfCall - if null, check this as if declaring it;
37/// if non-null, check this as if making a call to it with the given
38/// receiver type
39///
40/// \return true to indicate that there was an error and appropriate
41/// actions were taken
42bool Sema::checkInitMethod(ObjCMethodDecl *method,
43 QualType receiverTypeIfCall) {
44 if (method->isInvalidDecl()) return true;
45
46 // This castAs is safe: methods that don't return an object
47 // pointer won't be inferred as inits and will reject an explicit
48 // objc_method_family(init).
49
50 // We ignore protocols here. Should we? What about Class?
51
Alp Toker314cc812014-01-25 16:55:45 +000052 const ObjCObjectType *result =
53 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCall31168b02011-06-15 23:02:42 +000054
55 if (result->isObjCId()) {
56 return false;
57 } else if (result->isObjCClass()) {
58 // fall through: always an error
59 } else {
60 ObjCInterfaceDecl *resultClass = result->getInterface();
61 assert(resultClass && "unexpected object type!");
62
63 // It's okay for the result type to still be a forward declaration
64 // if we're checking an interface declaration.
Douglas Gregordc9166c2011-12-15 20:29:51 +000065 if (!resultClass->hasDefinition()) {
John McCall31168b02011-06-15 23:02:42 +000066 if (receiverTypeIfCall.isNull() &&
67 !isa<ObjCImplementationDecl>(method->getDeclContext()))
68 return false;
69
70 // Otherwise, we try to compare class types.
71 } else {
72 // If this method was declared in a protocol, we can't check
73 // anything unless we have a receiver type that's an interface.
Craig Topperc3ec1492014-05-26 06:22:03 +000074 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCall31168b02011-06-15 23:02:42 +000075 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76 if (receiverTypeIfCall.isNull())
77 return false;
78
79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
80 ->getInterfaceDecl();
81
82 // This can be null for calls to e.g. id<Foo>.
83 if (!receiverClass) return false;
84 } else {
85 receiverClass = method->getClassInterface();
86 assert(receiverClass && "method not associated with a class!");
87 }
88
89 // If either class is a subclass of the other, it's fine.
90 if (receiverClass->isSuperClassOf(resultClass) ||
91 resultClass->isSuperClassOf(receiverClass))
92 return false;
93 }
94 }
95
96 SourceLocation loc = method->getLocation();
97
98 // If we're in a system header, and this is not a call, just make
99 // the method unusable.
100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
John McCallc6af8c62015-10-28 05:03:19 +0000101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
John McCall31168b02011-06-15 23:02:42 +0000103 return true;
104 }
105
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
109 return true;
110}
111
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000112void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000113 const ObjCMethodDecl *Overridden) {
Douglas Gregor33823722011-06-11 01:09:30 +0000114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000120 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000121 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +0000122
123 // Figure out which class this method is part of, if any.
124 ObjCInterfaceDecl *CurrentClass
125 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
126 if (!CurrentClass) {
127 DeclContext *DC = NewMethod->getDeclContext();
128 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
129 CurrentClass = Cat->getClassInterface();
130 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
131 CurrentClass = Impl->getClassInterface();
132 else if (ObjCCategoryImplDecl *CatImpl
133 = dyn_cast<ObjCCategoryImplDecl>(DC))
134 CurrentClass = CatImpl->getClassInterface();
135 }
136
137 if (CurrentClass) {
138 Diag(NewMethod->getLocation(),
139 diag::warn_related_result_type_compatibility_class)
140 << Context.getObjCInterfaceType(CurrentClass)
141 << ResultType
142 << ResultTypeRange;
143 } else {
144 Diag(NewMethod->getLocation(),
145 diag::warn_related_result_type_compatibility_protocol)
146 << ResultType
147 << ResultTypeRange;
148 }
149
Douglas Gregorbab8a962011-09-08 01:46:34 +0000150 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000152 diag::note_related_result_type_family)
153 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000154 << Family;
155 else
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000158 }
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000159
160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000163 getLangOpts().ObjCAutoRefCount
164 ? diag::err_nsreturns_retained_attribute_mismatch
165 : diag::warn_nsreturns_retained_attribute_mismatch)
166 << 1;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000167 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
168 }
169 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
170 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
171 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000172 getLangOpts().ObjCAutoRefCount
173 ? diag::err_nsreturns_retained_attribute_mismatch
174 : diag::warn_nsreturns_retained_attribute_mismatch)
175 << 0;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000176 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
177 }
178
179 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
180 oe = Overridden->param_end();
181 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
182 ne = NewMethod->param_end();
183 ni != ne && oi != oe; ++ni, ++oi) {
184 const ParmVarDecl *oldDecl = (*oi);
185 ParmVarDecl *newDecl = (*ni);
186 if (newDecl->hasAttr<NSConsumedAttr>() !=
187 oldDecl->hasAttr<NSConsumedAttr>()) {
Alex Lorenz26d282f2018-01-03 23:52:42 +0000188 Diag(newDecl->getLocation(),
189 getLangOpts().ObjCAutoRefCount
190 ? diag::err_nsconsumed_attribute_mismatch
191 : diag::warn_nsconsumed_attribute_mismatch);
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000192 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000193 }
Akira Hatanaka98a49332017-09-22 00:41:05 +0000194
195 // A parameter of the overriding method should be annotated with noescape
196 // if the corresponding parameter of the overridden method is annotated.
197 if (oldDecl->hasAttr<NoEscapeAttr>() && !newDecl->hasAttr<NoEscapeAttr>()) {
198 Diag(newDecl->getLocation(),
199 diag::warn_overriding_method_missing_noescape);
200 Diag(oldDecl->getLocation(), diag::note_overridden_marked_noescape);
201 }
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000202 }
Douglas Gregor33823722011-06-11 01:09:30 +0000203}
204
John McCall31168b02011-06-15 23:02:42 +0000205/// \brief Check a method declaration for compatibility with the Objective-C
206/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000207bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000208 ObjCMethodFamily family = method->getMethodFamily();
209 switch (family) {
210 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000211 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000212 case OMF_retain:
213 case OMF_release:
214 case OMF_autorelease:
215 case OMF_retainCount:
216 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000217 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000218 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000219 return false;
220
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000221 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000222 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000223 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000224 if (ResultTypeRange.isInvalid())
Richard Smithf8812672016-12-02 22:38:31 +0000225 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000226 << method->getReturnType()
227 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000228 else
Richard Smithf8812672016-12-02 22:38:31 +0000229 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000230 << method->getReturnType()
231 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000232 return true;
233 }
234 return false;
235
John McCall31168b02011-06-15 23:02:42 +0000236 case OMF_init:
237 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000238 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000239 return true;
240
Aaron Ballman36a53502014-01-16 13:03:14 +0000241 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000242
243 // Don't add a second copy of this attribute, but otherwise don't
244 // let it be suppressed.
245 if (method->hasAttr<NSReturnsRetainedAttr>())
246 return false;
247 break;
248
249 case OMF_alloc:
250 case OMF_copy:
251 case OMF_mutableCopy:
252 case OMF_new:
253 if (method->hasAttr<NSReturnsRetainedAttr>() ||
254 method->hasAttr<NSReturnsNotRetainedAttr>() ||
255 method->hasAttr<NSReturnsAutoreleasedAttr>())
256 return false;
257 break;
258 }
259
Aaron Ballman36a53502014-01-16 13:03:14 +0000260 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000261 return false;
262}
263
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000264static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
265 SourceLocation ImplLoc) {
266 if (!ND)
267 return;
268 bool IsCategory = false;
Alex Lorenze1088dc2017-07-13 16:37:11 +0000269 AvailabilityResult Availability = ND->getAvailability();
270 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000271 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000272 if (Availability != AR_Unavailable)
273 return;
274 // Warn about implementing unavailable methods.
275 S.Diag(ImplLoc, diag::warn_unavailable_def);
276 S.Diag(ND->getLocation(), diag::note_method_declared_at)
277 << ND->getDeclName();
278 return;
279 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000280 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
281 if (!CD->getClassInterface()->isDeprecated())
282 return;
283 ND = CD->getClassInterface();
284 IsCategory = true;
285 } else
286 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000287 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000288 S.Diag(ImplLoc, diag::warn_deprecated_def)
289 << (isa<ObjCMethodDecl>(ND)
290 ? /*Method*/ 0
291 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
292 : /*Class*/ 1);
293 if (isa<ObjCMethodDecl>(ND))
294 S.Diag(ND->getLocation(), diag::note_method_declared_at)
295 << ND->getDeclName();
296 else
297 S.Diag(ND->getLocation(), diag::note_previous_decl)
298 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000299}
300
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000301/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
302/// pool.
303void Sema::AddAnyMethodToGlobalPool(Decl *D) {
304 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
305
306 // If we don't have a valid method decl, simply return.
307 if (!MDecl)
308 return;
309 if (MDecl->isInstanceMethod())
310 AddInstanceMethodToGlobalPool(MDecl, true);
311 else
312 AddFactoryMethodToGlobalPool(MDecl, true);
313}
314
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000315/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
316/// has explicit ownership attribute; false otherwise.
317static bool
318HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
319 QualType T = Param->getType();
320
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000321 if (const PointerType *PT = T->getAs<PointerType>()) {
322 T = PT->getPointeeType();
323 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
324 T = RT->getPointeeType();
325 } else {
326 return true;
327 }
328
329 // If we have a lifetime qualifier, but it's local, we must have
330 // inferred it. So, it is implicit.
331 return !T.getLocalQualifiers().hasObjCLifetime();
332}
333
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000334/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
335/// and user declared, in the method definition's AST.
336void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000337 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000338 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000339
Steve Naroff542cd5d2008-07-25 17:57:26 +0000340 // If we don't have a valid method decl, simply return.
341 if (!MDecl)
342 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000343
Chris Lattnerda463fe2007-12-12 07:09:47 +0000344 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000345 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000346 PushFunctionScope();
347
Chris Lattnerda463fe2007-12-12 07:09:47 +0000348 // Create Decl objects for each parameter, entrring them in the scope for
349 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000350
351 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000352 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000353
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000354 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
355 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000356
Reid Kleckner5a115802013-06-24 14:38:26 +0000357 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000358 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000359 /*CheckParameterNames=*/false);
360
Chris Lattner58258242008-04-10 02:22:51 +0000361 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000362 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000363 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000364 getLangOpts().ObjCAutoRefCount &&
365 !HasExplicitOwnershipAttr(*this, Param))
366 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
367 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000368
Aaron Ballman43b68be2014-03-07 17:50:17 +0000369 if (Param->getIdentifier())
370 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000371 }
John McCall31168b02011-06-15 23:02:42 +0000372
373 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000374 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000375 switch (MDecl->getMethodFamily()) {
376 case OMF_retain:
377 case OMF_retainCount:
378 case OMF_release:
379 case OMF_autorelease:
380 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000381 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000382 break;
383
384 case OMF_None:
385 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000386 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000387 case OMF_alloc:
388 case OMF_init:
389 case OMF_mutableCopy:
390 case OMF_copy:
391 case OMF_new:
392 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000393 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000394 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000395 break;
396 }
397 }
398
Nico Weber715abaf2011-08-22 17:25:57 +0000399 // Warn on deprecated methods under -Wdeprecated-implementations,
400 // and prepare for warning on missing super calls.
401 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000402 ObjCMethodDecl *IMD =
403 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
404
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000405 if (IMD) {
406 ObjCImplDecl *ImplDeclOfMethodDef =
407 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
408 ObjCContainerDecl *ContDeclOfMethodDecl =
409 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000410 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000411 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
412 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000413 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
414 if (CD->IsClassExtension()) {
415 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
416 ImplDeclOfMethodDecl = OID->getImplementation();
417 } else
418 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000419 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000420 // No need to issue deprecated warning if deprecated mehod in class/category
421 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000422 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000423 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000424 }
Nico Weber715abaf2011-08-22 17:25:57 +0000425
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000426 if (MDecl->getMethodFamily() == OMF_init) {
427 if (MDecl->isDesignatedInitializerForTheInterface()) {
428 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000429 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000430 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000431 } else if (IC->hasDesignatedInitializers()) {
432 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000433 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000434 }
435 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000436
Nico Weber1fb82662011-08-28 22:35:17 +0000437 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000438 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
439 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
440 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000441 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000442 ObjCMethodFamily Family = MDecl->getMethodFamily();
443 if (Family == OMF_dealloc) {
444 if (!(getLangOpts().ObjCAutoRefCount ||
445 getLangOpts().getGC() == LangOptions::GCOnly))
446 getCurFunction()->ObjCShouldCallSuper = true;
447
448 } else if (Family == OMF_finalize) {
449 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
450 getCurFunction()->ObjCShouldCallSuper = true;
451
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000452 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000453 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000454 SuperClass->lookupMethod(MDecl->getSelector(),
455 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000456 getCurFunction()->ObjCShouldCallSuper =
457 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000458 }
Nico Weber1fb82662011-08-28 22:35:17 +0000459 }
Nico Weber715abaf2011-08-22 17:25:57 +0000460 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000461}
462
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000463namespace {
464
465// Callback to only accept typo corrections that are Objective-C classes.
466// If an ObjCInterfaceDecl* is given to the constructor, then the validation
467// function will reject corrections to that class.
468class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
469 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000470 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000471 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
472 : CurrentIDecl(IDecl) {}
473
Craig Toppere14c0f82014-03-12 04:55:44 +0000474 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000475 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
476 return ID && !declaresSameEntity(ID, CurrentIDecl);
477 }
478
479 private:
480 ObjCInterfaceDecl *CurrentIDecl;
481};
482
Hans Wennborgdcfba332015-10-06 23:40:43 +0000483} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000484
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000485static void diagnoseUseOfProtocols(Sema &TheSema,
486 ObjCContainerDecl *CD,
487 ObjCProtocolDecl *const *ProtoRefs,
488 unsigned NumProtoRefs,
489 const SourceLocation *ProtoLocs) {
490 assert(ProtoRefs);
491 // Diagnose availability in the context of the ObjC container.
492 Sema::ContextRAII SavedContext(TheSema, CD);
493 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000494 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
495 /*UnknownObjCClass=*/nullptr,
496 /*ObjCPropertyAccess=*/false,
497 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000498 }
499}
500
Douglas Gregore9d95f12015-07-07 03:57:35 +0000501void Sema::
502ActOnSuperClassOfClassInterface(Scope *S,
503 SourceLocation AtInterfaceLoc,
504 ObjCInterfaceDecl *IDecl,
505 IdentifierInfo *ClassName,
506 SourceLocation ClassLoc,
507 IdentifierInfo *SuperName,
508 SourceLocation SuperLoc,
509 ArrayRef<ParsedType> SuperTypeArgs,
510 SourceRange SuperTypeArgsRange) {
511 // Check if a different kind of symbol declared in this scope.
512 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
513 LookupOrdinaryName);
514
515 if (!PrevDecl) {
516 // Try to correct for a typo in the superclass name without correcting
517 // to the class we're defining.
518 if (TypoCorrection Corrected = CorrectTypo(
519 DeclarationNameInfo(SuperName, SuperLoc),
520 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000521 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000522 CTK_ErrorRecovery)) {
523 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
524 << SuperName << ClassName);
525 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
526 }
527 }
528
529 if (declaresSameEntity(PrevDecl, IDecl)) {
530 Diag(SuperLoc, diag::err_recursive_superclass)
531 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
532 IDecl->setEndOfDefinitionLoc(ClassLoc);
533 } else {
534 ObjCInterfaceDecl *SuperClassDecl =
535 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
536 QualType SuperClassType;
537
538 // Diagnose classes that inherit from deprecated classes.
539 if (SuperClassDecl) {
540 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
541 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
542 }
543
Hans Wennborgdcfba332015-10-06 23:40:43 +0000544 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000545 // The previous declaration was not a class decl. Check if we have a
546 // typedef. If we do, get the underlying class type.
547 if (const TypedefNameDecl *TDecl =
548 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
549 QualType T = TDecl->getUnderlyingType();
550 if (T->isObjCObjectType()) {
551 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
552 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
553 SuperClassType = Context.getTypeDeclType(TDecl);
554
555 // This handles the following case:
556 // @interface NewI @end
557 // typedef NewI DeprI __attribute__((deprecated("blah")))
558 // @interface SI : DeprI /* warn here */ @end
559 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
560 }
561 }
562 }
563
564 // This handles the following case:
565 //
566 // typedef int SuperClass;
567 // @interface MyClass : SuperClass {} @end
568 //
569 if (!SuperClassDecl) {
570 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
571 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
572 }
573 }
574
575 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
576 if (!SuperClassDecl)
577 Diag(SuperLoc, diag::err_undef_superclass)
578 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
579 else if (RequireCompleteType(SuperLoc,
580 SuperClassType,
581 diag::err_forward_superclass,
582 SuperClassDecl->getDeclName(),
583 ClassName,
584 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000585 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000586 SuperClassType = QualType();
587 }
588 }
589
590 if (SuperClassType.isNull()) {
591 assert(!SuperClassDecl && "Failed to set SuperClassType?");
592 return;
593 }
594
595 // Handle type arguments on the superclass.
596 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000597 if (!SuperTypeArgs.empty()) {
598 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
599 S,
600 SuperLoc,
601 CreateParsedType(SuperClassType,
602 nullptr),
603 SuperTypeArgsRange.getBegin(),
604 SuperTypeArgs,
605 SuperTypeArgsRange.getEnd(),
606 SourceLocation(),
607 { },
608 { },
609 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000610 if (!fullSuperClassType.isUsable())
611 return;
612
613 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
614 &SuperClassTInfo);
615 }
616
617 if (!SuperClassTInfo) {
618 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
619 SuperLoc);
620 }
621
622 IDecl->setSuperClass(SuperClassTInfo);
623 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
624 }
625}
626
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000627DeclResult Sema::actOnObjCTypeParam(Scope *S,
628 ObjCTypeParamVariance variance,
629 SourceLocation varianceLoc,
630 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000631 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000632 SourceLocation paramLoc,
633 SourceLocation colonLoc,
634 ParsedType parsedTypeBound) {
635 // If there was an explicitly-provided type bound, check it.
636 TypeSourceInfo *typeBoundInfo = nullptr;
637 if (parsedTypeBound) {
638 // The type bound can be any Objective-C pointer type.
639 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
640 if (typeBound->isObjCObjectPointerType()) {
641 // okay
642 } else if (typeBound->isObjCObjectType()) {
643 // The user forgot the * on an Objective-C pointer type, e.g.,
644 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000645 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000646 typeBoundInfo->getTypeLoc().getEndLoc());
647 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
648 diag::err_objc_type_param_bound_missing_pointer)
649 << typeBound << paramName
650 << FixItHint::CreateInsertion(starLoc, " *");
651
652 // Create a new type location builder so we can update the type
653 // location information we have.
654 TypeLocBuilder builder;
655 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
656
657 // Create the Objective-C pointer type.
658 typeBound = Context.getObjCObjectPointerType(typeBound);
659 ObjCObjectPointerTypeLoc newT
660 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
661 newT.setStarLoc(starLoc);
662
663 // Form the new type source information.
664 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
665 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000666 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000667 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
668 diag::err_objc_type_param_bound_nonobject)
669 << typeBound << paramName;
670
671 // Forget the bound; we'll default to id later.
672 typeBoundInfo = nullptr;
673 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000674
John McCall69975252015-09-23 22:14:21 +0000675 // Type bounds cannot have qualifiers (even indirectly) or explicit
676 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000677 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000678 QualType typeBound = typeBoundInfo->getType();
679 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
680 if (qual || typeBound.hasQualifiers()) {
681 bool diagnosed = false;
682 SourceRange rangeToRemove;
683 if (qual) {
684 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
685 rangeToRemove = attr.getLocalSourceRange();
686 if (attr.getTypePtr()->getImmediateNullability()) {
687 Diag(attr.getLocStart(),
688 diag::err_objc_type_param_bound_explicit_nullability)
689 << paramName << typeBound
690 << FixItHint::CreateRemoval(rangeToRemove);
691 diagnosed = true;
692 }
693 }
694 }
695
696 if (!diagnosed) {
697 Diag(qual ? qual.getLocStart()
698 : typeBoundInfo->getTypeLoc().getLocStart(),
699 diag::err_objc_type_param_bound_qualified)
700 << paramName << typeBound << typeBound.getQualifiers().getAsString()
701 << FixItHint::CreateRemoval(rangeToRemove);
702 }
703
704 // If the type bound has qualifiers other than CVR, we need to strip
705 // them or we'll probably assert later when trying to apply new
706 // qualifiers.
707 Qualifiers quals = typeBound.getQualifiers();
708 quals.removeCVRQualifiers();
709 if (!quals.empty()) {
710 typeBoundInfo =
711 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
712 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000713 }
714 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000715 }
716
717 // If there was no explicit type bound (or we removed it due to an error),
718 // use 'id' instead.
719 if (!typeBoundInfo) {
720 colonLoc = SourceLocation();
721 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
722 }
723
724 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000725 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
726 index, paramLoc, paramName, colonLoc,
727 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000728}
729
730ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
731 SourceLocation lAngleLoc,
732 ArrayRef<Decl *> typeParamsIn,
733 SourceLocation rAngleLoc) {
734 // We know that the array only contains Objective-C type parameters.
735 ArrayRef<ObjCTypeParamDecl *>
736 typeParams(
737 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
738 typeParamsIn.size());
739
740 // Diagnose redeclarations of type parameters.
741 // We do this now because Objective-C type parameters aren't pushed into
742 // scope until later (after the instance variable block), but we want the
743 // diagnostics to occur right after we parse the type parameter list.
744 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
745 for (auto typeParam : typeParams) {
746 auto known = knownParams.find(typeParam->getIdentifier());
747 if (known != knownParams.end()) {
748 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
749 << typeParam->getIdentifier()
750 << SourceRange(known->second->getLocation());
751
752 typeParam->setInvalidDecl();
753 } else {
754 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
755
756 // Push the type parameter into scope.
757 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
758 }
759 }
760
761 // Create the parameter list.
762 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
763}
764
765void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
766 for (auto typeParam : *typeParamList) {
767 if (!typeParam->isInvalidDecl()) {
768 S->RemoveDecl(typeParam);
769 IdResolver.RemoveDecl(typeParam);
770 }
771 }
772}
773
774namespace {
775 /// The context in which an Objective-C type parameter list occurs, for use
776 /// in diagnostics.
777 enum class TypeParamListContext {
778 ForwardDeclaration,
779 Definition,
780 Category,
781 Extension
782 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000783} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000784
785/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000786/// between a category/extension and an \@interface or between an \@class and an
787/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000788static bool checkTypeParamListConsistency(Sema &S,
789 ObjCTypeParamList *prevTypeParams,
790 ObjCTypeParamList *newTypeParams,
791 TypeParamListContext newContext) {
792 // If the sizes don't match, complain about that.
793 if (prevTypeParams->size() != newTypeParams->size()) {
794 SourceLocation diagLoc;
795 if (newTypeParams->size() > prevTypeParams->size()) {
796 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
797 } else {
Craig Topper07fa1762015-11-15 02:31:46 +0000798 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000799 }
800
801 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
802 << static_cast<unsigned>(newContext)
803 << (newTypeParams->size() > prevTypeParams->size())
804 << prevTypeParams->size()
805 << newTypeParams->size();
806
807 return true;
808 }
809
810 // Match up the type parameters.
811 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
812 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
813 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
814
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000815 // Check for consistency of the variance.
816 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
817 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
818 newContext != TypeParamListContext::Definition) {
819 // When the new type parameter is invariant and is not part
820 // of the definition, just propagate the variance.
821 newTypeParam->setVariance(prevTypeParam->getVariance());
822 } else if (prevTypeParam->getVariance()
823 == ObjCTypeParamVariance::Invariant &&
824 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
825 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
826 ->getDefinition() == prevTypeParam->getDeclContext())) {
827 // When the old parameter is invariant and was not part of the
828 // definition, just ignore the difference because it doesn't
829 // matter.
830 } else {
831 {
832 // Diagnose the conflict and update the second declaration.
833 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
834 if (diagLoc.isInvalid())
835 diagLoc = newTypeParam->getLocStart();
836
837 auto diag = S.Diag(diagLoc,
838 diag::err_objc_type_param_variance_conflict)
839 << static_cast<unsigned>(newTypeParam->getVariance())
840 << newTypeParam->getDeclName()
841 << static_cast<unsigned>(prevTypeParam->getVariance())
842 << prevTypeParam->getDeclName();
843 switch (prevTypeParam->getVariance()) {
844 case ObjCTypeParamVariance::Invariant:
845 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
846 break;
847
848 case ObjCTypeParamVariance::Covariant:
849 case ObjCTypeParamVariance::Contravariant: {
850 StringRef newVarianceStr
851 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
852 ? "__covariant"
853 : "__contravariant";
854 if (newTypeParam->getVariance()
855 == ObjCTypeParamVariance::Invariant) {
856 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
857 (newVarianceStr + " ").str());
858 } else {
859 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
860 newVarianceStr);
861 }
862 }
863 }
864 }
865
866 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
867 << prevTypeParam->getDeclName();
868
869 // Override the variance.
870 newTypeParam->setVariance(prevTypeParam->getVariance());
871 }
872 }
873
Douglas Gregor85f3f952015-07-07 03:57:15 +0000874 // If the bound types match, there's nothing to do.
875 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
876 newTypeParam->getUnderlyingType()))
877 continue;
878
879 // If the new type parameter's bound was explicit, complain about it being
880 // different from the original.
881 if (newTypeParam->hasExplicitBound()) {
882 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
883 ->getTypeLoc().getSourceRange();
884 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
885 << newTypeParam->getUnderlyingType()
886 << newTypeParam->getDeclName()
887 << prevTypeParam->hasExplicitBound()
888 << prevTypeParam->getUnderlyingType()
889 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
890 << prevTypeParam->getDeclName()
891 << FixItHint::CreateReplacement(
892 newBoundRange,
893 prevTypeParam->getUnderlyingType().getAsString(
894 S.Context.getPrintingPolicy()));
895
896 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
897 << prevTypeParam->getDeclName();
898
899 // Override the new type parameter's bound type with the previous type,
900 // so that it's consistent.
901 newTypeParam->setTypeSourceInfo(
902 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
903 continue;
904 }
905
906 // The new type parameter got the implicit bound of 'id'. That's okay for
907 // categories and extensions (overwrite it later), but not for forward
908 // declarations and @interfaces, because those must be standalone.
909 if (newContext == TypeParamListContext::ForwardDeclaration ||
910 newContext == TypeParamListContext::Definition) {
911 // Diagnose this problem for forward declarations and definitions.
912 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000913 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000914 std::string newCode
915 = " : " + prevTypeParam->getUnderlyingType().getAsString(
916 S.Context.getPrintingPolicy());
917 S.Diag(newTypeParam->getLocation(),
918 diag::err_objc_type_param_bound_missing)
919 << prevTypeParam->getUnderlyingType()
920 << newTypeParam->getDeclName()
921 << (newContext == TypeParamListContext::ForwardDeclaration)
922 << FixItHint::CreateInsertion(insertionLoc, newCode);
923
924 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
925 << prevTypeParam->getDeclName();
926 }
927
928 // Update the new type parameter's bound to match the previous one.
929 newTypeParam->setTypeSourceInfo(
930 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
931 }
932
933 return false;
934}
935
John McCall48871652010-08-21 09:40:31 +0000936Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000937ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000938 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000939 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000940 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000941 ArrayRef<ParsedType> SuperTypeArgs,
942 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000943 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000944 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000945 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000946 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000947
Chris Lattnerda463fe2007-12-12 07:09:47 +0000948 // Check for another declaration kind with the same name.
Richard Smithbecb92d2017-10-10 22:33:17 +0000949 NamedDecl *PrevDecl =
950 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
951 forRedeclarationInCurContext());
Douglas Gregor5101c242008-12-05 18:15:24 +0000952
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000953 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000954 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000955 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000956 }
Mike Stump11289f42009-09-09 15:08:12 +0000957
Douglas Gregordc9166c2011-12-15 20:29:51 +0000958 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000959 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000960
961 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
962 // A previous decl with a different name is because of
963 // @compatibility_alias, for example:
964 // \code
965 // @class NewImage;
966 // @compatibility_alias OldImage NewImage;
967 // \endcode
968 // A lookup for 'OldImage' will return the 'NewImage' decl.
969 //
970 // In such a case use the real declaration name, instead of the alias one,
971 // otherwise we will break IdentifierResolver and redecls-chain invariants.
972 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
973 // has been aliased.
974 ClassName = PrevIDecl->getIdentifier();
975 }
976
Douglas Gregor85f3f952015-07-07 03:57:15 +0000977 // If there was a forward declaration with type parameters, check
978 // for consistency.
979 if (PrevIDecl) {
980 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
981 if (typeParamList) {
982 // Both have type parameter lists; check for consistency.
983 if (checkTypeParamListConsistency(*this, prevTypeParamList,
984 typeParamList,
985 TypeParamListContext::Definition)) {
986 typeParamList = nullptr;
987 }
988 } else {
989 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
990 << ClassName;
991 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
992 << ClassName;
993
994 // Clone the type parameter list.
995 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
996 for (auto typeParam : *prevTypeParamList) {
997 clonedTypeParams.push_back(
998 ObjCTypeParamDecl::Create(
999 Context,
1000 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001001 typeParam->getVariance(),
1002 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001003 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001004 SourceLocation(),
1005 typeParam->getIdentifier(),
1006 SourceLocation(),
1007 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1008 }
1009
1010 typeParamList = ObjCTypeParamList::create(Context,
1011 SourceLocation(),
1012 clonedTypeParams,
1013 SourceLocation());
1014 }
1015 }
1016 }
1017
Douglas Gregordc9166c2011-12-15 20:29:51 +00001018 ObjCInterfaceDecl *IDecl
1019 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001020 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001021 if (PrevIDecl) {
1022 // Class already seen. Was it a definition?
1023 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1024 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1025 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001026 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001027 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001028 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001029 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00001030
1031 if (AttrList)
1032 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001033 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001034 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001035
Douglas Gregordc9166c2011-12-15 20:29:51 +00001036 // Start the definition of this class. If we're in a redefinition case, there
1037 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001038 if (!IDecl->hasDefinition())
1039 IDecl->startDefinition();
1040
Chris Lattnerda463fe2007-12-12 07:09:47 +00001041 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001042 // Diagnose availability in the context of the @interface.
1043 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001044
Douglas Gregore9d95f12015-07-07 03:57:35 +00001045 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1046 ClassName, ClassLoc,
1047 SuperName, SuperLoc, SuperTypeArgs,
1048 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001049 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001050 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001051 }
Mike Stump11289f42009-09-09 15:08:12 +00001052
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001053 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001054 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001055 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1056 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001057 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001058 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001059 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001060 }
Mike Stump11289f42009-09-09 15:08:12 +00001061
Anders Carlssona6b508a2008-11-04 16:57:32 +00001062 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001063 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001064}
1065
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001066/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1067/// typedef'ed use for a qualified super class and adds them to the list
1068/// of the protocols.
1069void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001070 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001071 IdentifierInfo *SuperName,
1072 SourceLocation SuperLoc) {
1073 if (!SuperName)
1074 return;
1075 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1076 LookupOrdinaryName);
1077 if (!IDecl)
1078 return;
1079
1080 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1081 QualType T = TDecl->getUnderlyingType();
1082 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001083 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001084 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001085 // FIXME: Consider whether this should be an invalid loc since the loc
1086 // is not actually pointing to a protocol name reference but to the
1087 // typedef reference. Note that the base class name loc is also pointing
1088 // at the typedef.
1089 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1090 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001091 }
1092}
1093
Richard Smithac4e36d2012-08-08 23:32:13 +00001094/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001095/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001096Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1097 IdentifierInfo *AliasName,
1098 SourceLocation AliasLocation,
1099 IdentifierInfo *ClassName,
1100 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001101 // Look for previous declaration of alias name
Richard Smithbecb92d2017-10-10 22:33:17 +00001102 NamedDecl *ADecl =
1103 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1104 forRedeclarationInCurContext());
Chris Lattnerda463fe2007-12-12 07:09:47 +00001105 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001106 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001107 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001108 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001109 }
1110 // Check for class declaration
Richard Smithbecb92d2017-10-10 22:33:17 +00001111 NamedDecl *CDeclU =
1112 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1113 forRedeclarationInCurContext());
Richard Smithdda56e42011-04-15 14:24:37 +00001114 if (const TypedefNameDecl *TDecl =
1115 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001116 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001117 if (T->isObjCObjectType()) {
1118 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001119 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001120 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Richard Smithbecb92d2017-10-10 22:33:17 +00001121 LookupOrdinaryName,
1122 forRedeclarationInCurContext());
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001123 }
1124 }
1125 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001126 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001127 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001128 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001129 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001130 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001131 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001132 }
Mike Stump11289f42009-09-09 15:08:12 +00001133
Chris Lattner219b3e92008-03-16 21:17:37 +00001134 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001135 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001136 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001137
Anders Carlssona6b508a2008-11-04 16:57:32 +00001138 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001139 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001140
John McCall48871652010-08-21 09:40:31 +00001141 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001142}
1143
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001144bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001145 IdentifierInfo *PName,
1146 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001147 const ObjCList<ObjCProtocolDecl> &PList) {
1148
1149 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001150 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1151 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001152 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1153 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001154 if (PDecl->getIdentifier() == PName) {
1155 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1156 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001157 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001158 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001159
1160 if (!PDecl->hasDefinition())
1161 continue;
1162
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001163 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1164 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1165 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001166 }
1167 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001168 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001169}
1170
John McCall48871652010-08-21 09:40:31 +00001171Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001172Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1173 IdentifierInfo *ProtocolName,
1174 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001175 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001176 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001177 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001178 SourceLocation EndProtoLoc,
1179 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001180 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001181 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001182 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001183 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00001184 forRedeclarationInCurContext());
Craig Topperc3ec1492014-05-26 06:22:03 +00001185 ObjCProtocolDecl *PDecl = nullptr;
1186 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001187 // If we already have a definition, complain.
1188 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1189 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001190
Douglas Gregor32c17572012-01-01 20:30:41 +00001191 // Create a new protocol that is completely distinct from previous
1192 // declarations, and do not make this protocol available for name lookup.
1193 // That way, we'll end up completely ignoring the duplicate.
1194 // FIXME: Can we turn this into an error?
1195 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1196 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001197 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001198 PDecl->startDefinition();
1199 } else {
1200 if (PrevDecl) {
1201 // Check for circular dependencies among protocol declarations. This can
1202 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001203 ObjCList<ObjCProtocolDecl> PList;
1204 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1205 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001206 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001207 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001208
1209 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001210 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001211 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001212 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001213
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001214 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001215 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001216 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001217
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001218 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001219 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001220 AddPragmaAttributes(TUScope, PDecl);
1221
Douglas Gregor32c17572012-01-01 20:30:41 +00001222 // Merge attributes from previous declarations.
1223 if (PrevDecl)
1224 mergeDeclAttributes(PDecl, PrevDecl);
1225
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001226 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001227 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001228 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1229 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001230 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001231 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001232 }
Mike Stump11289f42009-09-09 15:08:12 +00001233
1234 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001235 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001236}
1237
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001238static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1239 ObjCProtocolDecl *&UndefinedProtocol) {
1240 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1241 UndefinedProtocol = PDecl;
1242 return true;
1243 }
1244
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001245 for (auto *PI : PDecl->protocols())
1246 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1247 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001248 return true;
1249 }
1250 return false;
1251}
1252
Chris Lattnerda463fe2007-12-12 07:09:47 +00001253/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001254/// issues an error if they are not declared. It returns list of
1255/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001256void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001257Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001258 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001259 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001260 for (const IdentifierLocPair &Pair : ProtocolId) {
1261 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001262 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001263 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001264 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001265 LookupObjCProtocolName, TUScope, nullptr,
1266 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001267 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001268 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1269 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001270 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001271 }
1272
1273 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001274 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001275 continue;
1276 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001277 // If this is a forward protocol declaration, get its definition.
1278 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1279 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001280
1281 // For an objc container, delay protocol reference checking until after we
1282 // can set the objc decl as the availability context, otherwise check now.
1283 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001284 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001285 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001286
1287 // If this is a forward declaration and we are supposed to warn in this
1288 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001289 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001290 ObjCProtocolDecl *UndefinedProtocol;
1291
Douglas Gregoreed49792013-01-17 00:38:46 +00001292 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001293 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001294 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001295 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1296 << UndefinedProtocol;
1297 }
John McCall48871652010-08-21 09:40:31 +00001298 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001299 }
1300}
1301
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001302namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001303// Callback to only accept typo corrections that are either
1304// Objective-C protocols or valid Objective-C type arguments.
1305class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1306 ASTContext &Context;
1307 Sema::LookupNameKind LookupKind;
1308 public:
1309 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1310 Sema::LookupNameKind lookupKind)
1311 : Context(context), LookupKind(lookupKind) { }
1312
1313 bool ValidateCandidate(const TypoCorrection &candidate) override {
1314 // If we're allowed to find protocols and we have a protocol, accept it.
1315 if (LookupKind != Sema::LookupOrdinaryName) {
1316 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1317 return true;
1318 }
1319
1320 // If we're allowed to find type names and we have one, accept it.
1321 if (LookupKind != Sema::LookupObjCProtocolName) {
1322 // If we have a type declaration, we might accept this result.
1323 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1324 // If we found a tag declaration outside of C++, skip it. This
1325 // can happy because we look for any name when there is no
1326 // bias to protocol or type names.
1327 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1328 return false;
1329
1330 // Make sure the type is something we would accept as a type
1331 // argument.
1332 auto type = Context.getTypeDeclType(typeDecl);
1333 if (type->isObjCObjectPointerType() ||
1334 type->isBlockPointerType() ||
1335 type->isDependentType() ||
1336 type->isObjCObjectType())
1337 return true;
1338
1339 return false;
1340 }
1341
1342 // If we have an Objective-C class type, accept it; there will
1343 // be another fix to add the '*'.
1344 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1345 return true;
1346
1347 return false;
1348 }
1349
1350 return false;
1351 }
1352};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001353} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001354
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001355void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1356 SourceLocation ProtocolLoc,
1357 IdentifierInfo *TypeArgId,
1358 SourceLocation TypeArgLoc,
1359 bool SelectProtocolFirst) {
1360 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1361 << SelectProtocolFirst << TypeArgId << ProtocolId
1362 << SourceRange(ProtocolLoc);
1363}
1364
Douglas Gregore9d95f12015-07-07 03:57:35 +00001365void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1366 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001367 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001368 SourceLocation lAngleLoc,
1369 ArrayRef<IdentifierInfo *> identifiers,
1370 ArrayRef<SourceLocation> identifierLocs,
1371 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001372 SourceLocation &typeArgsLAngleLoc,
1373 SmallVectorImpl<ParsedType> &typeArgs,
1374 SourceLocation &typeArgsRAngleLoc,
1375 SourceLocation &protocolLAngleLoc,
1376 SmallVectorImpl<Decl *> &protocols,
1377 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001378 bool warnOnIncompleteProtocols) {
1379 // Local function that updates the declaration specifiers with
1380 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001381 unsigned numProtocolsResolved = 0;
1382 auto resolvedAsProtocols = [&] {
1383 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1384
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001385 // Determine whether the base type is a parameterized class, in
1386 // which case we want to warn about typos such as
1387 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1388 ObjCInterfaceDecl *baseClass = nullptr;
1389 QualType base = GetTypeFromParser(baseType, nullptr);
1390 bool allAreTypeNames = false;
1391 SourceLocation firstClassNameLoc;
1392 if (!base.isNull()) {
1393 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1394 baseClass = objcObjectType->getInterface();
1395 if (baseClass) {
1396 if (auto typeParams = baseClass->getTypeParamList()) {
1397 if (typeParams->size() == numProtocolsResolved) {
1398 // Note that we should be looking for type names, too.
1399 allAreTypeNames = true;
1400 }
1401 }
1402 }
1403 }
1404 }
1405
Douglas Gregore9d95f12015-07-07 03:57:35 +00001406 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001407 ObjCProtocolDecl *&proto
1408 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001409 // For an objc container, delay protocol reference checking until after we
1410 // can set the objc decl as the availability context, otherwise check now.
1411 if (!warnOnIncompleteProtocols) {
1412 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1413 }
1414
1415 // If this is a forward protocol declaration, get its definition.
1416 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1417 proto = proto->getDefinition();
1418
1419 // If this is a forward declaration and we are supposed to warn in this
1420 // case, do it.
1421 // FIXME: Recover nicely in the hidden case.
1422 ObjCProtocolDecl *forwardDecl = nullptr;
1423 if (warnOnIncompleteProtocols &&
1424 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1425 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1426 << proto->getDeclName();
1427 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1428 << forwardDecl;
1429 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001430
1431 // If everything this far has been a type name (and we care
1432 // about such things), check whether this name refers to a type
1433 // as well.
1434 if (allAreTypeNames) {
1435 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1436 LookupOrdinaryName)) {
1437 if (isa<ObjCInterfaceDecl>(decl)) {
1438 if (firstClassNameLoc.isInvalid())
1439 firstClassNameLoc = identifierLocs[i];
1440 } else if (!isa<TypeDecl>(decl)) {
1441 // Not a type.
1442 allAreTypeNames = false;
1443 }
1444 } else {
1445 allAreTypeNames = false;
1446 }
1447 }
1448 }
1449
1450 // All of the protocols listed also have type names, and at least
1451 // one is an Objective-C class name. Check whether all of the
1452 // protocol conformances are declared by the base class itself, in
1453 // which case we warn.
1454 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1455 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1456 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1457 bool allProtocolsDeclared = true;
1458 for (auto proto : protocols) {
1459 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1460 allProtocolsDeclared = false;
1461 break;
1462 }
1463 }
1464
1465 if (allProtocolsDeclared) {
1466 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1467 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001468 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1469 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001470 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001471 }
1472
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001473 protocolLAngleLoc = lAngleLoc;
1474 protocolRAngleLoc = rAngleLoc;
1475 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001476 };
1477
1478 // Attempt to resolve all of the identifiers as protocols.
1479 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1480 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1481 protocols.push_back(proto);
1482 if (proto)
1483 ++numProtocolsResolved;
1484 }
1485
1486 // If all of the names were protocols, these were protocol qualifiers.
1487 if (numProtocolsResolved == identifiers.size())
1488 return resolvedAsProtocols();
1489
1490 // Attempt to resolve all of the identifiers as type names or
1491 // Objective-C class names. The latter is technically ill-formed,
1492 // but is probably something like \c NSArray<NSView *> missing the
1493 // \c*.
1494 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1495 SmallVector<TypeOrClassDecl, 4> typeDecls;
1496 unsigned numTypeDeclsResolved = 0;
1497 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1498 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1499 LookupOrdinaryName);
1500 if (!decl) {
1501 typeDecls.push_back(TypeOrClassDecl());
1502 continue;
1503 }
1504
1505 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1506 typeDecls.push_back(typeDecl);
1507 ++numTypeDeclsResolved;
1508 continue;
1509 }
1510
1511 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1512 typeDecls.push_back(objcClass);
1513 ++numTypeDeclsResolved;
1514 continue;
1515 }
1516
1517 typeDecls.push_back(TypeOrClassDecl());
1518 }
1519
1520 AttributeFactory attrFactory;
1521
1522 // Local function that forms a reference to the given type or
1523 // Objective-C class declaration.
1524 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1525 -> TypeResult {
1526 // Form declaration specifiers. They simply refer to the type.
1527 DeclSpec DS(attrFactory);
1528 const char* prevSpec; // unused
1529 unsigned diagID; // unused
1530 QualType type;
1531 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1532 type = Context.getTypeDeclType(actualTypeDecl);
1533 else
1534 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1535 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1536 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1537 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1538 parsedType, Context.getPrintingPolicy());
1539 // Use the identifier location for the type source range.
1540 DS.SetRangeStart(loc);
1541 DS.SetRangeEnd(loc);
1542
1543 // Form the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001544 Declarator D(DS, DeclaratorContext::TypeNameContext);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001545
1546 // If we have a typedef of an Objective-C class type that is missing a '*',
1547 // add the '*'.
1548 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001549 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001550 ParsedAttributes parsedAttrs(attrFactory);
1551 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1552 SourceLocation(),
1553 SourceLocation(),
1554 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001555 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001556 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001557 parsedAttrs,
1558 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001559
1560 // Diagnose the missing '*'.
1561 Diag(loc, diag::err_objc_type_arg_missing_star)
1562 << type
1563 << FixItHint::CreateInsertion(starLoc, " *");
1564 }
1565
1566 // Convert this to a type.
1567 return ActOnTypeName(S, D);
1568 };
1569
1570 // Local function that updates the declaration specifiers with
1571 // type argument information.
1572 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001573 // We did not resolve these as protocols.
1574 protocols.clear();
1575
Douglas Gregore9d95f12015-07-07 03:57:35 +00001576 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1577 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001578 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1579 // Map type reference to a type.
1580 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001581 if (!type.isUsable()) {
1582 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001583 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001584 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001585
1586 typeArgs.push_back(type.get());
1587 }
1588
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001589 typeArgsLAngleLoc = lAngleLoc;
1590 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001591 };
1592
1593 // If all of the identifiers can be resolved as type names or
1594 // Objective-C class names, we have type arguments.
1595 if (numTypeDeclsResolved == identifiers.size())
1596 return resolvedAsTypeDecls();
1597
1598 // Error recovery: some names weren't found, or we have a mix of
1599 // type and protocol names. Go resolve all of the unresolved names
1600 // and complain if we can't find a consistent answer.
1601 LookupNameKind lookupKind = LookupAnyName;
1602 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1603 // If we already have a protocol or type. Check whether it is the
1604 // right thing.
1605 if (protocols[i] || typeDecls[i]) {
1606 // If we haven't figured out whether we want types or protocols
1607 // yet, try to figure it out from this name.
1608 if (lookupKind == LookupAnyName) {
1609 // If this name refers to both a protocol and a type (e.g., \c
1610 // NSObject), don't conclude anything yet.
1611 if (protocols[i] && typeDecls[i])
1612 continue;
1613
1614 // Otherwise, let this name decide whether we'll be correcting
1615 // toward types or protocols.
1616 lookupKind = protocols[i] ? LookupObjCProtocolName
1617 : LookupOrdinaryName;
1618 continue;
1619 }
1620
1621 // If we want protocols and we have a protocol, there's nothing
1622 // more to do.
1623 if (lookupKind == LookupObjCProtocolName && protocols[i])
1624 continue;
1625
1626 // If we want types and we have a type declaration, there's
1627 // nothing more to do.
1628 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1629 continue;
1630
1631 // We have a conflict: some names refer to protocols and others
1632 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001633 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1634 identifiers[i], identifierLocs[i],
1635 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001636
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001637 protocols.clear();
1638 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001639 return;
1640 }
1641
1642 // Perform typo correction on the name.
1643 TypoCorrection corrected = CorrectTypo(
1644 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1645 nullptr,
1646 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1647 lookupKind),
1648 CTK_ErrorRecovery);
1649 if (corrected) {
1650 // Did we find a protocol?
1651 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1652 diagnoseTypo(corrected,
1653 PDiag(diag::err_undeclared_protocol_suggest)
1654 << identifiers[i]);
1655 lookupKind = LookupObjCProtocolName;
1656 protocols[i] = proto;
1657 ++numProtocolsResolved;
1658 continue;
1659 }
1660
1661 // Did we find a type?
1662 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1663 diagnoseTypo(corrected,
1664 PDiag(diag::err_unknown_typename_suggest)
1665 << identifiers[i]);
1666 lookupKind = LookupOrdinaryName;
1667 typeDecls[i] = typeDecl;
1668 ++numTypeDeclsResolved;
1669 continue;
1670 }
1671
1672 // Did we find an Objective-C class?
1673 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1674 diagnoseTypo(corrected,
1675 PDiag(diag::err_unknown_type_or_class_name_suggest)
1676 << identifiers[i] << true);
1677 lookupKind = LookupOrdinaryName;
1678 typeDecls[i] = objcClass;
1679 ++numTypeDeclsResolved;
1680 continue;
1681 }
1682 }
1683
1684 // We couldn't find anything.
1685 Diag(identifierLocs[i],
1686 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1687 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1688 : diag::err_unknown_typename))
1689 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001690 protocols.clear();
1691 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001692 return;
1693 }
1694
1695 // If all of the names were (corrected to) protocols, these were
1696 // protocol qualifiers.
1697 if (numProtocolsResolved == identifiers.size())
1698 return resolvedAsProtocols();
1699
1700 // Otherwise, all of the names were (corrected to) types.
1701 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1702 return resolvedAsTypeDecls();
1703}
1704
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001705/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001706/// a class method in its extension.
1707///
Mike Stump11289f42009-09-09 15:08:12 +00001708void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001709 ObjCInterfaceDecl *ID) {
1710 if (!ID)
1711 return; // Possibly due to previous error
1712
1713 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001714 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001715 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001716
1717 if (MethodMap.empty())
1718 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001719 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001720 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001721 if (PrevMethod &&
1722 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1723 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001724 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1725 << Method->getDeclName();
1726 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1727 }
1728 }
1729}
1730
James Dennett634962f2012-06-14 21:40:34 +00001731/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001732Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001733Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001734 ArrayRef<IdentifierLocPair> IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001735 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001736 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001737 for (const IdentifierLocPair &IdentPair : IdentList) {
1738 IdentifierInfo *Ident = IdentPair.first;
1739 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Richard Smithbecb92d2017-10-10 22:33:17 +00001740 forRedeclarationInCurContext());
Douglas Gregor32c17572012-01-01 20:30:41 +00001741 ObjCProtocolDecl *PDecl
1742 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001743 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001744 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001745
1746 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001747 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001748
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001749 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001750 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001751 AddPragmaAttributes(TUScope, PDecl);
1752
Douglas Gregor32c17572012-01-01 20:30:41 +00001753 if (PrevDecl)
1754 mergeDeclAttributes(PDecl, PrevDecl);
1755
Douglas Gregorf6102672012-01-01 21:23:57 +00001756 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001757 }
Mike Stump11289f42009-09-09 15:08:12 +00001758
Richard Smith3beb7c62017-01-12 02:27:38 +00001759 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001760}
1761
John McCall48871652010-08-21 09:40:31 +00001762Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001763ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1764 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001765 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001766 IdentifierInfo *CategoryName,
1767 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001768 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001769 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001770 const SourceLocation *ProtoLocs,
Alex Lorenzf9371392017-03-23 11:44:25 +00001771 SourceLocation EndProtoLoc,
1772 AttributeList *AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001773 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001774 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001775
1776 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001777
1778 if (!IDecl
1779 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001780 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001781 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001782 // Create an invalid ObjCCategoryDecl to serve as context for
1783 // the enclosing method declarations. We mark the decl invalid
1784 // to make it clear that this isn't a valid AST.
1785 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001786 ClassLoc, CategoryLoc, CategoryName,
1787 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001788 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001789 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001790
1791 if (!IDecl)
1792 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001793 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001794 }
1795
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001796 if (!CategoryName && IDecl->getImplementation()) {
1797 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1798 Diag(IDecl->getImplementation()->getLocation(),
1799 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001800 }
1801
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001802 if (CategoryName) {
1803 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001804 if (ObjCCategoryDecl *Previous
1805 = IDecl->FindCategoryDeclaration(CategoryName)) {
1806 // Class extensions can be declared multiple times, categories cannot.
1807 Diag(CategoryLoc, diag::warn_dup_category_def)
1808 << ClassName << CategoryName;
1809 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001810 }
1811 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001812
Douglas Gregor85f3f952015-07-07 03:57:15 +00001813 // If we have a type parameter list, check it.
1814 if (typeParamList) {
1815 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1816 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1817 CategoryName
1818 ? TypeParamListContext::Category
1819 : TypeParamListContext::Extension))
1820 typeParamList = nullptr;
1821 } else {
1822 Diag(typeParamList->getLAngleLoc(),
1823 diag::err_objc_parameterized_category_nonclass)
1824 << (CategoryName != nullptr)
1825 << ClassName
1826 << typeParamList->getSourceRange();
1827
1828 typeParamList = nullptr;
1829 }
1830 }
1831
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001832 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001833 ClassLoc, CategoryLoc, CategoryName, IDecl,
1834 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001835 // FIXME: PushOnScopeChains?
1836 CurContext->addDecl(CDecl);
1837
Alex Lorenza9c966d2018-02-23 23:49:43 +00001838 // Process the attributes before looking at protocols to ensure that the
1839 // availability attribute is attached to the category to provide availability
1840 // checking for protocol uses.
1841 if (AttrList)
1842 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1843 AddPragmaAttributes(TUScope, CDecl);
1844
Chris Lattnerda463fe2007-12-12 07:09:47 +00001845 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001846 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1847 NumProtoRefs, ProtoLocs);
1848 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001849 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001850 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001851 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001852 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001853 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001854 }
Mike Stump11289f42009-09-09 15:08:12 +00001855
Anders Carlssona6b508a2008-11-04 16:57:32 +00001856 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001857 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001858}
1859
1860/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001861/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001862/// object.
John McCall48871652010-08-21 09:40:31 +00001863Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001864 SourceLocation AtCatImplLoc,
1865 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1866 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001867 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001868 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001869 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001870 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1871 if (!CatIDecl) {
1872 // Category @implementation with no corresponding @interface.
1873 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001874 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1875 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001876 CatName, IDecl,
1877 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001878 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001879 }
1880 }
1881
Mike Stump11289f42009-09-09 15:08:12 +00001882 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001883 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001884 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001885 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001886 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001887 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001888 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001889 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1890 diag::err_undef_interface)) {
1891 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001892 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001893
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001894 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001895 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001896
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001897 // If the interface has the objc_runtime_visible attribute, we
1898 // cannot implement a category for it.
1899 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1900 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1901 << IDecl->getDeclName();
1902 }
1903
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001904 /// Check that CatName, category name, is not used in another implementation.
1905 if (CatIDecl) {
1906 if (CatIDecl->getImplementation()) {
1907 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1908 << CatName;
1909 Diag(CatIDecl->getImplementation()->getLocation(),
1910 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001911 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001912 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001913 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001914 // Warn on implementating category of deprecated class under
1915 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001916 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1917 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001918 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001919 }
Mike Stump11289f42009-09-09 15:08:12 +00001920
Anders Carlssona6b508a2008-11-04 16:57:32 +00001921 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001922 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001923}
1924
John McCall48871652010-08-21 09:40:31 +00001925Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001926 SourceLocation AtClassImplLoc,
1927 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001928 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001929 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001930 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001931 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001932 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001933 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001934 forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001935 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001936 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001937 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001938 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001939 // FIXME: This will produce an error if the definition of the interface has
1940 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001941 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1942 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001943 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001944 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001945 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001946 TypoCorrection Corrected = CorrectTypo(
1947 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1948 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001949 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1950 // Suggest the (potentially) correct interface name. Don't provide a
1951 // code-modification hint or use the typo name for recovery, because
1952 // this is just a warning. The program may actually be correct.
1953 diagnoseTypo(Corrected,
1954 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1955 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001956 } else {
1957 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1958 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001959 }
Mike Stump11289f42009-09-09 15:08:12 +00001960
Chris Lattnerda463fe2007-12-12 07:09:47 +00001961 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001962 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001963 if (SuperClassname) {
1964 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001965 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1966 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001967 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001968 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1969 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001970 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001971 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001972 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001973 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001974 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001975 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001976 Diag(SuperClassLoc, diag::err_undef_superclass)
1977 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001978 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001979 // This implementation and its interface do not have the same
1980 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001981 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001982 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001983 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001984 }
1985 }
1986 }
Mike Stump11289f42009-09-09 15:08:12 +00001987
Chris Lattnerda463fe2007-12-12 07:09:47 +00001988 if (!IDecl) {
1989 // Legacy case of @implementation with no corresponding @interface.
1990 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001991
Mike Stump87c57ac2009-05-16 07:39:55 +00001992 // FIXME: Do we support attributes on the @implementation? If so we should
1993 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001994 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001995 ClassName, /*typeParamList=*/nullptr,
1996 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001997 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001998 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001999 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00002000 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00002001 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2002 Context.getObjCInterfaceType(SDecl),
2003 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00002004 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2005 } else {
2006 IDecl->setEndOfDefinitionLoc(ClassLoc);
2007 }
2008
Douglas Gregorac345a32009-04-24 00:16:12 +00002009 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002010 } else {
2011 // Mark the interface as being completed, even if it was just as
2012 // @class ....;
2013 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002014 if (!IDecl->hasDefinition())
2015 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002016 }
Mike Stump11289f42009-09-09 15:08:12 +00002017
2018 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002019 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002020 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002021
Anders Carlssona6b508a2008-11-04 16:57:32 +00002022 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002023 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002024
Chris Lattnerda463fe2007-12-12 07:09:47 +00002025 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002026 if (IDecl->getImplementation()) {
2027 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002028 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002029 Diag(IDecl->getImplementation()->getLocation(),
2030 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002031 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002032 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002033 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002034 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002035 // Warn on implementating deprecated class under
2036 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002037 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002038 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002039
2040 // If the superclass has the objc_runtime_visible attribute, we
2041 // cannot implement a subclass of it.
2042 if (IDecl->getSuperClass() &&
2043 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2044 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2045 << IDecl->getDeclName()
2046 << IDecl->getSuperClass()->getDeclName();
2047 }
2048
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002049 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002050}
2051
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002052Sema::DeclGroupPtrTy
2053Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2054 SmallVector<Decl *, 64> DeclsInGroup;
2055 DeclsInGroup.reserve(Decls.size() + 1);
2056
2057 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2058 Decl *Dcl = Decls[i];
2059 if (!Dcl)
2060 continue;
2061 if (Dcl->getDeclContext()->isFileContext())
2062 Dcl->setTopLevelDeclInObjCContainer();
2063 DeclsInGroup.push_back(Dcl);
2064 }
2065
2066 DeclsInGroup.push_back(ObjCImpDecl);
2067
Richard Smith3beb7c62017-01-12 02:27:38 +00002068 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002069}
2070
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002071void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2072 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002073 SourceLocation RBrace) {
2074 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002075 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002076 if (!IDecl)
2077 return;
James Dennett634962f2012-06-14 21:40:34 +00002078 /// Check case of non-existing \@interface decl.
2079 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002080 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002081 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002082 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002083 // Add ivar's to class's DeclContext.
2084 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002085 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002086 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002087 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002088 }
2089
Chris Lattnerda463fe2007-12-12 07:09:47 +00002090 return;
2091 }
2092 // If implementation has empty ivar list, just return.
2093 if (numIvars == 0)
2094 return;
Mike Stump11289f42009-09-09 15:08:12 +00002095
Chris Lattnerda463fe2007-12-12 07:09:47 +00002096 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002097 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002098 if (ImpDecl->getSuperClass())
2099 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2100 for (unsigned i = 0; i < numIvars; i++) {
2101 ObjCIvarDecl* ImplIvar = ivars[i];
2102 if (const ObjCIvarDecl *ClsIvar =
2103 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2104 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2105 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2106 continue;
2107 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002108 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002109 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002110 if (const ObjCIvarDecl *ClsExtIvar =
2111 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2112 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2113 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2114 continue;
2115 }
2116 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002117 // Instance ivar to Implementation's DeclContext.
2118 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002119 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002120 ImpDecl->addDecl(ImplIvar);
2121 }
2122 return;
2123 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002124 // Check interface's Ivar list against those in the implementation.
2125 // names and types must match.
2126 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002127 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002128 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002129 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2130 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002131 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002132 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002133 assert (ImplIvar && "missing implementation ivar");
2134 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002135
Steve Naroff157599f2009-03-03 14:49:36 +00002136 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002137 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002138 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002139 << ImplIvar->getIdentifier()
2140 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002141 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002142 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2143 ImplIvar->getBitWidthValue(Context) !=
2144 ClsIvar->getBitWidthValue(Context)) {
2145 Diag(ImplIvar->getBitWidth()->getLocStart(),
2146 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2147 Diag(ClsIvar->getBitWidth()->getLocStart(),
2148 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002149 }
Steve Naroff157599f2009-03-03 14:49:36 +00002150 // Make sure the names are identical.
2151 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002152 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002153 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002154 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002155 }
2156 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002157 }
Mike Stump11289f42009-09-09 15:08:12 +00002158
Chris Lattner0f29d982007-12-12 18:11:49 +00002159 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002160 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002161 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002162 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002163}
2164
Ted Kremenekf87decd2013-12-13 05:58:44 +00002165static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2166 ObjCMethodDecl *method,
2167 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002168 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002169 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002170 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002171 switch (method->getAvailability()) {
2172 case AR_Available:
2173 case AR_Deprecated:
2174 break;
2175
2176 // Don't warn about unavailable or not-yet-introduced methods.
2177 case AR_NotYetIntroduced:
2178 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002179 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002180 }
2181
Ted Kremenek65d63572013-03-27 00:02:21 +00002182 // FIXME: For now ignore 'IncompleteImpl'.
2183 // Previously we grouped all unimplemented methods under a single
2184 // warning, but some users strongly voiced that they would prefer
2185 // separate warnings. We will give that approach a try, as that
2186 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002187 {
2188 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2189 B << method;
2190 if (NeededFor)
2191 B << NeededFor;
2192 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002193
2194 // Issue a note to the original declaration.
2195 SourceLocation MethodLoc = method->getLocStart();
2196 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002197 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002198}
2199
David Chisnallb62d15c2010-10-25 17:23:52 +00002200/// Determines if type B can be substituted for type A. Returns true if we can
2201/// guarantee that anything that the user will do to an object of type A can
2202/// also be done to an object of type B. This is trivially true if the two
2203/// types are the same, or if B is a subclass of A. It becomes more complex
2204/// in cases where protocols are involved.
2205///
2206/// Object types in Objective-C describe the minimum requirements for an
2207/// object, rather than providing a complete description of a type. For
2208/// example, if A is a subclass of B, then B* may refer to an instance of A.
2209/// The principle of substitutability means that we may use an instance of A
2210/// anywhere that we may use an instance of B - it will implement all of the
2211/// ivars of B and all of the methods of B.
2212///
2213/// This substitutability is important when type checking methods, because
2214/// the implementation may have stricter type definitions than the interface.
2215/// The interface specifies minimum requirements, but the implementation may
2216/// have more accurate ones. For example, a method may privately accept
2217/// instances of B, but only publish that it accepts instances of A. Any
2218/// object passed to it will be type checked against B, and so will implicitly
2219/// by a valid A*. Similarly, a method may return a subclass of the class that
2220/// it is declared as returning.
2221///
2222/// This is most important when considering subclassing. A method in a
2223/// subclass must accept any object as an argument that its superclass's
2224/// implementation accepts. It may, however, accept a more general type
2225/// without breaking substitutability (i.e. you can still use the subclass
2226/// anywhere that you can use the superclass, but not vice versa). The
2227/// converse requirement applies to return types: the return type for a
2228/// subclass method must be a valid object of the kind that the superclass
2229/// advertises, but it may be specified more accurately. This avoids the need
2230/// for explicit down-casting by callers.
2231///
2232/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002233static bool isObjCTypeSubstitutable(ASTContext &Context,
2234 const ObjCObjectPointerType *A,
2235 const ObjCObjectPointerType *B,
2236 bool rejectId) {
2237 // Reject a protocol-unqualified id.
2238 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002239
2240 // If B is a qualified id, then A must also be a qualified id and it must
2241 // implement all of the protocols in B. It may not be a qualified class.
2242 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2243 // stricter definition so it is not substitutable for id<A>.
2244 if (B->isObjCQualifiedIdType()) {
2245 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002246 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2247 QualType(B,0),
2248 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002249 }
2250
2251 /*
2252 // id is a special type that bypasses type checking completely. We want a
2253 // warning when it is used in one place but not another.
2254 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2255
2256
2257 // If B is a qualified id, then A must also be a qualified id (which it isn't
2258 // if we've got this far)
2259 if (B->isObjCQualifiedIdType()) return false;
2260 */
2261
2262 // Now we know that A and B are (potentially-qualified) class types. The
2263 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002264 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002265}
2266
John McCall071df462010-10-28 02:34:38 +00002267static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2268 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2269}
2270
Douglas Gregor813a0662015-06-19 18:14:38 +00002271/// Determine whether two set of Objective-C declaration qualifiers conflict.
2272static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2273 Decl::ObjCDeclQualifier y) {
2274 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2275 (y & ~Decl::OBJC_TQ_CSNullability);
2276}
2277
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002278static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002279 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002280 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002281 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002282 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002283 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002284 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002285 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2286 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002287 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002288 S.Diag(MethodImpl->getLocation(),
2289 (IsOverridingMode
2290 ? diag::warn_conflicting_overriding_ret_type_modifiers
2291 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002292 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002293 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002294 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002295 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002296 }
2297 else
2298 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002299 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002300 if (Warn && IsOverridingMode &&
2301 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2302 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2303 MethodDecl->getReturnType(),
2304 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002305 auto nullabilityMethodImpl =
2306 *MethodImpl->getReturnType()->getNullability(S.Context);
2307 auto nullabilityMethodDecl =
2308 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002309 S.Diag(MethodImpl->getLocation(),
2310 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002311 << DiagNullabilityKind(
2312 nullabilityMethodImpl,
2313 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2314 != 0))
2315 << DiagNullabilityKind(
2316 nullabilityMethodDecl,
2317 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2318 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002319 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2320 }
2321
Alp Toker314cc812014-01-25 16:55:45 +00002322 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2323 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002324 return true;
2325 if (!Warn)
2326 return false;
John McCall071df462010-10-28 02:34:38 +00002327
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002328 unsigned DiagID =
2329 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2330 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002331
2332 // Mismatches between ObjC pointers go into a different warning
2333 // category, and sometimes they're even completely whitelisted.
2334 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002335 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002336 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002337 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002338 // Allow non-matching return types as long as they don't violate
2339 // the principle of substitutability. Specifically, we permit
2340 // return types that are subclasses of the declared return type,
2341 // or that are more-qualified versions of the declared type.
2342 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002343 return false;
John McCall071df462010-10-28 02:34:38 +00002344
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002345 DiagID =
2346 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002347 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002348 }
2349 }
2350
2351 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002352 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2353 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002354 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002355 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2356 ? diag::note_previous_declaration
2357 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002358 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002359 return false;
John McCall071df462010-10-28 02:34:38 +00002360}
2361
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002362static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002363 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002364 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002365 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002366 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002367 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002368 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002369 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002370 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002371 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2372 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002373 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002374 if (IsOverridingMode)
2375 S.Diag(ImplVar->getLocation(),
2376 diag::warn_conflicting_overriding_param_modifiers)
2377 << getTypeRange(ImplVar->getTypeSourceInfo())
2378 << MethodImpl->getDeclName();
2379 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002380 diag::warn_conflicting_param_modifiers)
2381 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002382 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002383 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2384 << getTypeRange(IfaceVar->getTypeSourceInfo());
2385 }
2386 else
2387 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002388 }
2389
John McCall071df462010-10-28 02:34:38 +00002390 QualType ImplTy = ImplVar->getType();
2391 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002392 if (Warn && IsOverridingMode &&
2393 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2394 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002395 S.Diag(ImplVar->getLocation(),
2396 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002397 << DiagNullabilityKind(
2398 *ImplTy->getNullability(S.Context),
2399 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2400 != 0))
2401 << DiagNullabilityKind(
2402 *IfaceTy->getNullability(S.Context),
2403 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2404 != 0));
2405 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002406 }
John McCall071df462010-10-28 02:34:38 +00002407 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002408 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002409
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002410 if (!Warn)
2411 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002412 unsigned DiagID =
2413 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2414 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002415
2416 // Mismatches between ObjC pointers go into a different warning
2417 // category, and sometimes they're even completely whitelisted.
2418 if (const ObjCObjectPointerType *ImplPtrTy =
2419 ImplTy->getAs<ObjCObjectPointerType>()) {
2420 if (const ObjCObjectPointerType *IfacePtrTy =
2421 IfaceTy->getAs<ObjCObjectPointerType>()) {
2422 // Allow non-matching argument types as long as they don't
2423 // violate the principle of substitutability. Specifically, the
2424 // implementation must accept any objects that the superclass
2425 // accepts, however it may also accept others.
2426 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002427 return false;
John McCall071df462010-10-28 02:34:38 +00002428
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002429 DiagID =
2430 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002431 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002432 }
2433 }
2434
2435 S.Diag(ImplVar->getLocation(), DiagID)
2436 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002437 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2438 S.Diag(IfaceVar->getLocation(),
2439 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002440 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002441 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002442 return false;
John McCall071df462010-10-28 02:34:38 +00002443}
John McCall31168b02011-06-15 23:02:42 +00002444
2445/// In ARC, check whether the conventional meanings of the two methods
2446/// match. If they don't, it's a hard error.
2447static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2448 ObjCMethodDecl *decl) {
2449 ObjCMethodFamily implFamily = impl->getMethodFamily();
2450 ObjCMethodFamily declFamily = decl->getMethodFamily();
2451 if (implFamily == declFamily) return false;
2452
2453 // Since conventions are sorted by selector, the only possibility is
2454 // that the types differ enough to cause one selector or the other
2455 // to fall out of the family.
2456 assert(implFamily == OMF_None || declFamily == OMF_None);
2457
2458 // No further diagnostics required on invalid declarations.
2459 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2460
2461 const ObjCMethodDecl *unmatched = impl;
2462 ObjCMethodFamily family = declFamily;
2463 unsigned errorID = diag::err_arc_lost_method_convention;
2464 unsigned noteID = diag::note_arc_lost_method_convention;
2465 if (declFamily == OMF_None) {
2466 unmatched = decl;
2467 family = implFamily;
2468 errorID = diag::err_arc_gained_method_convention;
2469 noteID = diag::note_arc_gained_method_convention;
2470 }
2471
2472 // Indexes into a %select clause in the diagnostic.
2473 enum FamilySelector {
2474 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2475 };
2476 FamilySelector familySelector = FamilySelector();
2477
2478 switch (family) {
2479 case OMF_None: llvm_unreachable("logic error, no method convention");
2480 case OMF_retain:
2481 case OMF_release:
2482 case OMF_autorelease:
2483 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002484 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002485 case OMF_retainCount:
2486 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002487 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002488 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002489 // Mismatches for these methods don't change ownership
2490 // conventions, so we don't care.
2491 return false;
2492
2493 case OMF_init: familySelector = F_init; break;
2494 case OMF_alloc: familySelector = F_alloc; break;
2495 case OMF_copy: familySelector = F_copy; break;
2496 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2497 case OMF_new: familySelector = F_new; break;
2498 }
2499
2500 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2501 ReasonSelector reasonSelector;
2502
2503 // The only reason these methods don't fall within their families is
2504 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002505 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002506 reasonSelector = R_UnrelatedReturn;
2507 } else {
2508 reasonSelector = R_NonObjectReturn;
2509 }
2510
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002511 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2512 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002513
2514 return true;
2515}
John McCall071df462010-10-28 02:34:38 +00002516
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002517void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002518 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002519 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002520 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002521 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2522 return;
2523
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002524 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002525 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002526 true);
Mike Stump11289f42009-09-09 15:08:12 +00002527
Chris Lattner67f35b02009-04-11 19:58:42 +00002528 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002529 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2530 EF = MethodDecl->param_end();
2531 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002532 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002533 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002534 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002535
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002536 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002537 Diag(ImpMethodDecl->getLocation(),
2538 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002539 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002540 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002541}
2542
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002543void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2544 ObjCMethodDecl *Overridden,
2545 bool IsProtocolMethodDecl) {
2546
2547 CheckMethodOverrideReturn(*this, Method, Overridden,
2548 IsProtocolMethodDecl, true,
2549 true);
2550
2551 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002552 IF = Overridden->param_begin(), EM = Method->param_end(),
2553 EF = Overridden->param_end();
2554 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002555 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2556 IsProtocolMethodDecl, true, true);
2557 }
2558
2559 if (Method->isVariadic() != Overridden->isVariadic()) {
2560 Diag(Method->getLocation(),
2561 diag::warn_conflicting_overriding_variadic);
2562 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2563 }
2564}
2565
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002566/// WarnExactTypedMethods - This routine issues a warning if method
2567/// implementation declaration matches exactly that of its declaration.
2568void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2569 ObjCMethodDecl *MethodDecl,
2570 bool IsProtocolMethodDecl) {
2571 // don't issue warning when protocol method is optional because primary
2572 // class is not required to implement it and it is safe for protocol
2573 // to implement it.
2574 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2575 return;
2576 // don't issue warning when primary class's method is
2577 // depecated/unavailable.
2578 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2579 MethodDecl->hasAttr<DeprecatedAttr>())
2580 return;
2581
2582 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2583 IsProtocolMethodDecl, false, false);
2584 if (match)
2585 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002586 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2587 EF = MethodDecl->param_end();
2588 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002589 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2590 *IM, *IF,
2591 IsProtocolMethodDecl, false, false);
2592 if (!match)
2593 break;
2594 }
2595 if (match)
2596 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002597 if (match)
2598 match = !(MethodDecl->isClassMethod() &&
2599 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002600
2601 if (match) {
2602 Diag(ImpMethodDecl->getLocation(),
2603 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002604 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2605 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002606 }
2607}
2608
Mike Stump87c57ac2009-05-16 07:39:55 +00002609/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2610/// improve the efficiency of selector lookups and type checking by associating
2611/// with each protocol / interface / category the flattened instance tables. If
2612/// we used an immutable set to keep the table then it wouldn't add significant
2613/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002614
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002615typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002616typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002617
2618static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2619 ProtocolNameSet &PNS) {
2620 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2621 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002622 for (const auto *PI : PDecl->protocols())
2623 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002624}
2625
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002626/// Recursively populates a set with all conformed protocols in a class
2627/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2628/// attribute.
2629static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2630 ProtocolNameSet &PNS) {
2631 if (!Super)
2632 return;
2633
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002634 for (const auto *I : Super->all_referenced_protocols())
2635 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002636
2637 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002638}
2639
Steve Naroffa36992242008-02-08 22:06:17 +00002640/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002641/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002642static void CheckProtocolMethodDefs(Sema &S,
2643 SourceLocation ImpLoc,
2644 ObjCProtocolDecl *PDecl,
2645 bool& IncompleteImpl,
2646 const Sema::SelectorSet &InsMap,
2647 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002648 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002649 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002650 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2651 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2652 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002653 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2654
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002655 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002656 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002657
2658 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2659 // then we should check if any class in the super class hierarchy also
2660 // conforms to this protocol, either directly or via protocol inheritance.
2661 // If so, we can skip checking this protocol completely because we
2662 // know that a parent class already satisfies this protocol.
2663 //
2664 // Note: we could generalize this logic for all protocols, and merely
2665 // add the limit on looking at the super class chain for just
2666 // specially marked protocols. This may be a good optimization. This
2667 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2668 // protocols for now for controlled evaluation.
2669 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002670 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002671 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2672 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2673 }
2674 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2675 ProtocolsExplictImpl->end())
2676 return;
2677
2678 // If no super class conforms to the protocol, we should not search
2679 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002680 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002681 }
2682
Ted Kremenek285ee852013-12-13 06:26:10 +00002683 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002684 // check to see if class implements forwardInvocation method and objects
2685 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002686 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002687 // Under such conditions, which means that every method possible is
2688 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002689 // found" warnings.
2690 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002691 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2692 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002693 if (InsMap.count(fISelector))
2694 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2695 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002696 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002697 }
Mike Stump11289f42009-09-09 15:08:12 +00002698
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002699 // If this is a forward protocol declaration, get its definition.
2700 if (!PDecl->isThisDeclarationADefinition() &&
2701 PDecl->getDefinition())
2702 PDecl = PDecl->getDefinition();
2703
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002704 // If a method lookup fails locally we still need to look and see if
2705 // the method was implemented by a base class or an inherited
2706 // protocol. This lookup is slow, but occurs rarely in correct code
2707 // and otherwise would terminate in a warning.
2708
Chris Lattnerda463fe2007-12-12 07:09:47 +00002709 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002710 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002711 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002712 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002713 !method->isPropertyAccessor() &&
2714 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002715 (!Super || !Super->lookupMethod(method->getSelector(),
2716 true /* instance */,
2717 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002718 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002719 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002720 // If a method is not implemented in the category implementation but
2721 // has been declared in its primary class, superclass,
2722 // or in one of their protocols, no need to issue the warning.
2723 // This is because method will be implemented in the primary class
2724 // or one of its super class implementation.
2725
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002726 // Ugly, but necessary. Method declared in protcol might have
2727 // have been synthesized due to a property declared in the class which
2728 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002729 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002730 IDecl->lookupMethod(method->getSelector(),
2731 true /* instance */,
2732 true /* shallowCategoryLookup */,
2733 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002734 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002735 continue;
2736 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002737 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002738 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002739 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002740 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002741 }
2742 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002743 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002744 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002745 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2746 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002747 (!Super || !Super->lookupMethod(method->getSelector(),
2748 false /* class method */,
2749 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002750 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002751 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002752 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002753 if (C && IDecl->lookupMethod(method->getSelector(),
2754 false /* class */,
2755 true /* shallowCategoryLookup */,
2756 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002757 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002758
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002759 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002760 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002761 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002762 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002763 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002764 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002765 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002766 for (auto *PI : PDecl->protocols())
2767 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002768 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002769}
2770
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002771/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002772/// or protocol against those declared in their implementations.
2773///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002774void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2775 const SelectorSet &ClsMap,
2776 SelectorSet &InsMapSeen,
2777 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002778 ObjCImplDecl* IMPDecl,
2779 ObjCContainerDecl* CDecl,
2780 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002781 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002782 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002783 // Check and see if instance methods in class interface have been
2784 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002785 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002786 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002787 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002788 if (!I->isPropertyAccessor() &&
2789 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002790 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002791 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002792 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002793 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002794 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002795 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002796 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002797 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002798 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002799 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002800 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002801 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002802 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002803 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002804 else if (!I->isPropertyAccessor())
2805 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002806 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002807 }
2808 }
Mike Stump11289f42009-09-09 15:08:12 +00002809
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002810 // Check and see if class methods in class interface have been
2811 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002812 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002813 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002814 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002815 if (!I->isPropertyAccessor() &&
2816 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002817 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002818 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002819 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002820 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002821 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002822 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002823 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002824 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002825 // ImpMethodDecl may be null as in a @dynamic property.
2826 if (ImpMethodDecl) {
2827 if (!WarnCategoryMethodImpl)
2828 WarnConflictingTypedMethods(ImpMethodDecl, I,
2829 isa<ObjCProtocolDecl>(CDecl));
2830 else if (!I->isPropertyAccessor())
2831 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2832 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002833 }
2834 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002835
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002836 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2837 // Also, check for methods declared in protocols inherited by
2838 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002839 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002840 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002841 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002842 WarnCategoryMethodImpl);
2843 }
2844
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002845 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002846 // when checking that methods in implementation match their declaration,
2847 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2848 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002849 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002850 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002851 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002852 IMPDecl, Cat, IncompleteImpl,
2853 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002854 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002855 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002856 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002857 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002858 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002859 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002860 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002861 }
2862
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002863 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002864 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002865 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002866 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002867 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002868
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002869 // FIXME. For now, we are not checking for extact match of methods
2870 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002871 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002872 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002873 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002874 I->getSuperClass(), IncompleteImpl, false);
2875 }
2876}
2877
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002878/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2879/// category matches with those implemented in its primary class and
2880/// warns each time an exact match is found.
2881void Sema::CheckCategoryVsClassMethodMatches(
2882 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002883 // Get category's primary class.
2884 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2885 if (!CatDecl)
2886 return;
2887 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2888 if (!IDecl)
2889 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002890 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2891 SelectorSet InsMap, ClsMap;
2892
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002893 for (const auto *I : CatIMPDecl->instance_methods()) {
2894 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002895 // When checking for methods implemented in the category, skip over
2896 // those declared in category class's super class. This is because
2897 // the super class must implement the method.
2898 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2899 continue;
2900 InsMap.insert(Sel);
2901 }
2902
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002903 for (const auto *I : CatIMPDecl->class_methods()) {
2904 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002905 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2906 continue;
2907 ClsMap.insert(Sel);
2908 }
2909 if (InsMap.empty() && ClsMap.empty())
2910 return;
2911
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002912 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002913 bool IncompleteImpl = false;
2914 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2915 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002916 IncompleteImpl, false,
2917 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002918}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002919
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002920void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002921 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002922 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002923 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002924 // Check and see if instance methods in class interface have been
2925 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002926 for (const auto *I : IMPDecl->instance_methods())
2927 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002928
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002929 // Add the selectors for getters/setters of @dynamic properties.
2930 for (const auto *PImpl : IMPDecl->property_impls()) {
2931 // We only care about @dynamic implementations.
2932 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2933 continue;
2934
2935 const auto *P = PImpl->getPropertyDecl();
2936 if (!P) continue;
2937
2938 InsMap.insert(P->getGetterName());
2939 if (!P->getSetterName().isNull())
2940 InsMap.insert(P->getSetterName());
2941 }
2942
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002943 // Check and see if properties declared in the interface have either 1)
2944 // an implementation or 2) there is a @synthesize/@dynamic implementation
2945 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002946 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2947 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2948 LangOpts.ObjCRuntime.isNonFragile() &&
2949 !IDecl->isObjCRequiresPropertyDefs();
2950 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2951 }
2952
Douglas Gregor849ebc22015-06-19 18:14:46 +00002953 // Diagnose null-resettable synthesized setters.
2954 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2955
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002956 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002957 for (const auto *I : IMPDecl->class_methods())
2958 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002959
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002960 // Check for type conflict of methods declared in a class/protocol and
2961 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002962 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002963 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2964 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002965 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002966
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002967 // check all methods implemented in category against those declared
2968 // in its primary class.
2969 if (ObjCCategoryImplDecl *CatDecl =
2970 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2971 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002972
Chris Lattnerda463fe2007-12-12 07:09:47 +00002973 // Check the protocol list for unimplemented methods in the @implementation
2974 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002975 // Check and see if class methods in class interface have been
2976 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002977
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002978 LazyProtocolNameSet ExplicitImplProtocols;
2979
Chris Lattner9ef10f42009-03-01 00:56:52 +00002980 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002981 for (auto *PI : I->all_referenced_protocols())
2982 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2983 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002984 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002985 // For extended class, unimplemented methods in its protocols will
2986 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002987 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002988 for (auto *P : C->protocols())
2989 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002990 IncompleteImpl, InsMap, ClsMap, CDecl,
2991 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002992 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00002993 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002994 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002995 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002996 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002997}
2998
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002999Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00003000Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00003001 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00003002 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003003 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00003004 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003005 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003006 for (unsigned i = 0; i != NumElts; ++i) {
3007 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003008 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003009 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Richard Smithbecb92d2017-10-10 22:33:17 +00003010 LookupOrdinaryName, forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003011 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003012 // GCC apparently allows the following idiom:
3013 //
3014 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3015 // @class XCElementToggler;
3016 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003017 // Here we have chosen to ignore the forward class declaration
3018 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003019 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003020 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003021 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003022 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003023 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003024 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003025 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003026 // as this will force the intended behavior which is to lookup the
3027 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003028 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003029 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3030 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003031 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3032 continue;
3033 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003034 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003035 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00003036
3037 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003038 ObjCInterfaceDecl *PrevIDecl
3039 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003040
3041 IdentifierInfo *ClassName = IdentList[i];
3042 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3043 // A previous decl with a different name is because of
3044 // @compatibility_alias, for example:
3045 // \code
3046 // @class NewImage;
3047 // @compatibility_alias OldImage NewImage;
3048 // \endcode
3049 // A lookup for 'OldImage' will return the 'NewImage' decl.
3050 //
3051 // In such a case use the real declaration name, instead of the alias one,
3052 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3053 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3054 // has been aliased.
3055 ClassName = PrevIDecl->getIdentifier();
3056 }
3057
Douglas Gregor85f3f952015-07-07 03:57:15 +00003058 // If this forward declaration has type parameters, compare them with the
3059 // type parameters of the previous declaration.
3060 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3061 if (PrevIDecl && TypeParams) {
3062 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3063 // Check for consistency with the previous declaration.
3064 if (checkTypeParamListConsistency(
3065 *this, PrevTypeParams, TypeParams,
3066 TypeParamListContext::ForwardDeclaration)) {
3067 TypeParams = nullptr;
3068 }
3069 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3070 // The @interface does not have type parameters. Complain.
3071 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3072 << ClassName
3073 << TypeParams->getSourceRange();
3074 Diag(Def->getLocation(), diag::note_defined_here)
3075 << ClassName;
3076
3077 TypeParams = nullptr;
3078 }
3079 }
3080
Douglas Gregordc9166c2011-12-15 20:29:51 +00003081 ObjCInterfaceDecl *IDecl
3082 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003083 ClassName, TypeParams, PrevIDecl,
3084 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003085 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003086
Douglas Gregordc9166c2011-12-15 20:29:51 +00003087 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003088 CheckObjCDeclScope(IDecl);
3089 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003090 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003091
Richard Smith3beb7c62017-01-12 02:27:38 +00003092 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003093}
3094
John McCall54507ab2011-06-16 01:15:19 +00003095static bool tryMatchRecordTypes(ASTContext &Context,
3096 Sema::MethodMatchStrategy strategy,
3097 const Type *left, const Type *right);
3098
John McCall31168b02011-06-15 23:02:42 +00003099static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3100 QualType leftQT, QualType rightQT) {
3101 const Type *left =
3102 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3103 const Type *right =
3104 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3105
3106 if (left == right) return true;
3107
3108 // If we're doing a strict match, the types have to match exactly.
3109 if (strategy == Sema::MMS_strict) return false;
3110
3111 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3112
3113 // Otherwise, use this absurdly complicated algorithm to try to
3114 // validate the basic, low-level compatibility of the two types.
3115
3116 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003117 TypeInfo LeftTI = Context.getTypeInfo(left);
3118 TypeInfo RightTI = Context.getTypeInfo(right);
3119 if (LeftTI.Width != RightTI.Width)
3120 return false;
3121
3122 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003123 return false;
3124
3125 // Consider all the kinds of non-dependent canonical types:
3126 // - functions and arrays aren't possible as return and parameter types
3127
3128 // - vector types of equal size can be arbitrarily mixed
3129 if (isa<VectorType>(left)) return isa<VectorType>(right);
3130 if (isa<VectorType>(right)) return false;
3131
3132 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003133 // - structs, unions, and Objective-C objects must match more-or-less
3134 // exactly
John McCall31168b02011-06-15 23:02:42 +00003135 // - everything else should be a scalar
3136 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003137 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003138
John McCall9320b872011-09-09 05:25:32 +00003139 // Make scalars agree in kind, except count bools as chars, and group
3140 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003141 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3142 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3143 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3144 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003145 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3146 leftSK = Type::STK_ObjCObjectPointer;
3147 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3148 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003149
3150 // Note that data member pointers and function member pointers don't
3151 // intermix because of the size differences.
3152
3153 return (leftSK == rightSK);
3154}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003155
John McCall54507ab2011-06-16 01:15:19 +00003156static bool tryMatchRecordTypes(ASTContext &Context,
3157 Sema::MethodMatchStrategy strategy,
3158 const Type *lt, const Type *rt) {
3159 assert(lt && rt && lt != rt);
3160
3161 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3162 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3163 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3164
3165 // Require union-hood to match.
3166 if (left->isUnion() != right->isUnion()) return false;
3167
3168 // Require an exact match if either is non-POD.
3169 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3170 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3171 return false;
3172
3173 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003174 TypeInfo LeftTI = Context.getTypeInfo(lt);
3175 TypeInfo RightTI = Context.getTypeInfo(rt);
3176 if (LeftTI.Width != RightTI.Width)
3177 return false;
3178
3179 if (LeftTI.Align != RightTI.Align)
3180 return false;
John McCall54507ab2011-06-16 01:15:19 +00003181
3182 // Require fields to match.
3183 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3184 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3185 for (; li != le && ri != re; ++li, ++ri) {
3186 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3187 return false;
3188 }
3189 return (li == le && ri == re);
3190}
3191
Chris Lattnerda463fe2007-12-12 07:09:47 +00003192/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3193/// returns true, or false, accordingly.
3194/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003195bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3196 const ObjCMethodDecl *right,
3197 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003198 if (!matchTypes(Context, strategy, left->getReturnType(),
3199 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003200 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003201
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003202 // If either is hidden, it is not considered to match.
3203 if (left->isHidden() || right->isHidden())
3204 return false;
3205
David Blaikiebbafb8a2012-03-11 07:00:24 +00003206 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003207 (left->hasAttr<NSReturnsRetainedAttr>()
3208 != right->hasAttr<NSReturnsRetainedAttr>() ||
3209 left->hasAttr<NSConsumesSelfAttr>()
3210 != right->hasAttr<NSConsumesSelfAttr>()))
3211 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003212
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003213 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003214 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3215 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003216
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003217 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003218 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003219 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003220
3221 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3222 return false;
3223
David Blaikiebbafb8a2012-03-11 07:00:24 +00003224 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003225 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3226 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003227 }
3228 return true;
3229}
3230
Manman Ren71224532016-04-09 18:59:48 +00003231static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3232 ObjCMethodDecl *MethodInList) {
3233 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3234 auto *MethodInListProtocol =
3235 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3236 // If this method belongs to a protocol but the method in list does not, or
3237 // vice versa, we say the context is not the same.
3238 if ((MethodProtocol && !MethodInListProtocol) ||
3239 (!MethodProtocol && MethodInListProtocol))
3240 return false;
3241
3242 if (MethodProtocol && MethodInListProtocol)
3243 return true;
3244
3245 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3246 ObjCInterfaceDecl *MethodInListInterface =
3247 MethodInList->getClassInterface();
3248 return MethodInterface == MethodInListInterface;
3249}
3250
Nico Weber2e0c8f72014-12-27 03:58:08 +00003251void Sema::addMethodToGlobalList(ObjCMethodList *List,
3252 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003253 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3254 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003255 if (ObjCCategoryDecl *CD =
3256 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003257 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003258 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003259
Douglas Gregorc454afe2012-01-25 00:19:56 +00003260 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003261 if (List->getMethod() == nullptr) {
3262 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003263 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003264 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003265 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003266
Douglas Gregorc454afe2012-01-25 00:19:56 +00003267 // We've seen a method with this name, see if we have already seen this type
3268 // signature.
3269 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003270 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003271 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003272 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003273 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003274 continue;
3275
Manman Ren051d0b62016-04-13 23:43:56 +00003276 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3277 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003278 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003279 // We need to insert a method into the list if the context is different.
3280 // If the method's declaration matches the list
3281 // a> the method belongs to a different context: we need to insert it, in
3282 // order to emit the availability message, we need to prioritize over
3283 // availability among the methods with the same declaration.
3284 // b> the method belongs to the same context: there is no need to insert a
3285 // new entry.
3286 // If the method's declaration does not match the list, we insert it to the
3287 // end.
3288 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003289 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003290 // Even if two method types do not match, we would like to say
3291 // there is more than one declaration so unavailability/deprecated
3292 // warning is not too noisy.
3293 if (!Method->isDefined())
3294 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003295
3296 // For methods with the same declaration, the one that is deprecated
3297 // should be put in the front for better diagnostics.
3298 if (Method->isDeprecated() && SameDeclaration &&
3299 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3300 ListWithSameDeclaration = List;
3301
3302 if (Method->isUnavailable() && SameDeclaration &&
3303 !ListWithSameDeclaration &&
3304 List->getMethod()->getAvailability() < AR_Deprecated)
3305 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003306 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003307 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003308
3309 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003310
3311 // Propagate the 'defined' bit.
3312 if (Method->isDefined())
3313 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003314 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003315 // Objective-C doesn't allow an @interface for a class after its
3316 // @implementation. So if Method is not defined and there already is
3317 // an entry for this type signature, Method has to be for a different
3318 // class than PrevObjCMethod.
3319 List->setHasMoreThanOneDecl(true);
3320 }
3321
Douglas Gregorc454afe2012-01-25 00:19:56 +00003322 // If a method is deprecated, push it in the global pool.
3323 // This is used for better diagnostics.
3324 if (Method->isDeprecated()) {
3325 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003326 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003327 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003328 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003329 // unless previous one is deprecated.
3330 if (Method->isUnavailable()) {
3331 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003332 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003333 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003334
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003335 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003336 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003337
Douglas Gregorc454afe2012-01-25 00:19:56 +00003338 // We have a new signature for an existing method - add it.
3339 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003340 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003341
Manman Ren051d0b62016-04-13 23:43:56 +00003342 // We insert it right before ListWithSameDeclaration.
3343 if (ListWithSameDeclaration) {
3344 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3345 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3346 ListWithSameDeclaration->setMethod(Method);
3347 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003348 return;
3349 }
3350
Nico Weber2e0c8f72014-12-27 03:58:08 +00003351 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003352}
3353
Sebastian Redl75d8a322010-08-02 23:18:59 +00003354/// \brief Read the contents of the method pool for a given selector from
3355/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003356void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003357 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003358 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003359}
3360
Manman Rena0f31a02016-04-29 19:04:05 +00003361void Sema::updateOutOfDateSelector(Selector Sel) {
3362 if (!ExternalSource)
3363 return;
3364 ExternalSource->updateOutOfDateSelector(Sel);
3365}
3366
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003367void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003368 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003369 // Ignore methods of invalid containers.
3370 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003371 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003372
Douglas Gregor70f449b2012-01-25 00:59:09 +00003373 if (ExternalSource)
3374 ReadMethodPool(Method->getSelector());
3375
Sebastian Redl75d8a322010-08-02 23:18:59 +00003376 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003377 if (Pos == MethodPool.end())
3378 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3379 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003380
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003381 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003382
Sebastian Redl75d8a322010-08-02 23:18:59 +00003383 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003384 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003385}
3386
John McCall31168b02011-06-15 23:02:42 +00003387/// Determines if this is an "acceptable" loose mismatch in the global
3388/// method pool. This exists mostly as a hack to get around certain
3389/// global mismatches which we can't afford to make warnings / errors.
3390/// Really, what we want is a way to take a method out of the global
3391/// method pool.
3392static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3393 ObjCMethodDecl *other) {
3394 if (!chosen->isInstanceMethod())
3395 return false;
3396
3397 Selector sel = chosen->getSelector();
3398 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3399 return false;
3400
3401 // Don't complain about mismatches for -length if the method we
3402 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003403 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003404}
3405
Manman Ren7ed4f982016-04-07 19:32:24 +00003406/// Return true if the given method is wthin the type bound.
3407static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3408 const ObjCObjectType *TypeBound) {
3409 if (!TypeBound)
3410 return true;
3411
3412 if (TypeBound->isObjCId())
3413 // FIXME: should we handle the case of bounding to id<A, B> differently?
3414 return true;
3415
3416 auto *BoundInterface = TypeBound->getInterface();
3417 assert(BoundInterface && "unexpected object type!");
3418
3419 // Check if the Method belongs to a protocol. We should allow any method
3420 // defined in any protocol, because any subclass could adopt the protocol.
3421 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3422 if (MethodProtocol) {
3423 return true;
3424 }
3425
3426 // If the Method belongs to a class, check if it belongs to the class
3427 // hierarchy of the class bound.
3428 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3429 // We allow methods declared within classes that are part of the hierarchy
3430 // of the class bound (superclass of, subclass of, or the same as the class
3431 // bound).
3432 return MethodInterface == BoundInterface ||
3433 MethodInterface->isSuperClassOf(BoundInterface) ||
3434 BoundInterface->isSuperClassOf(MethodInterface);
3435 }
3436 llvm_unreachable("unknow method context");
3437}
3438
Manman Rend2a3cd72016-04-07 19:30:20 +00003439/// We first select the type of the method: Instance or Factory, then collect
3440/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003441bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003442 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003443 bool InstanceFirst, bool CheckTheOther,
3444 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003445 if (ExternalSource)
3446 ReadMethodPool(Sel);
3447
3448 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3449 if (Pos == MethodPool.end())
3450 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003451
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003452 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003453 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3454 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003455 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003456 if (M->getMethod() && !M->getMethod()->isHidden()) {
3457 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3458 Methods.push_back(M->getMethod());
3459 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003460
3461 // Return if we find any method with the desired kind.
3462 if (!Methods.empty())
3463 return Methods.size() > 1;
3464
3465 if (!CheckTheOther)
3466 return false;
3467
3468 // Gather the other kind.
3469 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3470 Pos->second.first;
3471 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003472 if (M->getMethod() && !M->getMethod()->isHidden()) {
3473 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3474 Methods.push_back(M->getMethod());
3475 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003476
Nico Weber2e0c8f72014-12-27 03:58:08 +00003477 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003478}
3479
Manman Rend2a3cd72016-04-07 19:30:20 +00003480bool Sema::AreMultipleMethodsInGlobalPool(
3481 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3482 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3483 // Diagnose finding more than one method in global pool.
3484 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3485 FilteredMethods.push_back(BestMethod);
3486
3487 for (auto *M : Methods)
3488 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3489 FilteredMethods.push_back(M);
3490
3491 if (FilteredMethods.size() > 1)
3492 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3493 receiverIdOrClass);
3494
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003495 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003496 // Test for no method in the pool which should not trigger any warning by
3497 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003498 if (Pos == MethodPool.end())
3499 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003500 ObjCMethodList &MethList =
3501 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003502 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003503}
3504
Sebastian Redl75d8a322010-08-02 23:18:59 +00003505ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003506 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003507 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003508 if (ExternalSource)
3509 ReadMethodPool(Sel);
3510
Sebastian Redl75d8a322010-08-02 23:18:59 +00003511 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003512 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003513 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003514
Douglas Gregor77f49a42013-01-16 18:47:38 +00003515 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003516 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003517 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003518 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003519 if (M->getMethod() && !M->getMethod()->isHidden())
3520 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003521 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003522 return nullptr;
3523}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003524
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003525void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3526 Selector Sel, SourceRange R,
3527 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003528 // We found multiple methods, so we may have to complain.
3529 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003530
Douglas Gregor77f49a42013-01-16 18:47:38 +00003531 // We support a warning which complains about *any* difference in
3532 // method signature.
3533 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003534 receiverIdOrClass &&
3535 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003536 if (strictSelectorMatch) {
3537 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3538 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3539 issueDiagnostic = true;
3540 break;
3541 }
3542 }
3543 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003544
Douglas Gregor77f49a42013-01-16 18:47:38 +00003545 // If we didn't see any strict differences, we won't see any loose
3546 // differences. In ARC, however, we also need to check for loose
3547 // mismatches, because most of them are errors.
3548 if (!strictSelectorMatch ||
3549 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3550 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3551 // This checks if the methods differ in type mismatch.
3552 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3553 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3554 issueDiagnostic = true;
3555 if (getLangOpts().ObjCAutoRefCount)
3556 issueError = true;
3557 break;
3558 }
3559 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003560
Douglas Gregor77f49a42013-01-16 18:47:38 +00003561 if (issueDiagnostic) {
3562 if (issueError)
3563 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3564 else if (strictSelectorMatch)
3565 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3566 else
3567 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003568
Douglas Gregor77f49a42013-01-16 18:47:38 +00003569 Diag(Methods[0]->getLocStart(),
3570 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003571 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003572 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3573 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003574 << Methods[I]->getSourceRange();
3575 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003576 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003577}
3578
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003579ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003580 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3581 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003582 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003583
3584 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003585 for (const ObjCMethodList *Method = &Methods.first; Method;
3586 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003587 if (Method->getMethod() &&
3588 (Method->getMethod()->isDefined() ||
3589 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003590 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003591
3592 for (const ObjCMethodList *Method = &Methods.second; Method;
3593 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003594 if (Method->getMethod() &&
3595 (Method->getMethod()->isDefined() ||
3596 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003597 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003598 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003599}
3600
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003601static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003602HelperSelectorsForTypoCorrection(
3603 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3604 StringRef Typo, const ObjCMethodDecl * Method) {
3605 const unsigned MaxEditDistance = 1;
3606 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003607 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003608
3609 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3610 if (MinPossibleEditDistance > 0 &&
3611 Typo.size() / MinPossibleEditDistance < 1)
3612 return;
3613 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3614 if (EditDistance > MaxEditDistance)
3615 return;
3616 if (EditDistance == BestEditDistance)
3617 BestMethod.push_back(Method);
3618 else if (EditDistance < BestEditDistance) {
3619 BestMethod.clear();
3620 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003621 }
3622}
3623
Fariborz Jahanian75481672013-06-17 17:10:54 +00003624static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3625 QualType ObjectType) {
3626 if (ObjectType.isNull())
3627 return true;
3628 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3629 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003630 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3631 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003632}
3633
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003634const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003635Sema::SelectorsForTypoCorrection(Selector Sel,
3636 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003637 unsigned NumArgs = Sel.getNumArgs();
3638 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003639 bool ObjectIsId = true, ObjectIsClass = true;
3640 if (ObjectType.isNull())
3641 ObjectIsId = ObjectIsClass = false;
3642 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003643 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003644 else if (const ObjCObjectPointerType *ObjCPtr =
3645 ObjectType->getAsObjCInterfacePointerType()) {
3646 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3647 ObjectIsId = ObjectIsClass = false;
3648 }
3649 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3650 ObjectIsClass = false;
3651 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3652 ObjectIsId = false;
3653 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003654 return nullptr;
3655
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003656 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3657 e = MethodPool.end(); b != e; b++) {
3658 // instance methods
3659 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003660 if (M->getMethod() &&
3661 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3662 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003663 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003664 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003665 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003666 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3667 ObjectType))
3668 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003669 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003670 // class methods
3671 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003672 if (M->getMethod() &&
3673 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3674 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003675 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003676 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003677 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003678 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3679 ObjectType))
3680 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003681 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003682 }
3683
3684 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3685 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3686 HelperSelectorsForTypoCorrection(SelectedMethods,
3687 Sel.getAsString(), Methods[i]);
3688 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003689 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003690}
3691
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003692/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003693/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003694/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003695/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003696/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003697void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3698 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003699 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003700 if (Ivar->isInvalidDecl())
3701 continue;
3702 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3703 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3704 if (prevIvar) {
3705 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3706 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3707 Ivar->setInvalidDecl();
3708 }
3709 }
3710 }
3711}
3712
John McCallb61e14e2015-10-27 04:54:50 +00003713/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3714static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3715 if (S.getLangOpts().ObjCWeak) return;
3716
3717 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3718 ivar; ivar = ivar->getNextIvar()) {
3719 if (ivar->isInvalidDecl()) continue;
3720 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3721 if (S.getLangOpts().ObjCWeakRuntime) {
3722 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3723 } else {
3724 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3725 }
3726 }
3727 }
3728}
3729
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003730/// Diagnose attempts to use flexible array member with retainable object type.
3731static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3732 ObjCInterfaceDecl *ID) {
3733 if (!S.getLangOpts().ObjCAutoRefCount)
3734 return;
3735
3736 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3737 ivar = ivar->getNextIvar()) {
3738 if (ivar->isInvalidDecl())
3739 continue;
3740 QualType IvarTy = ivar->getType();
3741 if (IvarTy->isIncompleteArrayType() &&
3742 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3743 IvarTy->isObjCLifetimeType()) {
3744 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3745 ivar->setInvalidDecl();
3746 }
3747 }
3748}
3749
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003750Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3751 switch (CurContext->getDeclKind()) {
3752 case Decl::ObjCInterface:
3753 return Sema::OCK_Interface;
3754 case Decl::ObjCProtocol:
3755 return Sema::OCK_Protocol;
3756 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003757 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003758 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003759 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003760 case Decl::ObjCImplementation:
3761 return Sema::OCK_Implementation;
3762 case Decl::ObjCCategoryImpl:
3763 return Sema::OCK_CategoryImplementation;
3764
3765 default:
3766 return Sema::OCK_None;
3767 }
3768}
3769
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003770static bool IsVariableSizedType(QualType T) {
3771 if (T->isIncompleteArrayType())
3772 return true;
3773 const auto *RecordTy = T->getAs<RecordType>();
3774 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3775}
3776
3777static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3778 ObjCInterfaceDecl *IntfDecl = nullptr;
3779 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3780 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3781 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3782 Ivars = IntfDecl->ivars();
3783 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3784 IntfDecl = ImplDecl->getClassInterface();
3785 Ivars = ImplDecl->ivars();
3786 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3787 if (CategoryDecl->IsClassExtension()) {
3788 IntfDecl = CategoryDecl->getClassInterface();
3789 Ivars = CategoryDecl->ivars();
3790 }
3791 }
3792
3793 // Check if variable sized ivar is in interface and visible to subclasses.
3794 if (!isa<ObjCInterfaceDecl>(OCD)) {
3795 for (auto ivar : Ivars) {
3796 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3797 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3798 << ivar->getDeclName() << ivar->getType();
3799 }
3800 }
3801 }
3802
3803 // Subsequent checks require interface decl.
3804 if (!IntfDecl)
3805 return;
3806
3807 // Check if variable sized ivar is followed by another ivar.
3808 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3809 ivar = ivar->getNextIvar()) {
3810 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3811 continue;
3812 QualType IvarTy = ivar->getType();
3813 bool IsInvalidIvar = false;
3814 if (IvarTy->isIncompleteArrayType()) {
3815 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3816 << ivar->getDeclName() << IvarTy
3817 << TTK_Class; // Use "class" for Obj-C.
3818 IsInvalidIvar = true;
3819 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3820 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3821 S.Diag(ivar->getLocation(),
3822 diag::err_objc_variable_sized_type_not_at_end)
3823 << ivar->getDeclName() << IvarTy;
3824 IsInvalidIvar = true;
3825 }
3826 }
3827 if (IsInvalidIvar) {
3828 S.Diag(ivar->getNextIvar()->getLocation(),
3829 diag::note_next_ivar_declaration)
3830 << ivar->getNextIvar()->getSynthesize();
3831 ivar->setInvalidDecl();
3832 }
3833 }
3834
3835 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3836 // Perform the check only if OCD is the first container to declare ivars to
3837 // avoid multiple warnings for the same ivar.
3838 ObjCIvarDecl *FirstIvar =
3839 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3840 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3841 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3842 while (SuperClass && SuperClass->ivar_empty())
3843 SuperClass = SuperClass->getSuperClass();
3844 if (SuperClass) {
3845 auto IvarIter = SuperClass->ivar_begin();
3846 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3847 const ObjCIvarDecl *LastIvar = *IvarIter;
3848 if (IsVariableSizedType(LastIvar->getType())) {
3849 S.Diag(FirstIvar->getLocation(),
3850 diag::warn_superclass_variable_sized_type_not_at_end)
3851 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3852 << LastIvar->getType() << SuperClass->getDeclName();
3853 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3854 << LastIvar->getDeclName();
3855 }
3856 }
3857 }
3858}
3859
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003860// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003861Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003862 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003863 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003864 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003865
3866 assert(AtEnd.isValid() && "Invalid location for '@end'");
3867
George Burgess IV00f70bd2018-03-01 05:43:23 +00003868 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3869 Decl *ClassDecl = OCD;
3870
Mike Stump11289f42009-09-09 15:08:12 +00003871 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003872 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3873 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003874 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003875
Steve Naroff35c62ae2009-01-08 17:28:14 +00003876 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3877 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3878 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3879
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003880 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003881 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003882 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003883
3884 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003885 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003886 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003887 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003888 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003889 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003890 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003891 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003892 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003893 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003894 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003895 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003896 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003897 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003898 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003899 if (!Context.getSourceManager().isInSystemHeader(
3900 Method->getLocation()))
3901 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3902 << Method->getDeclName();
3903 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3904 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003905 InsMap[Method->getSelector()] = Method;
3906 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003907 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003908 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003909 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003910 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003911 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003912 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003913 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003914 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003915 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003916 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003917 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003918 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003919 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003920 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003921 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003922 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003923 if (!Context.getSourceManager().isInSystemHeader(
3924 Method->getLocation()))
3925 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3926 << Method->getDeclName();
3927 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3928 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003929 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003930 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003931 }
3932 }
3933 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003934 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3935 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003936 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003937 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003938 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003939 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003940
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003941 if (C->IsClassExtension()) {
3942 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3943 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003944 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003945 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003946 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003947 if (CDecl->getIdentifier())
3948 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3949 // user-defined setter/getter. It also synthesizes setter/getter methods
3950 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003951 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003952 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003953 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003954 }
3955 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003956 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003957 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003958 // Any property declared in a class extension might have user
3959 // declared setter or getter in current class extension or one
3960 // of the other class extensions. Mark them as synthesized as
3961 // property will be synthesized when property with same name is
3962 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003963 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003964 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003965 // Skip over properties declared @dynamic
3966 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003967 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3968 Property->getQueryKind()))
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003969 if (PIDecl->getPropertyImplementation()
3970 == ObjCPropertyImplDecl::Dynamic)
3971 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003972
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003973 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003974 if (ObjCMethodDecl *GetterMethod
3975 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003976 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003977 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003978 if (ObjCMethodDecl *SetterMethod
3979 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003980 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003981 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003982 }
3983 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003984 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003985 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003986 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003987 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003988 if (IDecl->hasDesignatedInitializers())
3989 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00003990 DiagnoseWeakIvars(*this, IC);
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003991 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003992
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003993 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00003994 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003995 // This class has no superclass, so check that it has been marked with
3996 // __attribute((objc_root_class)).
3997 if (!HasRootClassAttr) {
3998 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00003999 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004000 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4001 << IDecl->getIdentifier();
4002 // See if NSObject is in the current scope, and if it is, suggest
4003 // adding " : NSObject " to the class declaration.
4004 NamedDecl *IF = LookupSingleName(TUScope,
4005 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4006 DeclLoc, LookupOrdinaryName);
4007 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4008 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4009 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4010 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4011 } else {
4012 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4013 }
4014 }
4015 } else if (HasRootClassAttr) {
4016 // Complain that only root classes may have this attribute.
4017 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4018 }
4019
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004020 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4021 // An interface can subclass another interface with a
4022 // objc_subclassing_restricted attribute when it has that attribute as
4023 // well (because of interfaces imported from Swift). Therefore we have
4024 // to check if we can subclass in the implementation as well.
4025 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4026 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4027 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4028 Diag(Super->getLocation(), diag::note_class_declared);
4029 }
4030 }
4031
John McCall5fb5df92012-06-20 06:18:46 +00004032 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00004033 while (IDecl->getSuperClass()) {
4034 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4035 IDecl = IDecl->getSuperClass();
4036 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004037 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004038 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004039 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00004040 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00004041 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00004042 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004043
Chris Lattnerda463fe2007-12-12 07:09:47 +00004044 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00004045 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00004046 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004047 if (ObjCCategoryDecl *Cat
4048 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4049 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004050 }
4051 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004052 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4053 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4054 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4055 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4056 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4057 Diag(Super->getLocation(), diag::note_class_declared);
4058 }
4059 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00004060 }
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004061 DiagnoseVariableSizedIvars(*this, OCD);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004062 if (isInterfaceDeclKind) {
4063 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004064 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004065 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004066 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4067 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004068 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00004069 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00004070 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004071 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004072 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00004073 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004074
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004075 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004076 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004077 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4078 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004079 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4080 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004081
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00004082 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004083 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004084}
4085
Chris Lattnerda463fe2007-12-12 07:09:47 +00004086/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4087/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00004088static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004089CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00004090 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004091}
4092
Douglas Gregor33823722011-06-11 01:09:30 +00004093/// \brief Check whether the declared result type of the given Objective-C
4094/// method declaration is compatible with the method's class.
4095///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004096static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00004097CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4098 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00004099 QualType ResultType = Method->getReturnType();
4100
Douglas Gregor33823722011-06-11 01:09:30 +00004101 // If an Objective-C method inherits its related result type, then its
4102 // declared result type must be compatible with its own class type. The
4103 // declared result type is compatible if:
4104 if (const ObjCObjectPointerType *ResultObjectType
4105 = ResultType->getAs<ObjCObjectPointerType>()) {
4106 // - it is id or qualified id, or
4107 if (ResultObjectType->isObjCIdType() ||
4108 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004109 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004110
4111 if (CurrentClass) {
4112 if (ObjCInterfaceDecl *ResultClass
4113 = ResultObjectType->getInterfaceDecl()) {
4114 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00004115 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004116 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004117
4118 // - it is a superclass of the method's class type
4119 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004120 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004121 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004122 } else {
4123 // Any Objective-C pointer type might be acceptable for a protocol
4124 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004125 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004126 }
4127 }
4128
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004129 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004130}
4131
John McCalld2930c22011-07-22 02:45:48 +00004132namespace {
4133/// A helper class for searching for methods which a particular method
4134/// overrides.
4135class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004136public:
John McCalld2930c22011-07-22 02:45:48 +00004137 Sema &S;
4138 ObjCMethodDecl *Method;
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004139 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004140 bool Recursive;
4141
4142public:
4143 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4144 Selector selector = method->getSelector();
4145
4146 // Bypass this search if we've never seen an instance/class method
4147 // with this selector before.
4148 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4149 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004150 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004151 S.ReadMethodPool(selector);
4152
4153 it = S.MethodPool.find(selector);
4154 if (it == S.MethodPool.end())
4155 return;
John McCalld2930c22011-07-22 02:45:48 +00004156 }
4157 ObjCMethodList &list =
4158 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004159 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004160
4161 ObjCContainerDecl *container
4162 = cast<ObjCContainerDecl>(method->getDeclContext());
4163
4164 // Prevent the search from reaching this container again. This is
4165 // important with categories, which override methods from the
4166 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004167 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4168 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004169 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4170 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004171 } else {
4172 searchFromContainer(container);
4173 }
Douglas Gregor33823722011-06-11 01:09:30 +00004174 }
John McCalld2930c22011-07-22 02:45:48 +00004175
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004176 typedef decltype(Overridden)::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004177 iterator begin() const { return Overridden.begin(); }
4178 iterator end() const { return Overridden.end(); }
4179
4180private:
4181 void searchFromContainer(ObjCContainerDecl *container) {
4182 if (container->isInvalidDecl()) return;
4183
4184 switch (container->getDeclKind()) {
4185#define OBJCCONTAINER(type, base) \
4186 case Decl::type: \
4187 searchFrom(cast<type##Decl>(container)); \
4188 break;
4189#define ABSTRACT_DECL(expansion)
4190#define DECL(type, base) \
4191 case Decl::type:
4192#include "clang/AST/DeclNodes.inc"
4193 llvm_unreachable("not an ObjC container!");
4194 }
4195 }
4196
4197 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004198 if (!protocol->hasDefinition())
4199 return;
4200
John McCalld2930c22011-07-22 02:45:48 +00004201 // A method in a protocol declaration overrides declarations from
4202 // referenced ("parent") protocols.
4203 search(protocol->getReferencedProtocols());
4204 }
4205
4206 void searchFrom(ObjCCategoryDecl *category) {
4207 // A method in a category declaration overrides declarations from
4208 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004209 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004210 search(category->getReferencedProtocols());
4211 }
4212
4213 void searchFrom(ObjCCategoryImplDecl *impl) {
4214 // A method in a category definition that has a category
4215 // declaration overrides declarations from the category
4216 // declaration.
4217 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4218 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004219 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4220 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004221
4222 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004223 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4224 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004225 }
4226 }
4227
4228 void searchFrom(ObjCInterfaceDecl *iface) {
4229 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004230 if (!iface->hasDefinition())
4231 return;
4232
John McCalld2930c22011-07-22 02:45:48 +00004233 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004234 for (auto *Cat : iface->known_categories())
4235 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004236
4237 // - the super class, and
4238 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4239 search(super);
4240
4241 // - any referenced protocols.
4242 search(iface->getReferencedProtocols());
4243 }
4244
4245 void searchFrom(ObjCImplementationDecl *impl) {
4246 // A method in a class implementation overrides declarations from
4247 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004248 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4249 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004250 }
4251
John McCalld2930c22011-07-22 02:45:48 +00004252 void search(const ObjCProtocolList &protocols) {
4253 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4254 i != e; ++i)
4255 search(*i);
4256 }
4257
4258 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004259 // Check for a method in this container which matches this selector.
4260 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004261 Method->isInstanceMethod(),
4262 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004263
4264 // If we find one, record it and bail out.
4265 if (meth) {
4266 Overridden.insert(meth);
4267 return;
4268 }
4269
4270 // Otherwise, search for methods that a hypothetical method here
4271 // would have overridden.
4272
4273 // Note that we're now in a recursive case.
4274 Recursive = true;
4275
4276 searchFromContainer(container);
4277 }
4278};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004279} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004280
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004281void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4282 ObjCInterfaceDecl *CurrentClass,
4283 ResultTypeCompatibilityKind RTC) {
4284 // Search for overridden methods and merge information down from them.
4285 OverrideSearch overrides(*this, ObjCMethod);
4286 // Keep track if the method overrides any method in the class's base classes,
4287 // its protocols, or its categories' protocols; we will keep that info
4288 // in the ObjCMethodDecl.
4289 // For this info, a method in an implementation is not considered as
4290 // overriding the same method in the interface or its categories.
4291 bool hasOverriddenMethodsInBaseOrProtocol = false;
4292 for (OverrideSearch::iterator
4293 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4294 ObjCMethodDecl *overridden = *i;
4295
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004296 if (!hasOverriddenMethodsInBaseOrProtocol) {
4297 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4298 CurrentClass != overridden->getClassInterface() ||
4299 overridden->isOverriding()) {
4300 hasOverriddenMethodsInBaseOrProtocol = true;
4301
4302 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4303 // OverrideSearch will return as "overridden" the same method in the
4304 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4305 // check whether a category of a base class introduced a method with the
4306 // same selector, after the interface method declaration.
4307 // To avoid unnecessary lookups in the majority of cases, we use the
4308 // extra info bits in GlobalMethodPool to check whether there were any
4309 // category methods with this selector.
4310 GlobalMethodPool::iterator It =
4311 MethodPool.find(ObjCMethod->getSelector());
4312 if (It != MethodPool.end()) {
4313 ObjCMethodList &List =
4314 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4315 unsigned CategCount = List.getBits();
4316 if (CategCount > 0) {
4317 // If the method is in a category we'll do lookup if there were at
4318 // least 2 category methods recorded, otherwise only one will do.
4319 if (CategCount > 1 ||
4320 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4321 OverrideSearch overrides(*this, overridden);
4322 for (OverrideSearch::iterator
4323 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4324 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004325 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4326 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004327 hasOverriddenMethodsInBaseOrProtocol = true;
4328 overridden->setOverriding(true);
4329 break;
4330 }
4331 }
4332 }
4333 }
4334 }
4335 }
4336 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004337
4338 // Propagate down the 'related result type' bit from overridden methods.
4339 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4340 ObjCMethod->SetRelatedResultType();
4341
4342 // Then merge the declarations.
4343 mergeObjCMethodDecls(ObjCMethod, overridden);
4344
4345 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4346 continue; // Conflicting properties are detected elsewhere.
4347
4348 // Check for overriding methods
4349 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4350 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4351 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4352 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4353
4354 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004355 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4356 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004357 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4358 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004359 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4360 PrevE = overridden->param_end();
4361 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004362 assert(PrevI != overridden->param_end() && "Param mismatch");
4363 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4364 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4365 // If type of argument of method in this class does not match its
4366 // respective argument type in the super class method, issue warning;
4367 if (!Context.typesAreCompatible(T1, T2)) {
4368 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4369 << T1 << T2;
4370 Diag(overridden->getLocation(), diag::note_previous_declaration);
4371 break;
4372 }
4373 }
4374 }
4375 }
4376
4377 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4378}
4379
Douglas Gregor813a0662015-06-19 18:14:38 +00004380/// Merge type nullability from for a redeclaration of the same entity,
4381/// producing the updated type of the redeclared entity.
4382static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4383 QualType type,
4384 bool usesCSKeyword,
4385 SourceLocation prevLoc,
4386 QualType prevType,
4387 bool prevUsesCSKeyword) {
4388 // Determine the nullability of both types.
4389 auto nullability = type->getNullability(S.Context);
4390 auto prevNullability = prevType->getNullability(S.Context);
4391
4392 // Easy case: both have nullability.
4393 if (nullability.hasValue() == prevNullability.hasValue()) {
4394 // Neither has nullability; continue.
4395 if (!nullability)
4396 return type;
4397
4398 // The nullabilities are equivalent; do nothing.
4399 if (*nullability == *prevNullability)
4400 return type;
4401
4402 // Complain about mismatched nullability.
4403 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004404 << DiagNullabilityKind(*nullability, usesCSKeyword)
4405 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004406 return type;
4407 }
4408
4409 // If it's the redeclaration that has nullability, don't change anything.
4410 if (nullability)
4411 return type;
4412
4413 // Otherwise, provide the result with the same nullability.
4414 return S.Context.getAttributedType(
4415 AttributedType::getNullabilityAttrKind(*prevNullability),
4416 type, type);
4417}
4418
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004419/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004420/// (or a category/extension) into the corresponding method in the
4421/// @implementation (for a class or category).
4422static void mergeInterfaceMethodToImpl(Sema &S,
4423 ObjCMethodDecl *method,
4424 ObjCMethodDecl *prevMethod) {
4425 // Merge the objc_requires_super attribute.
4426 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4427 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4428 // merge the attribute into implementation.
4429 method->addAttr(
4430 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4431 method->getLocation()));
4432 }
4433
4434 // Merge nullability of the result type.
4435 QualType newReturnType
4436 = mergeTypeNullabilityForRedecl(
4437 S, method->getReturnTypeSourceRange().getBegin(),
4438 method->getReturnType(),
4439 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4440 prevMethod->getReturnTypeSourceRange().getBegin(),
4441 prevMethod->getReturnType(),
4442 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4443 method->setReturnType(newReturnType);
4444
4445 // Handle each of the parameters.
4446 unsigned numParams = method->param_size();
4447 unsigned numPrevParams = prevMethod->param_size();
4448 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4449 ParmVarDecl *param = method->param_begin()[i];
4450 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4451
4452 // Merge nullability.
4453 QualType newParamType
4454 = mergeTypeNullabilityForRedecl(
4455 S, param->getLocation(), param->getType(),
4456 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4457 prevParam->getLocation(), prevParam->getType(),
4458 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4459 param->setType(newParamType);
4460 }
4461}
4462
Alex Lorenza8a372d2017-04-27 10:43:48 +00004463/// Verify that the method parameters/return value have types that are supported
4464/// by the x86 target.
4465static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4466 const ObjCMethodDecl *Method) {
4467 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4468 llvm::Triple::x86 &&
4469 "x86-specific check invoked for a different target");
4470 SourceLocation Loc;
4471 QualType T;
4472 for (const ParmVarDecl *P : Method->parameters()) {
4473 if (P->getType()->isVectorType()) {
4474 Loc = P->getLocStart();
4475 T = P->getType();
4476 break;
4477 }
4478 }
4479 if (Loc.isInvalid()) {
4480 if (Method->getReturnType()->isVectorType()) {
4481 Loc = Method->getReturnTypeSourceRange().getBegin();
4482 T = Method->getReturnType();
4483 } else
4484 return;
4485 }
4486
4487 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4488 // iOS < 9 and macOS < 10.11.
4489 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4490 VersionTuple AcceptedInVersion;
4491 if (Triple.getOS() == llvm::Triple::IOS)
4492 AcceptedInVersion = VersionTuple(/*Major=*/9);
4493 else if (Triple.isMacOSX())
4494 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4495 else
4496 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004497 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004498 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004499 return;
4500 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4501 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4502 : /*parameter*/ 0)
4503 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4504}
4505
John McCall48871652010-08-21 09:40:31 +00004506Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004507 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004508 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004509 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004510 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004511 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004512 Selector Sel,
4513 // optional arguments. The number of types/arguments is obtained
4514 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004515 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004516 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004517 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004518 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004519 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004520 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004521 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004522 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004523 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00004524 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004525 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004526
Douglas Gregorbab8a962011-09-08 01:46:34 +00004527 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004528 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004529 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004530 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004531
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004532 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004533 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004534
Douglas Gregor813a0662015-06-19 18:14:38 +00004535 QualType bareResultType = resultDeclType;
4536 (void)AttributedType::stripOuterNullability(bareResultType);
4537 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004538 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004539 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004540 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004541 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004542 }
Mike Stump11289f42009-09-09 15:08:12 +00004543
Alp Toker314cc812014-01-25 16:55:45 +00004544 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4545 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4546 MethodType == tok::minus, isVariadic,
4547 /*isPropertyAccessor=*/false,
4548 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4549 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4550 : ObjCMethodDecl::Required,
4551 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004552
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004553 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004554
Chris Lattner23b0faf2009-04-11 19:42:43 +00004555 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004556 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004557 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004558
David Blaikie7d170102013-05-15 07:37:26 +00004559 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004560 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004561 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004562 } else {
John McCall856bbea2009-10-23 21:48:59 +00004563 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004564 }
Mike Stump11289f42009-09-09 15:08:12 +00004565
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004566 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00004567 LookupOrdinaryName, forRedeclarationInCurContext());
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004568 LookupName(R, S);
4569 if (R.isSingleResult()) {
4570 NamedDecl *PrevDecl = R.getFoundDecl();
4571 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004572 Diag(ArgInfo[i].NameLoc,
4573 (MethodDefinition ? diag::warn_method_param_redefinition
4574 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004575 << ArgInfo[i].Name;
4576 Diag(PrevDecl->getLocation(),
4577 diag::note_previous_declaration);
4578 }
4579 }
4580
Abramo Bagnaradff19302011-03-08 08:55:46 +00004581 SourceLocation StartLoc = DI
4582 ? DI->getTypeLoc().getBeginLoc()
4583 : ArgInfo[i].NameLoc;
4584
John McCalld44f4d72011-04-23 02:46:06 +00004585 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4586 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004587 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004588
John McCall82490832011-05-02 00:30:12 +00004589 Param->setObjCMethodScopeInfo(i);
4590
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004591 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004592 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004593
Chris Lattner9713a1c2009-04-11 19:34:56 +00004594 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004595 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004596 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004597
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004598 if (Param->hasAttr<BlocksAttr>()) {
4599 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4600 Param->setInvalidDecl();
4601 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004602 S->AddDecl(Param);
4603 IdResolver.AddDecl(Param);
4604
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004605 Params.push_back(Param);
4606 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004607
Fariborz Jahanian60462092010-04-08 00:30:06 +00004608 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004609 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004610 QualType ArgType = Param->getType();
4611 if (ArgType.isNull())
4612 ArgType = Context.getObjCIdType();
4613 else
4614 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004615 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004616
Fariborz Jahanian60462092010-04-08 00:30:06 +00004617 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004618 Params.push_back(Param);
4619 }
4620
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004621 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004622 ObjCMethod->setObjCDeclQualifier(
4623 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004624
4625 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004626 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004627 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004628
Douglas Gregor87e92752010-12-21 17:34:17 +00004629 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004630 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004631 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004632 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004633 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4634 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004635 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004636 PrevMethod = ImpDecl->getClassMethod(Sel);
4637 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004638 }
Douglas Gregor33823722011-06-11 01:09:30 +00004639
Douglas Gregor813a0662015-06-19 18:14:38 +00004640 // Merge information from the @interface declaration into the
4641 // @implementation.
4642 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4643 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4644 ObjCMethod->isInstanceMethod())) {
4645 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4646
4647 // Warn about defining -dealloc in a category.
4648 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4649 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4650 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4651 << ObjCMethod->getDeclName();
4652 }
4653 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004654 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004655 } else {
4656 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004657 }
John McCalld2930c22011-07-22 02:45:48 +00004658
Chris Lattnerda463fe2007-12-12 07:09:47 +00004659 if (PrevMethod) {
4660 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004661 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004662 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004663 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004664 ObjCMethod->setInvalidDecl();
4665 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004666 }
John McCall28a6aea2009-11-04 02:18:39 +00004667
Douglas Gregor33823722011-06-11 01:09:30 +00004668 // If this Objective-C method does not have a related result type, but we
4669 // are allowed to infer related result types, try to do so based on the
4670 // method family.
4671 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4672 if (!CurrentClass) {
4673 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4674 CurrentClass = Cat->getClassInterface();
4675 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4676 CurrentClass = Impl->getClassInterface();
4677 else if (ObjCCategoryImplDecl *CatImpl
4678 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4679 CurrentClass = CatImpl->getClassInterface();
4680 }
John McCalld2930c22011-07-22 02:45:48 +00004681
Douglas Gregorbab8a962011-09-08 01:46:34 +00004682 ResultTypeCompatibilityKind RTC
4683 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004684
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004685 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004686
John McCall31168b02011-06-15 23:02:42 +00004687 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004688 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004689 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004690
Douglas Gregorbab8a962011-09-08 01:46:34 +00004691 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004692 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004693 !ObjCMethod->hasRelatedResultType() &&
4694 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004695 bool InferRelatedResultType = false;
4696 switch (ObjCMethod->getMethodFamily()) {
4697 case OMF_None:
4698 case OMF_copy:
4699 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004700 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004701 case OMF_mutableCopy:
4702 case OMF_release:
4703 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004704 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004705 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004706 break;
4707
4708 case OMF_alloc:
4709 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004710 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004711 break;
4712
4713 case OMF_init:
4714 case OMF_autorelease:
4715 case OMF_retain:
4716 case OMF_self:
4717 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4718 break;
4719 }
4720
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004721 if (InferRelatedResultType &&
4722 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004723 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004724 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004725
Alex Lorenza8a372d2017-04-27 10:43:48 +00004726 if (MethodDefinition &&
4727 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4728 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4729
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004730 ActOnDocumentableDecl(ObjCMethod);
4731
John McCall48871652010-08-21 09:40:31 +00004732 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004733}
4734
Chris Lattner438e5012008-12-17 07:13:27 +00004735bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004736 // Following is also an error. But it is caused by a missing @end
4737 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004738 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004739 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004740
4741 // If we switched context to translation unit while we are still lexically in
4742 // an objc container, it means the parser missed emitting an error.
4743 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4744 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004745
Anders Carlssona6b508a2008-11-04 16:57:32 +00004746 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4747 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004748
Anders Carlssona6b508a2008-11-04 16:57:32 +00004749 return true;
4750}
Chris Lattner438e5012008-12-17 07:13:27 +00004751
James Dennett634962f2012-06-14 21:40:34 +00004752/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004753/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004754void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004755 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004756 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004757 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004758 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004759 if (!Class) {
4760 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4761 return;
4762 }
John McCall5fb5df92012-06-20 06:18:46 +00004763 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004764 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4765 return;
4766 }
Mike Stump11289f42009-09-09 15:08:12 +00004767
Chris Lattner438e5012008-12-17 07:13:27 +00004768 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004769 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004770 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004771 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004772 for (unsigned i = 0; i < Ivars.size(); i++) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00004773 const FieldDecl* ID = Ivars[i];
John McCall48871652010-08-21 09:40:31 +00004774 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004775 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4776 /*FIXME: StartL=*/ID->getLocation(),
4777 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004778 ID->getIdentifier(), ID->getType(),
4779 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004780 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004781 }
Mike Stump11289f42009-09-09 15:08:12 +00004782
Chris Lattner438e5012008-12-17 07:13:27 +00004783 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004784 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004785 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004786 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004787 if (getLangOpts().CPlusPlus)
George Burgess IV00f70bd2018-03-01 05:43:23 +00004788 PushOnScopeChains(FD, S);
John McCall48871652010-08-21 09:40:31 +00004789 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004790 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004791 }
4792}
4793
Douglas Gregorf3564192010-04-26 17:32:49 +00004794/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004795VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4796 SourceLocation StartLoc,
4797 SourceLocation IdLoc,
4798 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004799 bool Invalid) {
4800 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4801 // duration shall not be qualified by an address-space qualifier."
4802 // Since all parameters have automatic store duration, they can not have
4803 // an address space.
Alexander Richardson6d989432017-10-15 18:48:14 +00004804 if (T.getAddressSpace() != LangAS::Default) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004805 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004806 Invalid = true;
4807 }
4808
4809 // An @catch parameter must be an unqualified object pointer type;
4810 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4811 if (Invalid) {
4812 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004813 } else if (T->isDependentType()) {
4814 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004815 } else if (!T->isObjCObjectPointerType()) {
4816 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004817 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004818 } else if (T->isObjCQualifiedIdType()) {
4819 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004820 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004821 }
4822
Abramo Bagnaradff19302011-03-08 08:55:46 +00004823 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004824 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004825 New->setExceptionVariable(true);
4826
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004827 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004828 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004829 Invalid = true;
4830
Douglas Gregorf3564192010-04-26 17:32:49 +00004831 if (Invalid)
4832 New->setInvalidDecl();
4833 return New;
4834}
4835
John McCall48871652010-08-21 09:40:31 +00004836Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004837 const DeclSpec &DS = D.getDeclSpec();
4838
4839 // We allow the "register" storage class on exception variables because
4840 // GCC did, but we drop it completely. Any other storage class is an error.
4841 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4842 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4843 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004844 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004845 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004846 << DeclSpec::getSpecifierName(SCS);
4847 }
Richard Smith62f19e72016-06-25 00:15:56 +00004848 if (DS.isInlineSpecified())
4849 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004850 << getLangOpts().CPlusPlus17;
Richard Smithb4a9e862013-04-12 22:46:28 +00004851 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4852 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4853 diag::err_invalid_thread)
4854 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004855 D.getMutableDeclSpec().ClearStorageClassSpecs();
4856
Richard Smithb1402ae2013-03-18 22:52:47 +00004857 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004858
4859 // Check that there are no default arguments inside the type of this
4860 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004861 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004862 CheckExtraCXXDefaultArguments(D);
4863
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004864 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004865 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004866
Abramo Bagnaradff19302011-03-08 08:55:46 +00004867 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4868 D.getSourceRange().getBegin(),
4869 D.getIdentifierLoc(),
4870 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004871 D.isInvalidType());
4872
4873 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4874 if (D.getCXXScopeSpec().isSet()) {
4875 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4876 << D.getCXXScopeSpec().getRange();
4877 New->setInvalidDecl();
4878 }
4879
4880 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004881 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004882 if (D.getIdentifier())
4883 IdResolver.AddDecl(New);
4884
4885 ProcessDeclAttributes(S, New, D);
4886
4887 if (New->hasAttr<BlocksAttr>())
4888 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004889 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004890}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004891
4892/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004893/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004894void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004895 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004896 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4897 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004898 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004899 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004900 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004901 }
4902}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004903
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004904void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004905 // Load referenced selectors from the external source.
4906 if (ExternalSource) {
4907 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4908 ExternalSource->ReadReferencedSelectors(Sels);
4909 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4910 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4911 }
4912
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004913 // Warning will be issued only when selector table is
4914 // generated (which means there is at lease one implementation
4915 // in the TU). This is to match gcc's behavior.
4916 if (ReferencedSelectors.empty() ||
4917 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004918 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004919 for (auto &SelectorAndLocation : ReferencedSelectors) {
4920 Selector Sel = SelectorAndLocation.first;
4921 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004922 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004923 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004924 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004925}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004926
4927ObjCIvarDecl *
4928Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4929 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004930 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004931 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004932 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4933 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004934 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004935 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4936 /*shallowCategoryLookup=*/false,
4937 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004938 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004939 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004940 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004941 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4942 // property backing ivar must belong to property's class
4943 // or be a private ivar in class's implementation.
4944 // FIXME. fix the const-ness issue.
4945 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4946 IV->getIdentifier());
4947 return IV;
4948 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004949 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004950}
4951
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004952namespace {
4953 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4954 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004955 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00004956 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004957 public:
4958 Sema &S;
4959 const ObjCMethodDecl *Method;
4960 const ObjCIvarDecl *IvarD;
4961 bool AccessedIvar;
4962 bool InvokedSelfMethod;
4963
4964 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4965 const ObjCIvarDecl *IvarD)
4966 : S(S), Method(Method), IvarD(IvarD),
4967 AccessedIvar(false), InvokedSelfMethod(false) {
4968 assert(IvarD);
4969 }
4970
4971 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4972 if (E->getDecl() == IvarD) {
4973 AccessedIvar = true;
4974 return false;
4975 }
4976 return true;
4977 }
4978
4979 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4980 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4981 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4982 InvokedSelfMethod = true;
4983 }
4984 return true;
4985 }
4986 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00004987} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004988
4989void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4990 const ObjCImplementationDecl *ImplD) {
4991 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004992 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004993
Aaron Ballmanf26acce2014-03-13 19:50:17 +00004994 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004995 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4996 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004997 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004998 continue;
4999
5000 const ObjCPropertyDecl *PDecl;
5001 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5002 if (!IV)
5003 continue;
5004
5005 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5006 Checker.TraverseStmt(CurMethod->getBody());
5007 if (Checker.AccessedIvar)
5008 continue;
5009
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005010 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005011 // implementation makes a self call. This is to prevent false positive in
5012 // cases where the ivar is accessed by another method that the accessor
5013 // delegates to.
5014 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00005015 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005016 Diag(PDecl->getLocation(), diag::note_property_declare);
5017 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005018 }
5019}