blob: 90a6264cb120cb1495df682b9e64073f68005481 [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
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.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"
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +000018#include "clang/AST/DataRecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclObjC.h"
Steve Naroff157599f2009-03-03 14:49:36 +000020#include "clang/AST/Expr.h"
John McCall31168b02011-06-15 23:02:42 +000021#include "clang/AST/ExprObjC.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"
24#include "clang/Sema/ExternalSemaSource.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
John McCalla1e130b2010-08-25 07:03:20 +000028#include "llvm/ADT/DenseSet.h"
29
Chris Lattnerda463fe2007-12-12 07:09:47 +000030using namespace clang;
31
John McCall31168b02011-06-15 23:02:42 +000032/// Check whether the given method, which must be in the 'init'
33/// family, is a valid member of that family.
34///
35/// \param receiverTypeIfCall - if null, check this as if declaring it;
36/// if non-null, check this as if making a call to it with the given
37/// receiver type
38///
39/// \return true to indicate that there was an error and appropriate
40/// actions were taken
41bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
44
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
48
49 // We ignore protocols here. Should we? What about Class?
50
Alp Toker314cc812014-01-25 16:55:45 +000051 const ObjCObjectType *result =
52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCall31168b02011-06-15 23:02:42 +000053
54 if (result->isObjCId()) {
55 return false;
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
58 } else {
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
61
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
Douglas Gregordc9166c2011-12-15 20:29:51 +000064 if (!resultClass->hasDefinition()) {
John McCall31168b02011-06-15 23:02:42 +000065 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
67 return false;
68
69 // Otherwise, we try to compare class types.
70 } else {
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
Craig Topperc3ec1492014-05-26 06:22:03 +000073 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCall31168b02011-06-15 23:02:42 +000074 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
76 return false;
77
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79 ->getInterfaceDecl();
80
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
83 } else {
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
86 }
87
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
91 return false;
92 }
93 }
94
95 SourceLocation loc = method->getLocation();
96
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
Aaron Ballman36a53502014-01-16 13:03:14 +0000100 method->addAttr(UnavailableAttr::CreateImplicit(Context,
101 "init method returns a type unrelated to its receiver type",
102 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 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000159 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
163 diag::err_nsreturns_retained_attribute_mismatch) << 1;
164 Diag(Overridden->getLocation(), diag::note_previous_decl)
165 << "method";
166 }
167 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
168 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
169 Diag(NewMethod->getLocation(),
170 diag::err_nsreturns_retained_attribute_mismatch) << 0;
171 Diag(Overridden->getLocation(), diag::note_previous_decl)
172 << "method";
173 }
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000174 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
175 oe = Overridden->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000176 for (ObjCMethodDecl::param_iterator
177 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000178 ni != ne && oi != oe; ++ni, ++oi) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000179 const ParmVarDecl *oldDecl = (*oi);
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000180 ParmVarDecl *newDecl = (*ni);
181 if (newDecl->hasAttr<NSConsumedAttr>() !=
182 oldDecl->hasAttr<NSConsumedAttr>()) {
183 Diag(newDecl->getLocation(),
184 diag::err_nsconsumed_attribute_mismatch);
185 Diag(oldDecl->getLocation(), diag::note_previous_decl)
186 << "parameter";
187 }
188 }
189 }
Douglas Gregor33823722011-06-11 01:09:30 +0000190}
191
John McCall31168b02011-06-15 23:02:42 +0000192/// \brief Check a method declaration for compatibility with the Objective-C
193/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000194bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000195 ObjCMethodFamily family = method->getMethodFamily();
196 switch (family) {
197 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000198 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000199 case OMF_retain:
200 case OMF_release:
201 case OMF_autorelease:
202 case OMF_retainCount:
203 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000204 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000205 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000206 return false;
207
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000208 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000209 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000210 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000211 if (ResultTypeRange.isInvalid())
Alp Toker314cc812014-01-25 16:55:45 +0000212 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
213 << method->getReturnType()
214 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000215 else
Alp Toker314cc812014-01-25 16:55:45 +0000216 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
217 << method->getReturnType()
218 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000219 return true;
220 }
221 return false;
222
John McCall31168b02011-06-15 23:02:42 +0000223 case OMF_init:
224 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000225 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000226 return true;
227
Aaron Ballman36a53502014-01-16 13:03:14 +0000228 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000229
230 // Don't add a second copy of this attribute, but otherwise don't
231 // let it be suppressed.
232 if (method->hasAttr<NSReturnsRetainedAttr>())
233 return false;
234 break;
235
236 case OMF_alloc:
237 case OMF_copy:
238 case OMF_mutableCopy:
239 case OMF_new:
240 if (method->hasAttr<NSReturnsRetainedAttr>() ||
241 method->hasAttr<NSReturnsNotRetainedAttr>() ||
242 method->hasAttr<NSReturnsAutoreleasedAttr>())
243 return false;
244 break;
245 }
246
Aaron Ballman36a53502014-01-16 13:03:14 +0000247 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000248 return false;
249}
250
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000251static void DiagnoseObjCImplementedDeprecations(Sema &S,
252 NamedDecl *ND,
253 SourceLocation ImplLoc,
254 int select) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000255 if (ND && ND->isDeprecated()) {
Fariborz Jahanian6fd94352011-02-16 00:30:31 +0000256 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000257 if (select == 0)
Ted Kremenek59b10db2012-02-27 22:55:11 +0000258 S.Diag(ND->getLocation(), diag::note_method_declared_at)
259 << ND->getDeclName();
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000260 else
261 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
262 }
263}
264
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000265/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
266/// pool.
267void Sema::AddAnyMethodToGlobalPool(Decl *D) {
268 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
269
270 // If we don't have a valid method decl, simply return.
271 if (!MDecl)
272 return;
273 if (MDecl->isInstanceMethod())
274 AddInstanceMethodToGlobalPool(MDecl, true);
275 else
276 AddFactoryMethodToGlobalPool(MDecl, true);
277}
278
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000279/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
280/// has explicit ownership attribute; false otherwise.
281static bool
282HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
283 QualType T = Param->getType();
284
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000285 if (const PointerType *PT = T->getAs<PointerType>()) {
286 T = PT->getPointeeType();
287 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
288 T = RT->getPointeeType();
289 } else {
290 return true;
291 }
292
293 // If we have a lifetime qualifier, but it's local, we must have
294 // inferred it. So, it is implicit.
295 return !T.getLocalQualifiers().hasObjCLifetime();
296}
297
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000298/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
299/// and user declared, in the method definition's AST.
300void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000301 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000302 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000303
Steve Naroff542cd5d2008-07-25 17:57:26 +0000304 // If we don't have a valid method decl, simply return.
305 if (!MDecl)
306 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000307
Chris Lattnerda463fe2007-12-12 07:09:47 +0000308 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000309 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000310 PushFunctionScope();
311
Chris Lattnerda463fe2007-12-12 07:09:47 +0000312 // Create Decl objects for each parameter, entrring them in the scope for
313 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000314
315 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000316 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000317
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000318 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
319 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000320
Reid Kleckner5a115802013-06-24 14:38:26 +0000321 // The ObjC parser requires parameter names so there's no need to check.
322 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
323 /*CheckParameterNames=*/false);
324
Chris Lattner58258242008-04-10 02:22:51 +0000325 // Introduce all of the other parameters into this scope.
Aaron Ballman43b68be2014-03-07 17:50:17 +0000326 for (auto *Param : MDecl->params()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000327 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000328 getLangOpts().ObjCAutoRefCount &&
329 !HasExplicitOwnershipAttr(*this, Param))
330 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
331 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000332
Aaron Ballman43b68be2014-03-07 17:50:17 +0000333 if (Param->getIdentifier())
334 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000335 }
John McCall31168b02011-06-15 23:02:42 +0000336
337 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000338 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000339 switch (MDecl->getMethodFamily()) {
340 case OMF_retain:
341 case OMF_retainCount:
342 case OMF_release:
343 case OMF_autorelease:
344 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000345 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000346 break;
347
348 case OMF_None:
349 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000350 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000351 case OMF_alloc:
352 case OMF_init:
353 case OMF_mutableCopy:
354 case OMF_copy:
355 case OMF_new:
356 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000357 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000358 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000359 break;
360 }
361 }
362
Nico Weber715abaf2011-08-22 17:25:57 +0000363 // Warn on deprecated methods under -Wdeprecated-implementations,
364 // and prepare for warning on missing super calls.
365 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000366 ObjCMethodDecl *IMD =
367 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
368
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000369 if (IMD) {
370 ObjCImplDecl *ImplDeclOfMethodDef =
371 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
372 ObjCContainerDecl *ContDeclOfMethodDecl =
373 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000374 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000375 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
376 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000377 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
378 if (CD->IsClassExtension()) {
379 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
380 ImplDeclOfMethodDecl = OID->getImplementation();
381 } else
382 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000383 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000384 // No need to issue deprecated warning if deprecated mehod in class/category
385 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000386 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000387 DiagnoseObjCImplementedDeprecations(*this,
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000388 dyn_cast<NamedDecl>(IMD),
389 MDecl->getLocation(), 0);
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000390 }
Nico Weber715abaf2011-08-22 17:25:57 +0000391
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000392 if (MDecl->getMethodFamily() == OMF_init) {
393 if (MDecl->isDesignatedInitializerForTheInterface()) {
394 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000395 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000396 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000397 } else if (IC->hasDesignatedInitializers()) {
398 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000399 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000400 }
401 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000402
Nico Weber1fb82662011-08-28 22:35:17 +0000403 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000404 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
405 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
406 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000407 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000408 ObjCMethodFamily Family = MDecl->getMethodFamily();
409 if (Family == OMF_dealloc) {
410 if (!(getLangOpts().ObjCAutoRefCount ||
411 getLangOpts().getGC() == LangOptions::GCOnly))
412 getCurFunction()->ObjCShouldCallSuper = true;
413
414 } else if (Family == OMF_finalize) {
415 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
416 getCurFunction()->ObjCShouldCallSuper = true;
417
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000418 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000419 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000420 SuperClass->lookupMethod(MDecl->getSelector(),
421 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000422 getCurFunction()->ObjCShouldCallSuper =
423 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000424 }
Nico Weber1fb82662011-08-28 22:35:17 +0000425 }
Nico Weber715abaf2011-08-22 17:25:57 +0000426 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000427}
428
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000429namespace {
430
431// Callback to only accept typo corrections that are Objective-C classes.
432// If an ObjCInterfaceDecl* is given to the constructor, then the validation
433// function will reject corrections to that class.
434class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
435 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000436 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000437 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
438 : CurrentIDecl(IDecl) {}
439
Craig Toppere14c0f82014-03-12 04:55:44 +0000440 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000441 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
442 return ID && !declaresSameEntity(ID, CurrentIDecl);
443 }
444
445 private:
446 ObjCInterfaceDecl *CurrentIDecl;
447};
448
449}
450
John McCall48871652010-08-21 09:40:31 +0000451Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +0000452ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
453 IdentifierInfo *ClassName, SourceLocation ClassLoc,
454 IdentifierInfo *SuperName, SourceLocation SuperLoc,
John McCall48871652010-08-21 09:40:31 +0000455 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000456 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000457 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000458 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000459
Chris Lattnerda463fe2007-12-12 07:09:47 +0000460 // Check for another declaration kind with the same name.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000461 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000462 LookupOrdinaryName, ForRedeclaration);
Douglas Gregor5101c242008-12-05 18:15:24 +0000463
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000464 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000465 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000466 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000467 }
Mike Stump11289f42009-09-09 15:08:12 +0000468
Douglas Gregordc9166c2011-12-15 20:29:51 +0000469 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000470 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000471
472 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
473 // A previous decl with a different name is because of
474 // @compatibility_alias, for example:
475 // \code
476 // @class NewImage;
477 // @compatibility_alias OldImage NewImage;
478 // \endcode
479 // A lookup for 'OldImage' will return the 'NewImage' decl.
480 //
481 // In such a case use the real declaration name, instead of the alias one,
482 // otherwise we will break IdentifierResolver and redecls-chain invariants.
483 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
484 // has been aliased.
485 ClassName = PrevIDecl->getIdentifier();
486 }
487
Douglas Gregordc9166c2011-12-15 20:29:51 +0000488 ObjCInterfaceDecl *IDecl
489 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000490 PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000491
Douglas Gregordc9166c2011-12-15 20:29:51 +0000492 if (PrevIDecl) {
493 // Class already seen. Was it a definition?
494 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
495 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
496 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +0000497 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000498 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +0000499 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000500 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000501
502 if (AttrList)
503 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
504 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +0000505
Douglas Gregordc9166c2011-12-15 20:29:51 +0000506 // Start the definition of this class. If we're in a redefinition case, there
507 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +0000508 if (!IDecl->hasDefinition())
509 IDecl->startDefinition();
510
Chris Lattnerda463fe2007-12-12 07:09:47 +0000511 if (SuperName) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000512 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000513 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
514 LookupOrdinaryName);
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000515
516 if (!PrevDecl) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000517 // Try to correct for a typo in the superclass name without correcting
518 // to the class we're defining.
519 ObjCInterfaceValidatorCCC Validator(IDecl);
520 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000521 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
Craig Topperc3ec1492014-05-26 06:22:03 +0000522 nullptr, Validator, CTK_ErrorRecovery)) {
Richard Smithf9b15102013-08-17 00:46:16 +0000523 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
524 << SuperName << ClassName);
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000525 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000526 }
527 }
528
Douglas Gregor0b144e12011-12-15 00:29:59 +0000529 if (declaresSameEntity(PrevDecl, IDecl)) {
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000530 Diag(SuperLoc, diag::err_recursive_superclass)
531 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
Douglas Gregor16408322011-12-15 22:34:59 +0000532 IDecl->setEndOfDefinitionLoc(ClassLoc);
Mike Stump12b8ce12009-08-04 21:02:39 +0000533 } else {
Mike Stump11289f42009-09-09 15:08:12 +0000534 ObjCInterfaceDecl *SuperClassDecl =
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000535 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000536
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000537 // Diagnose classes that inherit from deprecated classes.
538 if (SuperClassDecl)
539 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
Mike Stump11289f42009-09-09 15:08:12 +0000540
Craig Topperc3ec1492014-05-26 06:22:03 +0000541 if (PrevDecl && !SuperClassDecl) {
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000542 // The previous declaration was not a class decl. Check if we have a
543 // typedef. If we do, get the underlying class type.
Richard Smithdda56e42011-04-15 14:24:37 +0000544 if (const TypedefNameDecl *TDecl =
545 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000546 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +0000547 if (T->isObjCObjectType()) {
Fariborz Jahanian83f1be12013-04-04 18:45:52 +0000548 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Douglas Gregor1c283312010-08-11 12:19:30 +0000549 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian83f1be12013-04-04 18:45:52 +0000550 // This handles the following case:
551 // @interface NewI @end
552 // typedef NewI DeprI __attribute__((deprecated("blah")))
553 // @interface SI : DeprI /* warn here */ @end
554 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
555 }
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000556 }
557 }
Mike Stump11289f42009-09-09 15:08:12 +0000558
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000559 // This handles the following case:
560 //
561 // typedef int SuperClass;
562 // @interface MyClass : SuperClass {} @end
563 //
564 if (!SuperClassDecl) {
565 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
566 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Steve Naroff189d41f2009-02-04 17:14:05 +0000567 }
568 }
Mike Stump11289f42009-09-09 15:08:12 +0000569
Richard Smithdda56e42011-04-15 14:24:37 +0000570 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000571 if (!SuperClassDecl)
572 Diag(SuperLoc, diag::err_undef_superclass)
573 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
Douglas Gregor4123a862011-11-14 22:10:01 +0000574 else if (RequireCompleteType(SuperLoc,
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000575 Context.getObjCInterfaceType(SuperClassDecl),
576 diag::err_forward_superclass,
577 SuperClassDecl->getDeclName(),
578 ClassName,
579 SourceRange(AtInterfaceLoc, ClassLoc))) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000580 SuperClassDecl = nullptr;
Fariborz Jahanian3ee91fa2011-06-23 23:16:19 +0000581 }
Steve Naroff189d41f2009-02-04 17:14:05 +0000582 }
Fariborz Jahanian5582f232009-07-09 22:08:26 +0000583 IDecl->setSuperClass(SuperClassDecl);
584 IDecl->setSuperClassLoc(SuperLoc);
Douglas Gregor16408322011-12-15 22:34:59 +0000585 IDecl->setEndOfDefinitionLoc(SuperLoc);
Steve Naroff189d41f2009-02-04 17:14:05 +0000586 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000587 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +0000588 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000589 }
Mike Stump11289f42009-09-09 15:08:12 +0000590
Sebastian Redle7c1fe62010-08-13 00:28:03 +0000591 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +0000592 if (NumProtoRefs) {
Roman Divackye6377112012-09-06 15:59:27 +0000593 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000594 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +0000595 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000596 }
Mike Stump11289f42009-09-09 15:08:12 +0000597
Anders Carlssona6b508a2008-11-04 16:57:32 +0000598 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +0000599 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000600}
601
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +0000602/// ActOnTypedefedProtocols - this action finds protocol list as part of the
603/// typedef'ed use for a qualified super class and adds them to the list
604/// of the protocols.
605void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
606 IdentifierInfo *SuperName,
607 SourceLocation SuperLoc) {
608 if (!SuperName)
609 return;
610 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
611 LookupOrdinaryName);
612 if (!IDecl)
613 return;
614
615 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
616 QualType T = TDecl->getUnderlyingType();
617 if (T->isObjCObjectType())
618 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
Aaron Ballman1683f7b2014-03-17 15:55:30 +0000619 for (auto *I : OPT->quals())
620 ProtocolRefs.push_back(I);
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +0000621 }
622}
623
Richard Smithac4e36d2012-08-08 23:32:13 +0000624/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +0000625/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +0000626Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
627 IdentifierInfo *AliasName,
628 SourceLocation AliasLocation,
629 IdentifierInfo *ClassName,
630 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000631 // Look for previous declaration of alias name
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000632 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000633 LookupOrdinaryName, ForRedeclaration);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000634 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +0000635 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +0000636 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +0000637 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +0000638 }
639 // Check for class declaration
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000640 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000641 LookupOrdinaryName, ForRedeclaration);
Richard Smithdda56e42011-04-15 14:24:37 +0000642 if (const TypedefNameDecl *TDecl =
643 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +0000644 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +0000645 if (T->isObjCObjectType()) {
646 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +0000647 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000648 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000649 LookupOrdinaryName, ForRedeclaration);
Fariborz Jahanian17290c32009-01-08 01:10:55 +0000650 }
651 }
652 }
Chris Lattner219b3e92008-03-16 21:17:37 +0000653 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +0000654 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000655 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +0000656 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +0000657 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +0000658 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +0000659 }
Mike Stump11289f42009-09-09 15:08:12 +0000660
Chris Lattner219b3e92008-03-16 21:17:37 +0000661 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +0000662 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000663 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +0000664
Anders Carlssona6b508a2008-11-04 16:57:32 +0000665 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +0000666 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000667
John McCall48871652010-08-21 09:40:31 +0000668 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +0000669}
670
Fariborz Jahanian7d622732011-05-13 18:02:08 +0000671bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +0000672 IdentifierInfo *PName,
673 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +0000674 const ObjCList<ObjCProtocolDecl> &PList) {
675
676 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +0000677 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
678 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000679 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
680 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +0000681 if (PDecl->getIdentifier() == PName) {
682 Diag(Ploc, diag::err_protocol_has_circular_dependency);
683 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +0000684 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +0000685 }
Douglas Gregore6e48b12012-01-01 19:29:29 +0000686
687 if (!PDecl->hasDefinition())
688 continue;
689
Fariborz Jahanian7d622732011-05-13 18:02:08 +0000690 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
691 PDecl->getLocation(), PDecl->getReferencedProtocols()))
692 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +0000693 }
694 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +0000695 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +0000696}
697
John McCall48871652010-08-21 09:40:31 +0000698Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +0000699Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
700 IdentifierInfo *ProtocolName,
701 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +0000702 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +0000703 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000704 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000705 SourceLocation EndProtoLoc,
706 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +0000707 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +0000708 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000709 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +0000710 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
711 ForRedeclaration);
Craig Topperc3ec1492014-05-26 06:22:03 +0000712 ObjCProtocolDecl *PDecl = nullptr;
713 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +0000714 // If we already have a definition, complain.
715 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
716 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +0000717
Douglas Gregor32c17572012-01-01 20:30:41 +0000718 // Create a new protocol that is completely distinct from previous
719 // declarations, and do not make this protocol available for name lookup.
720 // That way, we'll end up completely ignoring the duplicate.
721 // FIXME: Can we turn this into an error?
722 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
723 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +0000724 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +0000725 PDecl->startDefinition();
726 } else {
727 if (PrevDecl) {
728 // Check for circular dependencies among protocol declarations. This can
729 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +0000730 ObjCList<ObjCProtocolDecl> PList;
731 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
732 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +0000733 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +0000734 }
Douglas Gregor32c17572012-01-01 20:30:41 +0000735
736 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +0000737 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +0000738 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +0000739 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +0000740
Douglas Gregorde9f17e2009-04-23 23:18:26 +0000741 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +0000742 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +0000743 }
Douglas Gregore6e48b12012-01-01 19:29:29 +0000744
Fariborz Jahanian1470e932008-12-17 01:07:27 +0000745 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +0000746 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Douglas Gregor32c17572012-01-01 20:30:41 +0000747
748 // Merge attributes from previous declarations.
749 if (PrevDecl)
750 mergeDeclAttributes(PDecl, PrevDecl);
751
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +0000752 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +0000753 /// Check then save referenced protocols.
Roman Divackye6377112012-09-06 15:59:27 +0000754 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000755 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000756 }
Mike Stump11289f42009-09-09 15:08:12 +0000757
758 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +0000759 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000760}
761
Fariborz Jahanianbf678e82014-03-11 17:10:51 +0000762static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
763 ObjCProtocolDecl *&UndefinedProtocol) {
764 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
765 UndefinedProtocol = PDecl;
766 return true;
767 }
768
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000769 for (auto *PI : PDecl->protocols())
770 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
771 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +0000772 return true;
773 }
774 return false;
775}
776
Chris Lattnerda463fe2007-12-12 07:09:47 +0000777/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +0000778/// issues an error if they are not declared. It returns list of
779/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000780void
Chris Lattner3bbae002008-07-26 04:03:38 +0000781Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000782 const IdentifierLocPair *ProtocolId,
Chris Lattnerda463fe2007-12-12 07:09:47 +0000783 unsigned NumProtocols,
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000784 SmallVectorImpl<Decl *> &Protocols) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000785 for (unsigned i = 0; i != NumProtocols; ++i) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000786 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
787 ProtocolId[i].second);
Chris Lattner9c1842b2008-07-26 03:47:43 +0000788 if (!PDecl) {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000789 DeclFilterCCC<ObjCProtocolDecl> Validator;
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000790 TypoCorrection Corrected = CorrectTypo(
791 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
Craig Topperc3ec1492014-05-26 06:22:03 +0000792 LookupObjCProtocolName, TUScope, nullptr, Validator,
793 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +0000794 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
795 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
796 << ProtocolId[i].first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000797 }
798
799 if (!PDecl) {
Chris Lattner3b054132008-11-19 05:08:23 +0000800 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000801 << ProtocolId[i].first;
Chris Lattner9c1842b2008-07-26 03:47:43 +0000802 continue;
803 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +0000804 // If this is a forward protocol declaration, get its definition.
805 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
806 PDecl = PDecl->getDefinition();
807
Douglas Gregor171c45a2009-02-18 21:56:37 +0000808 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
Chris Lattner9c1842b2008-07-26 03:47:43 +0000809
810 // If this is a forward declaration and we are supposed to warn in this
811 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +0000812 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +0000813 ObjCProtocolDecl *UndefinedProtocol;
814
Douglas Gregoreed49792013-01-17 00:38:46 +0000815 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +0000816 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Chris Lattner3b054132008-11-19 05:08:23 +0000817 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000818 << ProtocolId[i].first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +0000819 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
820 << UndefinedProtocol;
821 }
John McCall48871652010-08-21 09:40:31 +0000822 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000823 }
824}
825
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +0000826/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +0000827/// a class method in its extension.
828///
Mike Stump11289f42009-09-09 15:08:12 +0000829void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +0000830 ObjCInterfaceDecl *ID) {
831 if (!ID)
832 return; // Possibly due to previous error
833
834 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +0000835 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +0000836 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +0000837
838 if (MethodMap.empty())
839 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +0000840 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +0000841 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +0000842 if (PrevMethod &&
843 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
844 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +0000845 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
846 << Method->getDeclName();
847 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
848 }
849 }
850}
851
James Dennett634962f2012-06-14 21:40:34 +0000852/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +0000853Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +0000854Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000855 const IdentifierLocPair *IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +0000856 unsigned NumElts,
857 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +0000858 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +0000859 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattnerd7352d62008-07-21 22:17:28 +0000860 IdentifierInfo *Ident = IdentList[i].first;
Douglas Gregor32c17572012-01-01 20:30:41 +0000861 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
862 ForRedeclaration);
863 ObjCProtocolDecl *PDecl
864 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
865 IdentList[i].second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +0000866 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +0000867
868 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +0000869 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +0000870
Douglas Gregor42ff1bb2012-01-01 20:33:24 +0000871 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +0000872 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Douglas Gregor32c17572012-01-01 20:30:41 +0000873
874 if (PrevDecl)
875 mergeDeclAttributes(PDecl, PrevDecl);
876
Douglas Gregorf6102672012-01-01 21:23:57 +0000877 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000878 }
Mike Stump11289f42009-09-09 15:08:12 +0000879
Rafael Espindolaab417692013-07-09 12:05:01 +0000880 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000881}
882
John McCall48871652010-08-21 09:40:31 +0000883Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +0000884ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
885 IdentifierInfo *ClassName, SourceLocation ClassLoc,
886 IdentifierInfo *CategoryName,
887 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +0000888 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000889 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000890 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000891 SourceLocation EndProtoLoc) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000892 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000893 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +0000894
895 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +0000896
897 if (!IDecl
898 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000899 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +0000900 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +0000901 // Create an invalid ObjCCategoryDecl to serve as context for
902 // the enclosing method declarations. We mark the decl invalid
903 // to make it clear that this isn't a valid AST.
904 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +0000905 ClassLoc, CategoryLoc, CategoryName,IDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +0000906 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +0000907 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +0000908
909 if (!IDecl)
910 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +0000911 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +0000912 }
913
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +0000914 if (!CategoryName && IDecl->getImplementation()) {
915 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
916 Diag(IDecl->getImplementation()->getLocation(),
917 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +0000918 }
919
Fariborz Jahanian30a42922010-02-15 21:55:26 +0000920 if (CategoryName) {
921 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +0000922 if (ObjCCategoryDecl *Previous
923 = IDecl->FindCategoryDeclaration(CategoryName)) {
924 // Class extensions can be declared multiple times, categories cannot.
925 Diag(CategoryLoc, diag::warn_dup_category_def)
926 << ClassName << CategoryName;
927 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +0000928 }
929 }
Chris Lattner9018ca82009-02-16 21:26:43 +0000930
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +0000931 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
932 ClassLoc, CategoryLoc, CategoryName, IDecl);
933 // FIXME: PushOnScopeChains?
934 CurContext->addDecl(CDecl);
935
Chris Lattnerda463fe2007-12-12 07:09:47 +0000936 if (NumProtoRefs) {
Roman Divackye6377112012-09-06 15:59:27 +0000937 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000938 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +0000939 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +0000940 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +0000941 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +0000942 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000943 }
Mike Stump11289f42009-09-09 15:08:12 +0000944
Anders Carlssona6b508a2008-11-04 16:57:32 +0000945 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +0000946 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000947}
948
949/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000950/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +0000951/// object.
John McCall48871652010-08-21 09:40:31 +0000952Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +0000953 SourceLocation AtCatImplLoc,
954 IdentifierInfo *ClassName, SourceLocation ClassLoc,
955 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000956 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +0000957 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +0000958 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000959 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
960 if (!CatIDecl) {
961 // Category @implementation with no corresponding @interface.
962 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +0000963 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
964 ClassLoc, CatLoc,
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +0000965 CatName, IDecl);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +0000966 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000967 }
968 }
969
Mike Stump11289f42009-09-09 15:08:12 +0000970 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +0000971 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +0000972 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000973 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +0000974 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000975 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +0000976 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +0000977 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
978 diag::err_undef_interface)) {
979 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +0000980 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000981
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000982 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000983 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000984
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +0000985 // If the interface is deprecated/unavailable, warn/error about it.
986 if (IDecl)
987 DiagnoseUseOfDecl(IDecl, ClassLoc);
988
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000989 /// Check that CatName, category name, is not used in another implementation.
990 if (CatIDecl) {
991 if (CatIDecl->getImplementation()) {
992 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
993 << CatName;
994 Diag(CatIDecl->getImplementation()->getLocation(),
995 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +0000996 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +0000997 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +0000998 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +0000999 // Warn on implementating category of deprecated class under
1000 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001001 DiagnoseObjCImplementedDeprecations(*this,
1002 dyn_cast<NamedDecl>(IDecl),
1003 CDecl->getLocation(), 2);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001004 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001005 }
Mike Stump11289f42009-09-09 15:08:12 +00001006
Anders Carlssona6b508a2008-11-04 16:57:32 +00001007 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001008 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001009}
1010
John McCall48871652010-08-21 09:40:31 +00001011Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001012 SourceLocation AtClassImplLoc,
1013 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001014 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001015 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001016 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001017 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001018 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001019 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1020 ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001021 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001022 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001023 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001024 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001025 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1026 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001027 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001028 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001029 // typos in the class name.
Kaelyn Uhraine31b8882012-01-13 01:32:50 +00001030 ObjCInterfaceValidatorCCC Validator;
Richard Smithf9b15102013-08-17 00:46:16 +00001031 TypoCorrection Corrected =
1032 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
Craig Topperc3ec1492014-05-26 06:22:03 +00001033 LookupOrdinaryName, TUScope, nullptr, Validator,
John Thompson2255f2c2014-04-23 12:57:01 +00001034 CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001035 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1036 // Suggest the (potentially) correct interface name. Don't provide a
1037 // code-modification hint or use the typo name for recovery, because
1038 // this is just a warning. The program may actually be correct.
1039 diagnoseTypo(Corrected,
1040 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1041 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001042 } else {
1043 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1044 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001045 }
Mike Stump11289f42009-09-09 15:08:12 +00001046
Chris Lattnerda463fe2007-12-12 07:09:47 +00001047 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001048 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001049 if (SuperClassname) {
1050 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001051 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1052 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001053 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001054 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1055 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001056 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001057 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001058 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001059 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001060 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001061 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001062 Diag(SuperClassLoc, diag::err_undef_superclass)
1063 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001064 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001065 // This implementation and its interface do not have the same
1066 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001067 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001068 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001069 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001070 }
1071 }
1072 }
Mike Stump11289f42009-09-09 15:08:12 +00001073
Chris Lattnerda463fe2007-12-12 07:09:47 +00001074 if (!IDecl) {
1075 // Legacy case of @implementation with no corresponding @interface.
1076 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001077
Mike Stump87c57ac2009-05-16 07:39:55 +00001078 // FIXME: Do we support attributes on the @implementation? If so we should
1079 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001080 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001081 ClassName, /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001082 true);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001083 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00001084 if (SDecl) {
1085 IDecl->setSuperClass(SDecl);
1086 IDecl->setSuperClassLoc(SuperClassLoc);
1087 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1088 } else {
1089 IDecl->setEndOfDefinitionLoc(ClassLoc);
1090 }
1091
Douglas Gregorac345a32009-04-24 00:16:12 +00001092 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00001093 } else {
1094 // Mark the interface as being completed, even if it was just as
1095 // @class ....;
1096 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001097 if (!IDecl->hasDefinition())
1098 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001099 }
Mike Stump11289f42009-09-09 15:08:12 +00001100
1101 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001102 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00001103 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001104
Anders Carlssona6b508a2008-11-04 16:57:32 +00001105 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001106 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001107
Chris Lattnerda463fe2007-12-12 07:09:47 +00001108 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00001109 if (IDecl->getImplementation()) {
1110 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001111 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001112 Diag(IDecl->getImplementation()->getLocation(),
1113 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001114 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00001115 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001116 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00001117 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001118 // Warn on implementating deprecated class under
1119 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001120 DiagnoseObjCImplementedDeprecations(*this,
1121 dyn_cast<NamedDecl>(IDecl),
1122 IMPDecl->getLocation(), 1);
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001123 }
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001124 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001125}
1126
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001127Sema::DeclGroupPtrTy
1128Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1129 SmallVector<Decl *, 64> DeclsInGroup;
1130 DeclsInGroup.reserve(Decls.size() + 1);
1131
1132 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1133 Decl *Dcl = Decls[i];
1134 if (!Dcl)
1135 continue;
1136 if (Dcl->getDeclContext()->isFileContext())
1137 Dcl->setTopLevelDeclInObjCContainer();
1138 DeclsInGroup.push_back(Dcl);
1139 }
1140
1141 DeclsInGroup.push_back(ObjCImpDecl);
1142
Rafael Espindolaab417692013-07-09 12:05:01 +00001143 return BuildDeclaratorGroup(DeclsInGroup, false);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001144}
1145
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001146void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1147 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001148 SourceLocation RBrace) {
1149 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001150 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001151 if (!IDecl)
1152 return;
James Dennett634962f2012-06-14 21:40:34 +00001153 /// Check case of non-existing \@interface decl.
1154 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00001155 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00001156 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00001157 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00001158 // Add ivar's to class's DeclContext.
1159 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00001160 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00001161 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001162 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00001163 }
1164
Chris Lattnerda463fe2007-12-12 07:09:47 +00001165 return;
1166 }
1167 // If implementation has empty ivar list, just return.
1168 if (numIvars == 0)
1169 return;
Mike Stump11289f42009-09-09 15:08:12 +00001170
Chris Lattnerda463fe2007-12-12 07:09:47 +00001171 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00001172 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00001173 if (ImpDecl->getSuperClass())
1174 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1175 for (unsigned i = 0; i < numIvars; i++) {
1176 ObjCIvarDecl* ImplIvar = ivars[i];
1177 if (const ObjCIvarDecl *ClsIvar =
1178 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1179 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1180 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1181 continue;
1182 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00001183 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00001184 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00001185 if (const ObjCIvarDecl *ClsExtIvar =
1186 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1187 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1188 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1189 continue;
1190 }
1191 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00001192 // Instance ivar to Implementation's DeclContext.
1193 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00001194 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00001195 ImpDecl->addDecl(ImplIvar);
1196 }
1197 return;
1198 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001199 // Check interface's Ivar list against those in the implementation.
1200 // names and types must match.
1201 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00001202 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001203 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00001204 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1205 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001206 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00001207 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001208 assert (ImplIvar && "missing implementation ivar");
1209 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00001210
Steve Naroff157599f2009-03-03 14:49:36 +00001211 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00001212 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00001213 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001214 << ImplIvar->getIdentifier()
1215 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00001216 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00001217 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1218 ImplIvar->getBitWidthValue(Context) !=
1219 ClsIvar->getBitWidthValue(Context)) {
1220 Diag(ImplIvar->getBitWidth()->getLocStart(),
1221 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1222 Diag(ClsIvar->getBitWidth()->getLocStart(),
1223 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001224 }
Steve Naroff157599f2009-03-03 14:49:36 +00001225 // Make sure the names are identical.
1226 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00001227 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001228 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00001229 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001230 }
1231 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001232 }
Mike Stump11289f42009-09-09 15:08:12 +00001233
Chris Lattner0f29d982007-12-12 18:11:49 +00001234 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00001235 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00001236 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00001237 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001238}
1239
Ted Kremenekf87decd2013-12-13 05:58:44 +00001240static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1241 ObjCMethodDecl *method,
1242 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00001243 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00001244 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00001245 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00001246 switch (method->getAvailability()) {
1247 case AR_Available:
1248 case AR_Deprecated:
1249 break;
1250
1251 // Don't warn about unavailable or not-yet-introduced methods.
1252 case AR_NotYetIntroduced:
1253 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00001254 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00001255 }
1256
Ted Kremenek65d63572013-03-27 00:02:21 +00001257 // FIXME: For now ignore 'IncompleteImpl'.
1258 // Previously we grouped all unimplemented methods under a single
1259 // warning, but some users strongly voiced that they would prefer
1260 // separate warnings. We will give that approach a try, as that
1261 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00001262 {
1263 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1264 B << method;
1265 if (NeededFor)
1266 B << NeededFor;
1267 }
Ted Kremenek65d63572013-03-27 00:02:21 +00001268
1269 // Issue a note to the original declaration.
1270 SourceLocation MethodLoc = method->getLocStart();
1271 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00001272 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00001273}
1274
David Chisnallb62d15c2010-10-25 17:23:52 +00001275/// Determines if type B can be substituted for type A. Returns true if we can
1276/// guarantee that anything that the user will do to an object of type A can
1277/// also be done to an object of type B. This is trivially true if the two
1278/// types are the same, or if B is a subclass of A. It becomes more complex
1279/// in cases where protocols are involved.
1280///
1281/// Object types in Objective-C describe the minimum requirements for an
1282/// object, rather than providing a complete description of a type. For
1283/// example, if A is a subclass of B, then B* may refer to an instance of A.
1284/// The principle of substitutability means that we may use an instance of A
1285/// anywhere that we may use an instance of B - it will implement all of the
1286/// ivars of B and all of the methods of B.
1287///
1288/// This substitutability is important when type checking methods, because
1289/// the implementation may have stricter type definitions than the interface.
1290/// The interface specifies minimum requirements, but the implementation may
1291/// have more accurate ones. For example, a method may privately accept
1292/// instances of B, but only publish that it accepts instances of A. Any
1293/// object passed to it will be type checked against B, and so will implicitly
1294/// by a valid A*. Similarly, a method may return a subclass of the class that
1295/// it is declared as returning.
1296///
1297/// This is most important when considering subclassing. A method in a
1298/// subclass must accept any object as an argument that its superclass's
1299/// implementation accepts. It may, however, accept a more general type
1300/// without breaking substitutability (i.e. you can still use the subclass
1301/// anywhere that you can use the superclass, but not vice versa). The
1302/// converse requirement applies to return types: the return type for a
1303/// subclass method must be a valid object of the kind that the superclass
1304/// advertises, but it may be specified more accurately. This avoids the need
1305/// for explicit down-casting by callers.
1306///
1307/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00001308static bool isObjCTypeSubstitutable(ASTContext &Context,
1309 const ObjCObjectPointerType *A,
1310 const ObjCObjectPointerType *B,
1311 bool rejectId) {
1312 // Reject a protocol-unqualified id.
1313 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00001314
1315 // If B is a qualified id, then A must also be a qualified id and it must
1316 // implement all of the protocols in B. It may not be a qualified class.
1317 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1318 // stricter definition so it is not substitutable for id<A>.
1319 if (B->isObjCQualifiedIdType()) {
1320 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00001321 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1322 QualType(B,0),
1323 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00001324 }
1325
1326 /*
1327 // id is a special type that bypasses type checking completely. We want a
1328 // warning when it is used in one place but not another.
1329 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1330
1331
1332 // If B is a qualified id, then A must also be a qualified id (which it isn't
1333 // if we've got this far)
1334 if (B->isObjCQualifiedIdType()) return false;
1335 */
1336
1337 // Now we know that A and B are (potentially-qualified) class types. The
1338 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00001339 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00001340}
1341
John McCall071df462010-10-28 02:34:38 +00001342static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1343 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1344}
1345
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001346static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00001347 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001348 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00001349 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001350 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001351 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001352 if (IsProtocolMethodDecl &&
1353 (MethodDecl->getObjCDeclQualifier() !=
1354 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001355 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00001356 S.Diag(MethodImpl->getLocation(),
1357 (IsOverridingMode
1358 ? diag::warn_conflicting_overriding_ret_type_modifiers
1359 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001360 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001361 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00001362 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001363 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001364 }
1365 else
1366 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001367 }
Alp Toker314cc812014-01-25 16:55:45 +00001368
1369 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1370 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001371 return true;
1372 if (!Warn)
1373 return false;
John McCall071df462010-10-28 02:34:38 +00001374
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001375 unsigned DiagID =
1376 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1377 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00001378
1379 // Mismatches between ObjC pointers go into a different warning
1380 // category, and sometimes they're even completely whitelisted.
1381 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00001382 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00001383 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00001384 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00001385 // Allow non-matching return types as long as they don't violate
1386 // the principle of substitutability. Specifically, we permit
1387 // return types that are subclasses of the declared return type,
1388 // or that are more-qualified versions of the declared type.
1389 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001390 return false;
John McCall071df462010-10-28 02:34:38 +00001391
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001392 DiagID =
1393 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1394 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00001395 }
1396 }
1397
1398 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00001399 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1400 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001401 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00001402 S.Diag(MethodDecl->getLocation(), IsOverridingMode
1403 ? diag::note_previous_declaration
1404 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00001405 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001406 return false;
John McCall071df462010-10-28 02:34:38 +00001407}
1408
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001409static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00001410 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001411 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00001412 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001413 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00001414 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001415 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001416 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001417 if (IsProtocolMethodDecl &&
1418 (ImplVar->getObjCDeclQualifier() !=
1419 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001420 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001421 if (IsOverridingMode)
1422 S.Diag(ImplVar->getLocation(),
1423 diag::warn_conflicting_overriding_param_modifiers)
1424 << getTypeRange(ImplVar->getTypeSourceInfo())
1425 << MethodImpl->getDeclName();
1426 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001427 diag::warn_conflicting_param_modifiers)
1428 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001429 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001430 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1431 << getTypeRange(IfaceVar->getTypeSourceInfo());
1432 }
1433 else
1434 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001435 }
1436
John McCall071df462010-10-28 02:34:38 +00001437 QualType ImplTy = ImplVar->getType();
1438 QualType IfaceTy = IfaceVar->getType();
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001439
John McCall071df462010-10-28 02:34:38 +00001440 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001441 return true;
1442
1443 if (!Warn)
1444 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001445 unsigned DiagID =
1446 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1447 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00001448
1449 // Mismatches between ObjC pointers go into a different warning
1450 // category, and sometimes they're even completely whitelisted.
1451 if (const ObjCObjectPointerType *ImplPtrTy =
1452 ImplTy->getAs<ObjCObjectPointerType>()) {
1453 if (const ObjCObjectPointerType *IfacePtrTy =
1454 IfaceTy->getAs<ObjCObjectPointerType>()) {
1455 // Allow non-matching argument types as long as they don't
1456 // violate the principle of substitutability. Specifically, the
1457 // implementation must accept any objects that the superclass
1458 // accepts, however it may also accept others.
1459 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001460 return false;
John McCall071df462010-10-28 02:34:38 +00001461
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001462 DiagID =
1463 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1464 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00001465 }
1466 }
1467
1468 S.Diag(ImplVar->getLocation(), DiagID)
1469 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001470 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1471 S.Diag(IfaceVar->getLocation(),
1472 (IsOverridingMode ? diag::note_previous_declaration
1473 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00001474 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001475 return false;
John McCall071df462010-10-28 02:34:38 +00001476}
John McCall31168b02011-06-15 23:02:42 +00001477
1478/// In ARC, check whether the conventional meanings of the two methods
1479/// match. If they don't, it's a hard error.
1480static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1481 ObjCMethodDecl *decl) {
1482 ObjCMethodFamily implFamily = impl->getMethodFamily();
1483 ObjCMethodFamily declFamily = decl->getMethodFamily();
1484 if (implFamily == declFamily) return false;
1485
1486 // Since conventions are sorted by selector, the only possibility is
1487 // that the types differ enough to cause one selector or the other
1488 // to fall out of the family.
1489 assert(implFamily == OMF_None || declFamily == OMF_None);
1490
1491 // No further diagnostics required on invalid declarations.
1492 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1493
1494 const ObjCMethodDecl *unmatched = impl;
1495 ObjCMethodFamily family = declFamily;
1496 unsigned errorID = diag::err_arc_lost_method_convention;
1497 unsigned noteID = diag::note_arc_lost_method_convention;
1498 if (declFamily == OMF_None) {
1499 unmatched = decl;
1500 family = implFamily;
1501 errorID = diag::err_arc_gained_method_convention;
1502 noteID = diag::note_arc_gained_method_convention;
1503 }
1504
1505 // Indexes into a %select clause in the diagnostic.
1506 enum FamilySelector {
1507 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1508 };
1509 FamilySelector familySelector = FamilySelector();
1510
1511 switch (family) {
1512 case OMF_None: llvm_unreachable("logic error, no method convention");
1513 case OMF_retain:
1514 case OMF_release:
1515 case OMF_autorelease:
1516 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00001517 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00001518 case OMF_retainCount:
1519 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00001520 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00001521 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00001522 // Mismatches for these methods don't change ownership
1523 // conventions, so we don't care.
1524 return false;
1525
1526 case OMF_init: familySelector = F_init; break;
1527 case OMF_alloc: familySelector = F_alloc; break;
1528 case OMF_copy: familySelector = F_copy; break;
1529 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1530 case OMF_new: familySelector = F_new; break;
1531 }
1532
1533 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1534 ReasonSelector reasonSelector;
1535
1536 // The only reason these methods don't fall within their families is
1537 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00001538 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00001539 reasonSelector = R_UnrelatedReturn;
1540 } else {
1541 reasonSelector = R_NonObjectReturn;
1542 }
1543
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00001544 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1545 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00001546
1547 return true;
1548}
John McCall071df462010-10-28 02:34:38 +00001549
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00001550void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001551 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00001552 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001553 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00001554 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1555 return;
1556
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00001557 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00001558 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001559 true);
Mike Stump11289f42009-09-09 15:08:12 +00001560
Chris Lattner67f35b02009-04-11 19:58:42 +00001561 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00001562 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1563 EF = MethodDecl->param_end();
1564 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001565 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00001566 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00001567 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00001568
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00001569 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00001570 Diag(ImpMethodDecl->getLocation(),
1571 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00001572 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00001573 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00001574}
1575
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00001576void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1577 ObjCMethodDecl *Overridden,
1578 bool IsProtocolMethodDecl) {
1579
1580 CheckMethodOverrideReturn(*this, Method, Overridden,
1581 IsProtocolMethodDecl, true,
1582 true);
1583
1584 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00001585 IF = Overridden->param_begin(), EM = Method->param_end(),
1586 EF = Overridden->param_end();
1587 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00001588 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1589 IsProtocolMethodDecl, true, true);
1590 }
1591
1592 if (Method->isVariadic() != Overridden->isVariadic()) {
1593 Diag(Method->getLocation(),
1594 diag::warn_conflicting_overriding_variadic);
1595 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1596 }
1597}
1598
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001599/// WarnExactTypedMethods - This routine issues a warning if method
1600/// implementation declaration matches exactly that of its declaration.
1601void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1602 ObjCMethodDecl *MethodDecl,
1603 bool IsProtocolMethodDecl) {
1604 // don't issue warning when protocol method is optional because primary
1605 // class is not required to implement it and it is safe for protocol
1606 // to implement it.
1607 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1608 return;
1609 // don't issue warning when primary class's method is
1610 // depecated/unavailable.
1611 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1612 MethodDecl->hasAttr<DeprecatedAttr>())
1613 return;
1614
1615 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1616 IsProtocolMethodDecl, false, false);
1617 if (match)
1618 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00001619 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1620 EF = MethodDecl->param_end();
1621 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001622 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1623 *IM, *IF,
1624 IsProtocolMethodDecl, false, false);
1625 if (!match)
1626 break;
1627 }
1628 if (match)
1629 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00001630 if (match)
1631 match = !(MethodDecl->isClassMethod() &&
1632 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001633
1634 if (match) {
1635 Diag(ImpMethodDecl->getLocation(),
1636 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00001637 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1638 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001639 }
1640}
1641
Mike Stump87c57ac2009-05-16 07:39:55 +00001642/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1643/// improve the efficiency of selector lookups and type checking by associating
1644/// with each protocol / interface / category the flattened instance tables. If
1645/// we used an immutable set to keep the table then it wouldn't add significant
1646/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00001647
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001648typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00001649typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00001650
1651static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1652 ProtocolNameSet &PNS) {
1653 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1654 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001655 for (const auto *PI : PDecl->protocols())
1656 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00001657}
1658
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001659/// Recursively populates a set with all conformed protocols in a class
1660/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1661/// attribute.
1662static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1663 ProtocolNameSet &PNS) {
1664 if (!Super)
1665 return;
1666
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001667 for (const auto *I : Super->all_referenced_protocols())
1668 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00001669
1670 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001671}
1672
Steve Naroffa36992242008-02-08 22:06:17 +00001673/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00001674/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00001675static void CheckProtocolMethodDefs(Sema &S,
1676 SourceLocation ImpLoc,
1677 ObjCProtocolDecl *PDecl,
1678 bool& IncompleteImpl,
1679 const Sema::SelectorSet &InsMap,
1680 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00001681 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001682 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001683 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1684 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1685 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00001686 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1687
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001688 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00001689 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001690
1691 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1692 // then we should check if any class in the super class hierarchy also
1693 // conforms to this protocol, either directly or via protocol inheritance.
1694 // If so, we can skip checking this protocol completely because we
1695 // know that a parent class already satisfies this protocol.
1696 //
1697 // Note: we could generalize this logic for all protocols, and merely
1698 // add the limit on looking at the super class chain for just
1699 // specially marked protocols. This may be a good optimization. This
1700 // change is restricted to 'objc_protocol_requires_explicit_implementation'
1701 // protocols for now for controlled evaluation.
1702 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00001703 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001704 ProtocolsExplictImpl.reset(new ProtocolNameSet);
1705 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1706 }
1707 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1708 ProtocolsExplictImpl->end())
1709 return;
1710
1711 // If no super class conforms to the protocol, we should not search
1712 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00001713 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001714 }
1715
Ted Kremenek285ee852013-12-13 06:26:10 +00001716 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00001717 // check to see if class implements forwardInvocation method and objects
1718 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00001719 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00001720 // Under such conditions, which means that every method possible is
1721 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00001722 // found" warnings.
1723 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00001724 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1725 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00001726 if (InsMap.count(fISelector))
1727 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1728 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00001729 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00001730 }
Mike Stump11289f42009-09-09 15:08:12 +00001731
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00001732 // If this is a forward protocol declaration, get its definition.
1733 if (!PDecl->isThisDeclarationADefinition() &&
1734 PDecl->getDefinition())
1735 PDecl = PDecl->getDefinition();
1736
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001737 // If a method lookup fails locally we still need to look and see if
1738 // the method was implemented by a base class or an inherited
1739 // protocol. This lookup is slow, but occurs rarely in correct code
1740 // and otherwise would terminate in a warning.
1741
Chris Lattnerda463fe2007-12-12 07:09:47 +00001742 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00001743 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001744 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00001745 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00001746 !method->isPropertyAccessor() &&
1747 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00001748 (!Super || !Super->lookupMethod(method->getSelector(),
1749 true /* instance */,
1750 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00001751 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00001752 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001753 // If a method is not implemented in the category implementation but
1754 // has been declared in its primary class, superclass,
1755 // or in one of their protocols, no need to issue the warning.
1756 // This is because method will be implemented in the primary class
1757 // or one of its super class implementation.
1758
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00001759 // Ugly, but necessary. Method declared in protcol might have
1760 // have been synthesized due to a property declared in the class which
1761 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001762 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00001763 IDecl->lookupMethod(method->getSelector(),
1764 true /* instance */,
1765 true /* shallowCategoryLookup */,
1766 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00001767 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001768 continue;
1769 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001770 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00001771 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00001772 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00001773 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00001774 }
1775 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001776 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001777 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001778 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1779 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00001780 (!Super || !Super->lookupMethod(method->getSelector(),
1781 false /* class method */,
1782 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00001783 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00001784 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001785 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00001786 if (C && IDecl->lookupMethod(method->getSelector(),
1787 false /* class */,
1788 true /* shallowCategoryLookup */,
1789 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001790 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00001791
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00001792 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001793 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00001794 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00001795 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00001796 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00001797 }
Chris Lattner390d39a2008-07-21 21:32:27 +00001798 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001799 for (auto *PI : PDecl->protocols())
1800 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001801 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001802}
1803
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00001804/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001805/// or protocol against those declared in their implementations.
1806///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00001807void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1808 const SelectorSet &ClsMap,
1809 SelectorSet &InsMapSeen,
1810 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001811 ObjCImplDecl* IMPDecl,
1812 ObjCContainerDecl* CDecl,
1813 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001814 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001815 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001816 // Check and see if instance methods in class interface have been
1817 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001818 for (auto *I : CDecl->instance_methods()) {
1819 if (!InsMapSeen.insert(I->getSelector()))
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00001820 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001821 if (!I->isPropertyAccessor() &&
1822 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001823 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001824 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00001825 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001826 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00001827 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001828 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001829 IMPDecl->getInstanceMethod(I->getSelector());
1830 assert(CDecl->getInstanceMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00001831 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001832 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001833 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001834 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001835 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001836 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001837 else if (!I->isPropertyAccessor())
1838 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001839 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001840 }
1841 }
Mike Stump11289f42009-09-09 15:08:12 +00001842
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001843 // Check and see if class methods in class interface have been
1844 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001845 for (auto *I : CDecl->class_methods()) {
1846 if (!ClsMapSeen.insert(I->getSelector()))
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00001847 continue;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001848 if (!ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001849 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001850 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00001851 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00001852 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001853 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001854 IMPDecl->getClassMethod(I->getSelector());
1855 assert(CDecl->getClassMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00001856 "Expected to find the method through lookup as well");
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001857 if (!WarnCategoryMethodImpl)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001858 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001859 isa<ObjCProtocolDecl>(CDecl));
1860 else
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001861 WarnExactTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001862 isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001863 }
1864 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00001865
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00001866 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1867 // Also, check for methods declared in protocols inherited by
1868 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001869 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00001870 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001871 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00001872 WarnCategoryMethodImpl);
1873 }
1874
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001875 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00001876 // when checking that methods in implementation match their declaration,
1877 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1878 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001879 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00001880 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00001881 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman3fe486a2014-03-13 21:23:55 +00001882 IMPDecl, Cat, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00001883 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001884 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00001885 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00001886 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00001887 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00001888 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00001889 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001890 }
1891
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001892 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001893 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00001894 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001895 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001896 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001897
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001898 // FIXME. For now, we are not checking for extact match of methods
1899 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001900 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001901 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00001902 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001903 I->getSuperClass(), IncompleteImpl, false);
1904 }
1905}
1906
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001907/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1908/// category matches with those implemented in its primary class and
1909/// warns each time an exact match is found.
1910void Sema::CheckCategoryVsClassMethodMatches(
1911 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001912 // Get category's primary class.
1913 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1914 if (!CatDecl)
1915 return;
1916 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1917 if (!IDecl)
1918 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00001919 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1920 SelectorSet InsMap, ClsMap;
1921
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001922 for (const auto *I : CatIMPDecl->instance_methods()) {
1923 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00001924 // When checking for methods implemented in the category, skip over
1925 // those declared in category class's super class. This is because
1926 // the super class must implement the method.
1927 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1928 continue;
1929 InsMap.insert(Sel);
1930 }
1931
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001932 for (const auto *I : CatIMPDecl->class_methods()) {
1933 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00001934 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1935 continue;
1936 ClsMap.insert(Sel);
1937 }
1938 if (InsMap.empty() && ClsMap.empty())
1939 return;
1940
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00001941 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001942 bool IncompleteImpl = false;
1943 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1944 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00001945 IncompleteImpl, false,
1946 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001947}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00001948
Fariborz Jahanian25491a22010-05-05 21:52:17 +00001949void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00001950 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00001951 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00001952 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001953 // Check and see if instance methods in class interface have been
1954 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001955 for (const auto *I : IMPDecl->instance_methods())
1956 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00001957
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00001958 // Check and see if properties declared in the interface have either 1)
1959 // an implementation or 2) there is a @synthesize/@dynamic implementation
1960 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00001961 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1962 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1963 LangOpts.ObjCRuntime.isNonFragile() &&
1964 !IDecl->isObjCRequiresPropertyDefs();
1965 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1966 }
1967
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00001968 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001969 for (const auto *I : IMPDecl->class_methods())
1970 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00001971
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001972 // Check for type conflict of methods declared in a class/protocol and
1973 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00001974 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00001975 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1976 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001977 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00001978
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00001979 // check all methods implemented in category against those declared
1980 // in its primary class.
1981 if (ObjCCategoryImplDecl *CatDecl =
1982 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1983 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001984
Chris Lattnerda463fe2007-12-12 07:09:47 +00001985 // Check the protocol list for unimplemented methods in the @implementation
1986 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00001987 // Check and see if class methods in class interface have been
1988 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00001989
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00001990 LazyProtocolNameSet ExplicitImplProtocols;
1991
Chris Lattner9ef10f42009-03-01 00:56:52 +00001992 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00001993 for (auto *PI : I->all_referenced_protocols())
1994 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
1995 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00001996 // Check class extensions (unnamed categories)
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00001997 for (auto *Ext : I->visible_extensions())
1998 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
Chris Lattner9ef10f42009-03-01 00:56:52 +00001999 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002000 // For extended class, unimplemented methods in its protocols will
2001 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002002 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002003 for (auto *P : C->protocols())
2004 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002005 IncompleteImpl, InsMap, ClsMap, CDecl,
2006 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002007 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2008 /* SynthesizeProperties */ false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002009 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002010 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002011 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002012}
2013
Mike Stump11289f42009-09-09 15:08:12 +00002014/// ActOnForwardClassDeclaration -
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002015Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00002016Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00002017 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00002018 SourceLocation *IdentLocs,
Chris Lattner99a83312009-02-16 19:25:52 +00002019 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002020 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002021 for (unsigned i = 0; i != NumElts; ++i) {
2022 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002023 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002024 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Douglas Gregorb8eaf292010-04-15 23:40:53 +00002025 LookupOrdinaryName, ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002026 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00002027 // GCC apparently allows the following idiom:
2028 //
2029 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2030 // @class XCElementToggler;
2031 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002032 // Here we have chosen to ignore the forward class declaration
2033 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00002034 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00002035 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002036 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00002037 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00002038 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00002039 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002040 // to the underlying class. Just ignore the forward class with a warning
2041 // as this will force the intended behavior which is to lookup the typedef
2042 // name.
2043 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2044 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
2045 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2046 continue;
2047 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00002048 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002049 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00002050
2051 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002052 ObjCInterfaceDecl *PrevIDecl
2053 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00002054
2055 IdentifierInfo *ClassName = IdentList[i];
2056 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2057 // A previous decl with a different name is because of
2058 // @compatibility_alias, for example:
2059 // \code
2060 // @class NewImage;
2061 // @compatibility_alias OldImage NewImage;
2062 // \endcode
2063 // A lookup for 'OldImage' will return the 'NewImage' decl.
2064 //
2065 // In such a case use the real declaration name, instead of the alias one,
2066 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2067 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2068 // has been aliased.
2069 ClassName = PrevIDecl->getIdentifier();
2070 }
2071
Douglas Gregordc9166c2011-12-15 20:29:51 +00002072 ObjCInterfaceDecl *IDecl
2073 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00002074 ClassName, PrevIDecl, IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00002075 IDecl->setAtEndRange(IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00002076
Douglas Gregordc9166c2011-12-15 20:29:51 +00002077 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00002078 CheckObjCDeclScope(IDecl);
2079 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002080 }
Rafael Espindolaab417692013-07-09 12:05:01 +00002081
2082 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002083}
2084
John McCall54507ab2011-06-16 01:15:19 +00002085static bool tryMatchRecordTypes(ASTContext &Context,
2086 Sema::MethodMatchStrategy strategy,
2087 const Type *left, const Type *right);
2088
John McCall31168b02011-06-15 23:02:42 +00002089static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2090 QualType leftQT, QualType rightQT) {
2091 const Type *left =
2092 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2093 const Type *right =
2094 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2095
2096 if (left == right) return true;
2097
2098 // If we're doing a strict match, the types have to match exactly.
2099 if (strategy == Sema::MMS_strict) return false;
2100
2101 if (left->isIncompleteType() || right->isIncompleteType()) return false;
2102
2103 // Otherwise, use this absurdly complicated algorithm to try to
2104 // validate the basic, low-level compatibility of the two types.
2105
2106 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00002107 TypeInfo LeftTI = Context.getTypeInfo(left);
2108 TypeInfo RightTI = Context.getTypeInfo(right);
2109 if (LeftTI.Width != RightTI.Width)
2110 return false;
2111
2112 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00002113 return false;
2114
2115 // Consider all the kinds of non-dependent canonical types:
2116 // - functions and arrays aren't possible as return and parameter types
2117
2118 // - vector types of equal size can be arbitrarily mixed
2119 if (isa<VectorType>(left)) return isa<VectorType>(right);
2120 if (isa<VectorType>(right)) return false;
2121
2122 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00002123 // - structs, unions, and Objective-C objects must match more-or-less
2124 // exactly
John McCall31168b02011-06-15 23:02:42 +00002125 // - everything else should be a scalar
2126 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00002127 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00002128
John McCall9320b872011-09-09 05:25:32 +00002129 // Make scalars agree in kind, except count bools as chars, and group
2130 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00002131 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2132 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2133 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2134 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00002135 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2136 leftSK = Type::STK_ObjCObjectPointer;
2137 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2138 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00002139
2140 // Note that data member pointers and function member pointers don't
2141 // intermix because of the size differences.
2142
2143 return (leftSK == rightSK);
2144}
Chris Lattnerda463fe2007-12-12 07:09:47 +00002145
John McCall54507ab2011-06-16 01:15:19 +00002146static bool tryMatchRecordTypes(ASTContext &Context,
2147 Sema::MethodMatchStrategy strategy,
2148 const Type *lt, const Type *rt) {
2149 assert(lt && rt && lt != rt);
2150
2151 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2152 RecordDecl *left = cast<RecordType>(lt)->getDecl();
2153 RecordDecl *right = cast<RecordType>(rt)->getDecl();
2154
2155 // Require union-hood to match.
2156 if (left->isUnion() != right->isUnion()) return false;
2157
2158 // Require an exact match if either is non-POD.
2159 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2160 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2161 return false;
2162
2163 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00002164 TypeInfo LeftTI = Context.getTypeInfo(lt);
2165 TypeInfo RightTI = Context.getTypeInfo(rt);
2166 if (LeftTI.Width != RightTI.Width)
2167 return false;
2168
2169 if (LeftTI.Align != RightTI.Align)
2170 return false;
John McCall54507ab2011-06-16 01:15:19 +00002171
2172 // Require fields to match.
2173 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2174 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2175 for (; li != le && ri != re; ++li, ++ri) {
2176 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2177 return false;
2178 }
2179 return (li == le && ri == re);
2180}
2181
Chris Lattnerda463fe2007-12-12 07:09:47 +00002182/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2183/// returns true, or false, accordingly.
2184/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00002185bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2186 const ObjCMethodDecl *right,
2187 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00002188 if (!matchTypes(Context, strategy, left->getReturnType(),
2189 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00002190 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002191
Douglas Gregor560b7fa2013-02-07 19:13:24 +00002192 // If either is hidden, it is not considered to match.
2193 if (left->isHidden() || right->isHidden())
2194 return false;
2195
David Blaikiebbafb8a2012-03-11 07:00:24 +00002196 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002197 (left->hasAttr<NSReturnsRetainedAttr>()
2198 != right->hasAttr<NSReturnsRetainedAttr>() ||
2199 left->hasAttr<NSConsumesSelfAttr>()
2200 != right->hasAttr<NSConsumesSelfAttr>()))
2201 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002202
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002203 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002204 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2205 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00002206
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002207 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00002208 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00002209 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00002210
2211 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2212 return false;
2213
David Blaikiebbafb8a2012-03-11 07:00:24 +00002214 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002215 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2216 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002217 }
2218 return true;
2219}
2220
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002221void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002222 // Record at the head of the list whether there were 0, 1, or >= 2 methods
2223 // inside categories.
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00002224 if (ObjCCategoryDecl *
2225 CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2226 if (!CD->IsClassExtension() && List->getBits() < 2)
2227 List->setBits(List->getBits()+1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002228
Douglas Gregorc454afe2012-01-25 00:19:56 +00002229 // If the list is empty, make it a singleton list.
Craig Topperc3ec1492014-05-26 06:22:03 +00002230 if (List->Method == nullptr) {
Douglas Gregorc454afe2012-01-25 00:19:56 +00002231 List->Method = Method;
Craig Topperc3ec1492014-05-26 06:22:03 +00002232 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002233 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00002234 }
2235
2236 // We've seen a method with this name, see if we have already seen this type
2237 // signature.
2238 ObjCMethodList *Previous = List;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002239 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00002240 // If we are building a module, keep all of the methods.
2241 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2242 continue;
2243
Douglas Gregore1716012012-01-25 00:49:42 +00002244 if (!MatchTwoMethodDeclarations(Method, List->Method))
Douglas Gregorc454afe2012-01-25 00:19:56 +00002245 continue;
2246
2247 ObjCMethodDecl *PrevObjCMethod = List->Method;
2248
2249 // Propagate the 'defined' bit.
2250 if (Method->isDefined())
2251 PrevObjCMethod->setDefined(true);
2252
2253 // If a method is deprecated, push it in the global pool.
2254 // This is used for better diagnostics.
2255 if (Method->isDeprecated()) {
2256 if (!PrevObjCMethod->isDeprecated())
2257 List->Method = Method;
2258 }
2259 // If new method is unavailable, push it into global pool
2260 // unless previous one is deprecated.
2261 if (Method->isUnavailable()) {
2262 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2263 List->Method = Method;
2264 }
2265
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002266 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00002267 }
2268
2269 // We have a new signature for an existing method - add it.
2270 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00002271 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Craig Topperc3ec1492014-05-26 06:22:03 +00002272 Previous->setNext(new (Mem) ObjCMethodList(Method, nullptr));
Douglas Gregorc454afe2012-01-25 00:19:56 +00002273}
2274
Sebastian Redl75d8a322010-08-02 23:18:59 +00002275/// \brief Read the contents of the method pool for a given selector from
2276/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00002277void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00002278 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00002279 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00002280}
2281
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002282void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00002283 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00002284 // Ignore methods of invalid containers.
2285 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002286 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00002287
Douglas Gregor70f449b2012-01-25 00:59:09 +00002288 if (ExternalSource)
2289 ReadMethodPool(Method->getSelector());
2290
Sebastian Redl75d8a322010-08-02 23:18:59 +00002291 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00002292 if (Pos == MethodPool.end())
2293 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2294 GlobalMethods())).first;
Douglas Gregorc454afe2012-01-25 00:19:56 +00002295
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00002296 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00002297
Sebastian Redl75d8a322010-08-02 23:18:59 +00002298 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002299 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002300}
2301
John McCall31168b02011-06-15 23:02:42 +00002302/// Determines if this is an "acceptable" loose mismatch in the global
2303/// method pool. This exists mostly as a hack to get around certain
2304/// global mismatches which we can't afford to make warnings / errors.
2305/// Really, what we want is a way to take a method out of the global
2306/// method pool.
2307static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2308 ObjCMethodDecl *other) {
2309 if (!chosen->isInstanceMethod())
2310 return false;
2311
2312 Selector sel = chosen->getSelector();
2313 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2314 return false;
2315
2316 // Don't complain about mismatches for -length if the method we
2317 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00002318 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00002319}
2320
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00002321bool Sema::CollectMultipleMethodsInGlobalPool(Selector Sel,
2322 SmallVectorImpl<ObjCMethodDecl*>& Methods,
2323 bool instance) {
2324 if (ExternalSource)
2325 ReadMethodPool(Sel);
2326
2327 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2328 if (Pos == MethodPool.end())
2329 return false;
2330 // Gather the non-hidden methods.
2331 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2332 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
2333 if (M->Method && !M->Method->isHidden())
2334 Methods.push_back(M->Method);
2335 return (Methods.size() > 1);
2336}
2337
Sebastian Redl75d8a322010-08-02 23:18:59 +00002338ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00002339 bool receiverIdOrClass,
Sebastian Redl75d8a322010-08-02 23:18:59 +00002340 bool warn, bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00002341 if (ExternalSource)
2342 ReadMethodPool(Sel);
2343
Sebastian Redl75d8a322010-08-02 23:18:59 +00002344 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00002345 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00002346 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00002347
Douglas Gregor77f49a42013-01-16 18:47:38 +00002348 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00002349 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00002350 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00002351 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00002352 if (M->Method && !M->Method->isHidden()) {
2353 // If we're not supposed to warn about mismatches, we're done.
2354 if (!warn)
2355 return M->Method;
Mike Stump11289f42009-09-09 15:08:12 +00002356
Douglas Gregor77f49a42013-01-16 18:47:38 +00002357 Methods.push_back(M->Method);
Sebastian Redl75d8a322010-08-02 23:18:59 +00002358 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00002359 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00002360
2361 // If there aren't any visible methods, we're done.
2362 // FIXME: Recover if there are any known-but-hidden methods?
2363 if (Methods.empty())
Craig Topperc3ec1492014-05-26 06:22:03 +00002364 return nullptr;
Douglas Gregor77f49a42013-01-16 18:47:38 +00002365
2366 if (Methods.size() == 1)
2367 return Methods[0];
2368
2369 // We found multiple methods, so we may have to complain.
2370 bool issueDiagnostic = false, issueError = false;
2371
2372 // We support a warning which complains about *any* difference in
2373 // method signature.
2374 bool strictSelectorMatch =
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002375 receiverIdOrClass && warn &&
2376 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00002377 if (strictSelectorMatch) {
2378 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2379 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2380 issueDiagnostic = true;
2381 break;
2382 }
2383 }
2384 }
2385
2386 // If we didn't see any strict differences, we won't see any loose
2387 // differences. In ARC, however, we also need to check for loose
2388 // mismatches, because most of them are errors.
2389 if (!strictSelectorMatch ||
2390 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2391 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2392 // This checks if the methods differ in type mismatch.
2393 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2394 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2395 issueDiagnostic = true;
2396 if (getLangOpts().ObjCAutoRefCount)
2397 issueError = true;
2398 break;
2399 }
2400 }
2401
2402 if (issueDiagnostic) {
2403 if (issueError)
2404 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2405 else if (strictSelectorMatch)
2406 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2407 else
2408 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2409
2410 Diag(Methods[0]->getLocStart(),
2411 issueError ? diag::note_possibility : diag::note_using)
2412 << Methods[0]->getSourceRange();
2413 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2414 Diag(Methods[I]->getLocStart(), diag::note_also_found)
2415 << Methods[I]->getSourceRange();
2416 }
2417 }
2418 return Methods[0];
Douglas Gregorc78d3462009-04-24 21:10:55 +00002419}
2420
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00002421ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00002422 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2423 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00002424 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00002425
2426 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00002427 for (const ObjCMethodList *Method = &Methods.first; Method;
2428 Method = Method->getNext())
2429 if (Method->Method && Method->Method->isDefined())
2430 return Method->Method;
2431
2432 for (const ObjCMethodList *Method = &Methods.second; Method;
2433 Method = Method->getNext())
2434 if (Method->Method && Method->Method->isDefined())
2435 return Method->Method;
Craig Topperc3ec1492014-05-26 06:22:03 +00002436 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00002437}
2438
Fariborz Jahanian42f89382013-05-30 21:48:58 +00002439static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002440HelperSelectorsForTypoCorrection(
2441 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2442 StringRef Typo, const ObjCMethodDecl * Method) {
2443 const unsigned MaxEditDistance = 1;
2444 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00002445 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002446
2447 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2448 if (MinPossibleEditDistance > 0 &&
2449 Typo.size() / MinPossibleEditDistance < 1)
2450 return;
2451 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2452 if (EditDistance > MaxEditDistance)
2453 return;
2454 if (EditDistance == BestEditDistance)
2455 BestMethod.push_back(Method);
2456 else if (EditDistance < BestEditDistance) {
2457 BestMethod.clear();
2458 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002459 }
2460}
2461
Fariborz Jahanian75481672013-06-17 17:10:54 +00002462static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2463 QualType ObjectType) {
2464 if (ObjectType.isNull())
2465 return true;
2466 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2467 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00002468 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
2469 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00002470}
2471
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002472const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00002473Sema::SelectorsForTypoCorrection(Selector Sel,
2474 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002475 unsigned NumArgs = Sel.getNumArgs();
2476 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00002477 bool ObjectIsId = true, ObjectIsClass = true;
2478 if (ObjectType.isNull())
2479 ObjectIsId = ObjectIsClass = false;
2480 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00002481 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00002482 else if (const ObjCObjectPointerType *ObjCPtr =
2483 ObjectType->getAsObjCInterfacePointerType()) {
2484 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2485 ObjectIsId = ObjectIsClass = false;
2486 }
2487 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2488 ObjectIsClass = false;
2489 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2490 ObjectIsId = false;
2491 else
Craig Topperc3ec1492014-05-26 06:22:03 +00002492 return nullptr;
2493
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002494 for (GlobalMethodPool::iterator b = MethodPool.begin(),
2495 e = MethodPool.end(); b != e; b++) {
2496 // instance methods
2497 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2498 if (M->Method &&
Fariborz Jahanian06499232013-06-18 17:10:58 +00002499 (M->Method->getSelector().getNumArgs() == NumArgs) &&
2500 (M->Method->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00002501 if (ObjectIsId)
2502 Methods.push_back(M->Method);
2503 else if (!ObjectIsClass &&
2504 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2505 Methods.push_back(M->Method);
2506 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002507 // class methods
2508 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2509 if (M->Method &&
Fariborz Jahanian06499232013-06-18 17:10:58 +00002510 (M->Method->getSelector().getNumArgs() == NumArgs) &&
2511 (M->Method->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00002512 if (ObjectIsClass)
2513 Methods.push_back(M->Method);
2514 else if (!ObjectIsId &&
2515 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2516 Methods.push_back(M->Method);
2517 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002518 }
2519
2520 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2521 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2522 HelperSelectorsForTypoCorrection(SelectedMethods,
2523 Sel.getAsString(), Methods[i]);
2524 }
Craig Topperc3ec1492014-05-26 06:22:03 +00002525 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00002526}
2527
Fariborz Jahanian42f89382013-05-30 21:48:58 +00002528/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00002529/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00002530/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00002531/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00002532/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00002533void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2534 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00002535 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00002536 if (Ivar->isInvalidDecl())
2537 continue;
2538 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2539 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2540 if (prevIvar) {
2541 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2542 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2543 Ivar->setInvalidDecl();
2544 }
2545 }
2546 }
2547}
2548
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00002549Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2550 switch (CurContext->getDeclKind()) {
2551 case Decl::ObjCInterface:
2552 return Sema::OCK_Interface;
2553 case Decl::ObjCProtocol:
2554 return Sema::OCK_Protocol;
2555 case Decl::ObjCCategory:
2556 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2557 return Sema::OCK_ClassExtension;
2558 else
2559 return Sema::OCK_Category;
2560 case Decl::ObjCImplementation:
2561 return Sema::OCK_Implementation;
2562 case Decl::ObjCCategoryImpl:
2563 return Sema::OCK_CategoryImplementation;
2564
2565 default:
2566 return Sema::OCK_None;
2567 }
2568}
2569
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00002570// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00002571Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00002572 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00002573 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00002574 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00002575
2576 assert(AtEnd.isValid() && "Invalid location for '@end'");
2577
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00002578 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2579 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian9290ede2009-11-16 18:57:01 +00002580
Mike Stump11289f42009-09-09 15:08:12 +00002581 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00002582 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2583 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002584 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00002585
Steve Naroff35c62ae2009-01-08 17:28:14 +00002586 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2587 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2588 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2589
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00002590 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002591 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00002592 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002593
2594 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00002595 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00002596 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002597 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00002598 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00002599 : false;
Mike Stump11289f42009-09-09 15:08:12 +00002600 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00002601 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00002602 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00002603 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002604 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00002605 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002606 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00002607 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00002608 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00002609 if (!Context.getSourceManager().isInSystemHeader(
2610 Method->getLocation()))
2611 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2612 << Method->getDeclName();
2613 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2614 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002615 InsMap[Method->getSelector()] = Method;
2616 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002617 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002618 }
Mike Stump12b8ce12009-08-04 21:02:39 +00002619 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00002620 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002621 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00002622 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00002623 : false;
Mike Stump11289f42009-09-09 15:08:12 +00002624 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00002625 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00002626 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00002627 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002628 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00002629 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002630 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00002631 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00002632 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00002633 if (!Context.getSourceManager().isInSystemHeader(
2634 Method->getLocation()))
2635 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2636 << Method->getDeclName();
2637 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2638 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002639 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00002640 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002641 }
2642 }
2643 }
Douglas Gregorb8982092013-01-21 19:42:21 +00002644 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2645 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00002646 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00002647 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00002648 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00002649 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002650
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00002651 if (C->IsClassExtension()) {
2652 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2653 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00002654 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002655 }
Steve Naroffb3a87982009-01-09 15:36:25 +00002656 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002657 if (CDecl->getIdentifier())
2658 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2659 // user-defined setter/getter. It also synthesizes setter/getter methods
2660 // and adds them to the DeclContext and global method pools.
Aaron Ballmand174edf2014-03-13 19:11:50 +00002661 for (auto *I : CDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00002662 ProcessPropertyDecl(I, CDecl);
Ted Kremenekc7c64312010-01-07 01:20:12 +00002663 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00002664 }
2665 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00002666 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00002667 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00002668 // Any property declared in a class extension might have user
2669 // declared setter or getter in current class extension or one
2670 // of the other class extensions. Mark them as synthesized as
2671 // property will be synthesized when property with same name is
2672 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002673 for (const auto *Ext : IDecl->visible_extensions()) {
Aaron Ballmand174edf2014-03-13 19:11:50 +00002674 for (const auto *Property : Ext->properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00002675 // Skip over properties declared @dynamic
2676 if (const ObjCPropertyImplDecl *PIDecl
2677 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2678 if (PIDecl->getPropertyImplementation()
2679 == ObjCPropertyImplDecl::Dynamic)
2680 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002681
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002682 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002683 if (ObjCMethodDecl *GetterMethod
2684 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002685 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00002686 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002687 if (ObjCMethodDecl *SetterMethod
2688 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002689 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002690 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00002691 }
2692 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002693 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00002694 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00002695 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00002696 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00002697 if (IDecl->hasDesignatedInitializers())
2698 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2699
Patrick Beardacfbe9e2012-04-06 18:12:22 +00002700 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00002701 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00002702 // This class has no superclass, so check that it has been marked with
2703 // __attribute((objc_root_class)).
2704 if (!HasRootClassAttr) {
2705 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00002706 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00002707 Diag(DeclLoc, diag::warn_objc_root_class_missing)
2708 << IDecl->getIdentifier();
2709 // See if NSObject is in the current scope, and if it is, suggest
2710 // adding " : NSObject " to the class declaration.
2711 NamedDecl *IF = LookupSingleName(TUScope,
2712 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2713 DeclLoc, LookupOrdinaryName);
2714 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2715 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2716 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2717 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2718 } else {
2719 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2720 }
2721 }
2722 } else if (HasRootClassAttr) {
2723 // Complain that only root classes may have this attribute.
2724 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2725 }
2726
John McCall5fb5df92012-06-20 06:18:46 +00002727 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00002728 while (IDecl->getSuperClass()) {
2729 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2730 IDecl = IDecl->getSuperClass();
2731 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00002732 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00002733 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00002734 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00002735 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00002736 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00002737 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002738
Chris Lattnerda463fe2007-12-12 07:09:47 +00002739 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00002740 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00002741 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002742 if (ObjCCategoryDecl *Cat
2743 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2744 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002745 }
2746 }
2747 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002748 if (isInterfaceDeclKind) {
2749 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00002750 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002751 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002752 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2753 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00002754 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00002755 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00002756 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00002757 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00002758 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00002759 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00002760
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00002761 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00002762 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00002763 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2764 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00002765 Consumer.HandleTopLevelDeclInObjCContainer(DG);
2766 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00002767
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00002768 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00002769 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002770}
2771
2772
2773/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2774/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00002775static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002776CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00002777 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002778}
2779
Douglas Gregor33823722011-06-11 01:09:30 +00002780/// \brief Check whether the declared result type of the given Objective-C
2781/// method declaration is compatible with the method's class.
2782///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00002783static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00002784CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2785 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00002786 QualType ResultType = Method->getReturnType();
2787
Douglas Gregor33823722011-06-11 01:09:30 +00002788 // If an Objective-C method inherits its related result type, then its
2789 // declared result type must be compatible with its own class type. The
2790 // declared result type is compatible if:
2791 if (const ObjCObjectPointerType *ResultObjectType
2792 = ResultType->getAs<ObjCObjectPointerType>()) {
2793 // - it is id or qualified id, or
2794 if (ResultObjectType->isObjCIdType() ||
2795 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00002796 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00002797
2798 if (CurrentClass) {
2799 if (ObjCInterfaceDecl *ResultClass
2800 = ResultObjectType->getInterfaceDecl()) {
2801 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00002802 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00002803 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00002804
2805 // - it is a superclass of the method's class type
2806 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00002807 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00002808 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00002809 } else {
2810 // Any Objective-C pointer type might be acceptable for a protocol
2811 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00002812 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00002813 }
2814 }
2815
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00002816 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00002817}
2818
John McCalld2930c22011-07-22 02:45:48 +00002819namespace {
2820/// A helper class for searching for methods which a particular method
2821/// overrides.
2822class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00002823public:
John McCalld2930c22011-07-22 02:45:48 +00002824 Sema &S;
2825 ObjCMethodDecl *Method;
Daniel Dunbard6d74c32012-02-29 03:04:05 +00002826 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00002827 bool Recursive;
2828
2829public:
2830 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2831 Selector selector = method->getSelector();
2832
2833 // Bypass this search if we've never seen an instance/class method
2834 // with this selector before.
2835 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2836 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00002837 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00002838 S.ReadMethodPool(selector);
2839
2840 it = S.MethodPool.find(selector);
2841 if (it == S.MethodPool.end())
2842 return;
John McCalld2930c22011-07-22 02:45:48 +00002843 }
2844 ObjCMethodList &list =
2845 method->isInstanceMethod() ? it->second.first : it->second.second;
2846 if (!list.Method) return;
2847
2848 ObjCContainerDecl *container
2849 = cast<ObjCContainerDecl>(method->getDeclContext());
2850
2851 // Prevent the search from reaching this container again. This is
2852 // important with categories, which override methods from the
2853 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00002854 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2855 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00002856 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2857 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00002858 } else {
2859 searchFromContainer(container);
2860 }
Douglas Gregor33823722011-06-11 01:09:30 +00002861 }
John McCalld2930c22011-07-22 02:45:48 +00002862
Daniel Dunbard6d74c32012-02-29 03:04:05 +00002863 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00002864 iterator begin() const { return Overridden.begin(); }
2865 iterator end() const { return Overridden.end(); }
2866
2867private:
2868 void searchFromContainer(ObjCContainerDecl *container) {
2869 if (container->isInvalidDecl()) return;
2870
2871 switch (container->getDeclKind()) {
2872#define OBJCCONTAINER(type, base) \
2873 case Decl::type: \
2874 searchFrom(cast<type##Decl>(container)); \
2875 break;
2876#define ABSTRACT_DECL(expansion)
2877#define DECL(type, base) \
2878 case Decl::type:
2879#include "clang/AST/DeclNodes.inc"
2880 llvm_unreachable("not an ObjC container!");
2881 }
2882 }
2883
2884 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00002885 if (!protocol->hasDefinition())
2886 return;
2887
John McCalld2930c22011-07-22 02:45:48 +00002888 // A method in a protocol declaration overrides declarations from
2889 // referenced ("parent") protocols.
2890 search(protocol->getReferencedProtocols());
2891 }
2892
2893 void searchFrom(ObjCCategoryDecl *category) {
2894 // A method in a category declaration overrides declarations from
2895 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00002896 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00002897 search(category->getReferencedProtocols());
2898 }
2899
2900 void searchFrom(ObjCCategoryImplDecl *impl) {
2901 // A method in a category definition that has a category
2902 // declaration overrides declarations from the category
2903 // declaration.
2904 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2905 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00002906 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2907 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00002908
2909 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00002910 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2911 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00002912 }
2913 }
2914
2915 void searchFrom(ObjCInterfaceDecl *iface) {
2916 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002917 if (!iface->hasDefinition())
2918 return;
2919
John McCalld2930c22011-07-22 02:45:48 +00002920 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00002921 for (auto *Cat : iface->known_categories())
2922 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00002923
2924 // - the super class, and
2925 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2926 search(super);
2927
2928 // - any referenced protocols.
2929 search(iface->getReferencedProtocols());
2930 }
2931
2932 void searchFrom(ObjCImplementationDecl *impl) {
2933 // A method in a class implementation overrides declarations from
2934 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00002935 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2936 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00002937 }
2938
2939
2940 void search(const ObjCProtocolList &protocols) {
2941 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2942 i != e; ++i)
2943 search(*i);
2944 }
2945
2946 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00002947 // Check for a method in this container which matches this selector.
2948 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00002949 Method->isInstanceMethod(),
2950 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00002951
2952 // If we find one, record it and bail out.
2953 if (meth) {
2954 Overridden.insert(meth);
2955 return;
2956 }
2957
2958 // Otherwise, search for methods that a hypothetical method here
2959 // would have overridden.
2960
2961 // Note that we're now in a recursive case.
2962 Recursive = true;
2963
2964 searchFromContainer(container);
2965 }
2966};
Douglas Gregor33823722011-06-11 01:09:30 +00002967}
2968
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00002969void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
2970 ObjCInterfaceDecl *CurrentClass,
2971 ResultTypeCompatibilityKind RTC) {
2972 // Search for overridden methods and merge information down from them.
2973 OverrideSearch overrides(*this, ObjCMethod);
2974 // Keep track if the method overrides any method in the class's base classes,
2975 // its protocols, or its categories' protocols; we will keep that info
2976 // in the ObjCMethodDecl.
2977 // For this info, a method in an implementation is not considered as
2978 // overriding the same method in the interface or its categories.
2979 bool hasOverriddenMethodsInBaseOrProtocol = false;
2980 for (OverrideSearch::iterator
2981 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2982 ObjCMethodDecl *overridden = *i;
2983
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00002984 if (!hasOverriddenMethodsInBaseOrProtocol) {
2985 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
2986 CurrentClass != overridden->getClassInterface() ||
2987 overridden->isOverriding()) {
2988 hasOverriddenMethodsInBaseOrProtocol = true;
2989
2990 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
2991 // OverrideSearch will return as "overridden" the same method in the
2992 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
2993 // check whether a category of a base class introduced a method with the
2994 // same selector, after the interface method declaration.
2995 // To avoid unnecessary lookups in the majority of cases, we use the
2996 // extra info bits in GlobalMethodPool to check whether there were any
2997 // category methods with this selector.
2998 GlobalMethodPool::iterator It =
2999 MethodPool.find(ObjCMethod->getSelector());
3000 if (It != MethodPool.end()) {
3001 ObjCMethodList &List =
3002 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3003 unsigned CategCount = List.getBits();
3004 if (CategCount > 0) {
3005 // If the method is in a category we'll do lookup if there were at
3006 // least 2 category methods recorded, otherwise only one will do.
3007 if (CategCount > 1 ||
3008 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3009 OverrideSearch overrides(*this, overridden);
3010 for (OverrideSearch::iterator
3011 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3012 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003013 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3014 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003015 hasOverriddenMethodsInBaseOrProtocol = true;
3016 overridden->setOverriding(true);
3017 break;
3018 }
3019 }
3020 }
3021 }
3022 }
3023 }
3024 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003025
3026 // Propagate down the 'related result type' bit from overridden methods.
3027 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3028 ObjCMethod->SetRelatedResultType();
3029
3030 // Then merge the declarations.
3031 mergeObjCMethodDecls(ObjCMethod, overridden);
3032
3033 if (ObjCMethod->isImplicit() && overridden->isImplicit())
3034 continue; // Conflicting properties are detected elsewhere.
3035
3036 // Check for overriding methods
3037 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3038 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3039 CheckConflictingOverridingMethod(ObjCMethod, overridden,
3040 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3041
3042 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00003043 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3044 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003045 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3046 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003047 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3048 PrevE = overridden->param_end();
3049 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003050 assert(PrevI != overridden->param_end() && "Param mismatch");
3051 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3052 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3053 // If type of argument of method in this class does not match its
3054 // respective argument type in the super class method, issue warning;
3055 if (!Context.typesAreCompatible(T1, T2)) {
3056 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3057 << T1 << T2;
3058 Diag(overridden->getLocation(), diag::note_previous_declaration);
3059 break;
3060 }
3061 }
3062 }
3063 }
3064
3065 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3066}
3067
John McCall48871652010-08-21 09:40:31 +00003068Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00003069 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00003070 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003071 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00003072 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003073 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00003074 Selector Sel,
3075 // optional arguments. The number of types/arguments is obtained
3076 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00003077 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00003078 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00003079 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00003080 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00003081 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003082 if (!CurContext->isObjCContainer()) {
Steve Naroff83777fe2008-02-29 21:48:07 +00003083 Diag(MethodLoc, diag::error_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00003084 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00003085 }
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003086 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3087 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003088 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00003089
Douglas Gregorbab8a962011-09-08 01:46:34 +00003090 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00003091 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00003092 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00003093 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00003094
Eli Friedman31a5bcc2013-06-14 21:14:10 +00003095 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00003096 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00003097
Douglas Gregorbab8a962011-09-08 01:46:34 +00003098 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00003099 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003100 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00003101 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00003102 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00003103 }
Mike Stump11289f42009-09-09 15:08:12 +00003104
Alp Toker314cc812014-01-25 16:55:45 +00003105 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3106 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3107 MethodType == tok::minus, isVariadic,
3108 /*isPropertyAccessor=*/false,
3109 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3110 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3111 : ObjCMethodDecl::Required,
3112 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00003113
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003114 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00003115
Chris Lattner23b0faf2009-04-11 19:42:43 +00003116 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00003117 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00003118 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00003119
David Blaikie7d170102013-05-15 07:37:26 +00003120 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00003121 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00003122 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00003123 } else {
John McCall856bbea2009-10-23 21:48:59 +00003124 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00003125 }
Mike Stump11289f42009-09-09 15:08:12 +00003126
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00003127 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3128 LookupOrdinaryName, ForRedeclaration);
3129 LookupName(R, S);
3130 if (R.isSingleResult()) {
3131 NamedDecl *PrevDecl = R.getFoundDecl();
3132 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00003133 Diag(ArgInfo[i].NameLoc,
3134 (MethodDefinition ? diag::warn_method_param_redefinition
3135 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00003136 << ArgInfo[i].Name;
3137 Diag(PrevDecl->getLocation(),
3138 diag::note_previous_declaration);
3139 }
3140 }
3141
Abramo Bagnaradff19302011-03-08 08:55:46 +00003142 SourceLocation StartLoc = DI
3143 ? DI->getTypeLoc().getBeginLoc()
3144 : ArgInfo[i].NameLoc;
3145
John McCalld44f4d72011-04-23 02:46:06 +00003146 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3147 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003148 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00003149
John McCall82490832011-05-02 00:30:12 +00003150 Param->setObjCMethodScopeInfo(i);
3151
Chris Lattnerc5ffed42008-04-04 06:12:32 +00003152 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00003153 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00003154
Chris Lattner9713a1c2009-04-11 19:34:56 +00003155 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00003156 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Mike Stump11289f42009-09-09 15:08:12 +00003157
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00003158 if (Param->hasAttr<BlocksAttr>()) {
3159 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3160 Param->setInvalidDecl();
3161 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00003162 S->AddDecl(Param);
3163 IdResolver.AddDecl(Param);
3164
Chris Lattnerc5ffed42008-04-04 06:12:32 +00003165 Params.push_back(Param);
3166 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00003167
Fariborz Jahanian60462092010-04-08 00:30:06 +00003168 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00003169 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00003170 QualType ArgType = Param->getType();
3171 if (ArgType.isNull())
3172 ArgType = Context.getObjCIdType();
3173 else
3174 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00003175 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00003176
Fariborz Jahanian60462092010-04-08 00:30:06 +00003177 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00003178 Params.push_back(Param);
3179 }
3180
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003181 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003182 ObjCMethod->setObjCDeclQualifier(
3183 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00003184
3185 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00003186 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Mike Stump11289f42009-09-09 15:08:12 +00003187
Douglas Gregor87e92752010-12-21 17:34:17 +00003188 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00003189 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00003190 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003191 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003192 PrevMethod = ImpDecl->getInstanceMethod(Sel);
3193 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003194 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003195 PrevMethod = ImpDecl->getClassMethod(Sel);
3196 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003197 }
Douglas Gregor33823722011-06-11 01:09:30 +00003198
Craig Topperc3ec1492014-05-26 06:22:03 +00003199 ObjCMethodDecl *IMD = nullptr;
Fariborz Jahanian512a4cc92011-10-22 01:21:15 +00003200 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3201 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3202 ObjCMethod->isInstanceMethod());
Fariborz Jahaniandb4fc282013-07-09 22:02:20 +00003203 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3204 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3205 // merge the attribute into implementation.
Aaron Ballman36a53502014-01-16 13:03:14 +00003206 ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3207 ObjCMethod->getLocation()));
Fariborz Jahaniandb4fc282013-07-09 22:02:20 +00003208 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00003209 if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
Fariborz Jahanianf40ef452014-01-28 22:46:29 +00003210 ObjCMethodFamily family =
3211 ObjCMethod->getSelector().getMethodFamily();
Fariborz Jahanian1b30b592013-12-18 00:52:54 +00003212 if (family == OMF_dealloc && IMD && IMD->isOverriding())
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00003213 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
3214 << ObjCMethod->getDeclName();
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00003215 }
Douglas Gregor87e92752010-12-21 17:34:17 +00003216 } else {
3217 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003218 }
John McCalld2930c22011-07-22 02:45:48 +00003219
Chris Lattnerda463fe2007-12-12 07:09:47 +00003220 if (PrevMethod) {
3221 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00003222 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003223 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003224 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00003225 ObjCMethod->setInvalidDecl();
3226 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00003227 }
John McCall28a6aea2009-11-04 02:18:39 +00003228
Douglas Gregor33823722011-06-11 01:09:30 +00003229 // If this Objective-C method does not have a related result type, but we
3230 // are allowed to infer related result types, try to do so based on the
3231 // method family.
3232 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3233 if (!CurrentClass) {
3234 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3235 CurrentClass = Cat->getClassInterface();
3236 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3237 CurrentClass = Impl->getClassInterface();
3238 else if (ObjCCategoryImplDecl *CatImpl
3239 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3240 CurrentClass = CatImpl->getClassInterface();
3241 }
John McCalld2930c22011-07-22 02:45:48 +00003242
Douglas Gregorbab8a962011-09-08 01:46:34 +00003243 ResultTypeCompatibilityKind RTC
3244 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00003245
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003246 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00003247
John McCall31168b02011-06-15 23:02:42 +00003248 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00003249 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00003250 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00003251
Douglas Gregorbab8a962011-09-08 01:46:34 +00003252 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003253 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00003254 !ObjCMethod->hasRelatedResultType() &&
3255 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00003256 bool InferRelatedResultType = false;
3257 switch (ObjCMethod->getMethodFamily()) {
3258 case OMF_None:
3259 case OMF_copy:
3260 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00003261 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00003262 case OMF_mutableCopy:
3263 case OMF_release:
3264 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00003265 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00003266 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00003267 break;
3268
3269 case OMF_alloc:
3270 case OMF_new:
3271 InferRelatedResultType = ObjCMethod->isClassMethod();
3272 break;
3273
3274 case OMF_init:
3275 case OMF_autorelease:
3276 case OMF_retain:
3277 case OMF_self:
3278 InferRelatedResultType = ObjCMethod->isInstanceMethod();
3279 break;
3280 }
3281
John McCalld2930c22011-07-22 02:45:48 +00003282 if (InferRelatedResultType)
Douglas Gregor33823722011-06-11 01:09:30 +00003283 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00003284 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00003285
3286 ActOnDocumentableDecl(ObjCMethod);
3287
John McCall48871652010-08-21 09:40:31 +00003288 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003289}
3290
Chris Lattner438e5012008-12-17 07:13:27 +00003291bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00003292 // Following is also an error. But it is caused by a missing @end
3293 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00003294 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003295 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00003296
3297 // If we switched context to translation unit while we are still lexically in
3298 // an objc container, it means the parser missed emitting an error.
3299 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3300 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003301
Anders Carlssona6b508a2008-11-04 16:57:32 +00003302 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3303 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003304
Anders Carlssona6b508a2008-11-04 16:57:32 +00003305 return true;
3306}
Chris Lattner438e5012008-12-17 07:13:27 +00003307
James Dennett634962f2012-06-14 21:40:34 +00003308/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00003309/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00003310void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00003311 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003312 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00003313 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003314 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00003315 if (!Class) {
3316 Diag(DeclStart, diag::err_undef_interface) << ClassName;
3317 return;
3318 }
John McCall5fb5df92012-06-20 06:18:46 +00003319 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00003320 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3321 return;
3322 }
Mike Stump11289f42009-09-09 15:08:12 +00003323
Chris Lattner438e5012008-12-17 07:13:27 +00003324 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00003325 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003326 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00003327 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003328 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosea91768e2011-07-22 02:08:32 +00003329 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCall48871652010-08-21 09:40:31 +00003330 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00003331 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3332 /*FIXME: StartL=*/ID->getLocation(),
3333 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00003334 ID->getIdentifier(), ID->getType(),
3335 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00003336 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00003337 }
Mike Stump11289f42009-09-09 15:08:12 +00003338
Chris Lattner438e5012008-12-17 07:13:27 +00003339 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003340 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00003341 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00003342 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00003343 if (getLangOpts().CPlusPlus)
Chris Lattner438e5012008-12-17 07:13:27 +00003344 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCall48871652010-08-21 09:40:31 +00003345 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003346 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00003347 }
3348}
3349
Douglas Gregorf3564192010-04-26 17:32:49 +00003350/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00003351VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3352 SourceLocation StartLoc,
3353 SourceLocation IdLoc,
3354 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00003355 bool Invalid) {
3356 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3357 // duration shall not be qualified by an address-space qualifier."
3358 // Since all parameters have automatic store duration, they can not have
3359 // an address space.
3360 if (T.getAddressSpace() != 0) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00003361 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00003362 Invalid = true;
3363 }
3364
3365 // An @catch parameter must be an unqualified object pointer type;
3366 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3367 if (Invalid) {
3368 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00003369 } else if (T->isDependentType()) {
3370 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00003371 } else if (!T->isObjCObjectPointerType()) {
3372 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00003373 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00003374 } else if (T->isObjCQualifiedIdType()) {
3375 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00003376 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00003377 }
3378
Abramo Bagnaradff19302011-03-08 08:55:46 +00003379 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003380 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00003381 New->setExceptionVariable(true);
3382
Douglas Gregor8ca0c642011-12-10 01:22:52 +00003383 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00003384 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00003385 Invalid = true;
3386
Douglas Gregorf3564192010-04-26 17:32:49 +00003387 if (Invalid)
3388 New->setInvalidDecl();
3389 return New;
3390}
3391
John McCall48871652010-08-21 09:40:31 +00003392Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00003393 const DeclSpec &DS = D.getDeclSpec();
3394
3395 // We allow the "register" storage class on exception variables because
3396 // GCC did, but we drop it completely. Any other storage class is an error.
3397 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3398 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3399 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00003400 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00003401 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00003402 << DeclSpec::getSpecifierName(SCS);
3403 }
3404 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3405 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3406 diag::err_invalid_thread)
3407 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00003408 D.getMutableDeclSpec().ClearStorageClassSpecs();
3409
Richard Smithb1402ae2013-03-18 22:52:47 +00003410 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00003411
3412 // Check that there are no default arguments inside the type of this
3413 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00003414 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00003415 CheckExtraCXXDefaultArguments(D);
3416
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00003417 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00003418 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00003419
Abramo Bagnaradff19302011-03-08 08:55:46 +00003420 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3421 D.getSourceRange().getBegin(),
3422 D.getIdentifierLoc(),
3423 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00003424 D.isInvalidType());
3425
3426 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3427 if (D.getCXXScopeSpec().isSet()) {
3428 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3429 << D.getCXXScopeSpec().getRange();
3430 New->setInvalidDecl();
3431 }
3432
3433 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00003434 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00003435 if (D.getIdentifier())
3436 IdResolver.AddDecl(New);
3437
3438 ProcessDeclAttributes(S, New, D);
3439
3440 if (New->hasAttr<BlocksAttr>())
3441 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00003442 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00003443}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00003444
3445/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003446/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003447void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003448 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003449 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3450 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00003451 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00003452 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00003453 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00003454 }
3455}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003456
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003457void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00003458 // Load referenced selectors from the external source.
3459 if (ExternalSource) {
3460 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3461 ExternalSource->ReadReferencedSelectors(Sels);
3462 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3463 ReferencedSelectors[Sels[I].first] = Sels[I].second;
3464 }
3465
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00003466 // Warning will be issued only when selector table is
3467 // generated (which means there is at lease one implementation
3468 // in the TU). This is to match gcc's behavior.
3469 if (ReferencedSelectors.empty() ||
3470 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003471 return;
3472 for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3473 ReferencedSelectors.begin(),
3474 E = ReferencedSelectors.end(); S != E; ++S) {
3475 Selector Sel = (*S).first;
3476 if (!LookupImplementedMethodInGlobalPool(Sel))
3477 Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
3478 }
3479 return;
3480}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00003481
3482ObjCIvarDecl *
3483Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3484 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00003485 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00003486 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00003487 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3488 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00003489 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003490 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3491 /*shallowCategoryLookup=*/false,
3492 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00003493 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00003494 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003495 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00003496 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3497 // property backing ivar must belong to property's class
3498 // or be a private ivar in class's implementation.
3499 // FIXME. fix the const-ness issue.
3500 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3501 IV->getIdentifier());
3502 return IV;
3503 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003504 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00003505}
3506
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003507namespace {
3508 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3509 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00003510 class UnusedBackingIvarChecker :
3511 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003512 public:
3513 Sema &S;
3514 const ObjCMethodDecl *Method;
3515 const ObjCIvarDecl *IvarD;
3516 bool AccessedIvar;
3517 bool InvokedSelfMethod;
3518
3519 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3520 const ObjCIvarDecl *IvarD)
3521 : S(S), Method(Method), IvarD(IvarD),
3522 AccessedIvar(false), InvokedSelfMethod(false) {
3523 assert(IvarD);
3524 }
3525
3526 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3527 if (E->getDecl() == IvarD) {
3528 AccessedIvar = true;
3529 return false;
3530 }
3531 return true;
3532 }
3533
3534 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3535 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3536 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3537 InvokedSelfMethod = true;
3538 }
3539 return true;
3540 }
3541 };
3542}
3543
3544void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3545 const ObjCImplementationDecl *ImplD) {
3546 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00003547 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003548
Aaron Ballmanf26acce2014-03-13 19:50:17 +00003549 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003550 unsigned DIAG = diag::warn_unused_property_backing_ivar;
3551 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00003552 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003553 continue;
3554
3555 const ObjCPropertyDecl *PDecl;
3556 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3557 if (!IV)
3558 continue;
3559
3560 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3561 Checker.TraverseStmt(CurMethod->getBody());
3562 if (Checker.AccessedIvar)
3563 continue;
3564
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00003565 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003566 // implementation makes a self call. This is to prevent false positive in
3567 // cases where the ivar is accessed by another method that the accessor
3568 // delegates to.
3569 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00003570 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00003571 Diag(PDecl->getLocation(), diag::note_property_declare);
3572 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00003573 }
3574}