blob: cf45e916af2005c69b682b4dd6a53f47e104b9bf [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"
Richard Smith50668452015-11-24 03:55:01 +000018#include "clang/AST/RecursiveASTVisitor.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"
Douglas Gregor85f3f952015-07-07 03:57:15 +000028#include "llvm/ADT/DenseMap.h"
John McCalla1e130b2010-08-25 07:03:20 +000029#include "llvm/ADT/DenseSet.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000030#include "TypeLocBuilder.h"
John McCalla1e130b2010-08-25 07:03:20 +000031
Chris Lattnerda463fe2007-12-12 07:09:47 +000032using namespace clang;
33
John McCall31168b02011-06-15 23:02:42 +000034/// Check whether the given method, which must be in the 'init'
35/// family, is a valid member of that family.
36///
37/// \param receiverTypeIfCall - if null, check this as if declaring it;
38/// if non-null, check this as if making a call to it with the given
39/// receiver type
40///
41/// \return true to indicate that there was an error and appropriate
42/// actions were taken
43bool Sema::checkInitMethod(ObjCMethodDecl *method,
44 QualType receiverTypeIfCall) {
45 if (method->isInvalidDecl()) return true;
46
47 // This castAs is safe: methods that don't return an object
48 // pointer won't be inferred as inits and will reject an explicit
49 // objc_method_family(init).
50
51 // We ignore protocols here. Should we? What about Class?
52
Alp Toker314cc812014-01-25 16:55:45 +000053 const ObjCObjectType *result =
54 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCall31168b02011-06-15 23:02:42 +000055
56 if (result->isObjCId()) {
57 return false;
58 } else if (result->isObjCClass()) {
59 // fall through: always an error
60 } else {
61 ObjCInterfaceDecl *resultClass = result->getInterface();
62 assert(resultClass && "unexpected object type!");
63
64 // It's okay for the result type to still be a forward declaration
65 // if we're checking an interface declaration.
Douglas Gregordc9166c2011-12-15 20:29:51 +000066 if (!resultClass->hasDefinition()) {
John McCall31168b02011-06-15 23:02:42 +000067 if (receiverTypeIfCall.isNull() &&
68 !isa<ObjCImplementationDecl>(method->getDeclContext()))
69 return false;
70
71 // Otherwise, we try to compare class types.
72 } else {
73 // If this method was declared in a protocol, we can't check
74 // anything unless we have a receiver type that's an interface.
Craig Topperc3ec1492014-05-26 06:22:03 +000075 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCall31168b02011-06-15 23:02:42 +000076 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
77 if (receiverTypeIfCall.isNull())
78 return false;
79
80 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
81 ->getInterfaceDecl();
82
83 // This can be null for calls to e.g. id<Foo>.
84 if (!receiverClass) return false;
85 } else {
86 receiverClass = method->getClassInterface();
87 assert(receiverClass && "method not associated with a class!");
88 }
89
90 // If either class is a subclass of the other, it's fine.
91 if (receiverClass->isSuperClassOf(resultClass) ||
92 resultClass->isSuperClassOf(receiverClass))
93 return false;
94 }
95 }
96
97 SourceLocation loc = method->getLocation();
98
99 // If we're in a system header, and this is not a call, just make
100 // the method unusable.
101 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
John McCallc6af8c62015-10-28 05:03:19 +0000102 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
103 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
John McCall31168b02011-06-15 23:02:42 +0000104 return true;
105 }
106
107 // Otherwise, it's an error.
108 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
109 method->setInvalidDecl();
110 return true;
111}
112
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000113void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000114 const ObjCMethodDecl *Overridden) {
Douglas Gregor33823722011-06-11 01:09:30 +0000115 if (Overridden->hasRelatedResultType() &&
116 !NewMethod->hasRelatedResultType()) {
117 // This can only happen when the method follows a naming convention that
118 // implies a related result type, and the original (overridden) method has
119 // a suitable return type, but the new (overriding) method does not have
120 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000121 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000122 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +0000123
124 // Figure out which class this method is part of, if any.
125 ObjCInterfaceDecl *CurrentClass
126 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
127 if (!CurrentClass) {
128 DeclContext *DC = NewMethod->getDeclContext();
129 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
130 CurrentClass = Cat->getClassInterface();
131 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
132 CurrentClass = Impl->getClassInterface();
133 else if (ObjCCategoryImplDecl *CatImpl
134 = dyn_cast<ObjCCategoryImplDecl>(DC))
135 CurrentClass = CatImpl->getClassInterface();
136 }
137
138 if (CurrentClass) {
139 Diag(NewMethod->getLocation(),
140 diag::warn_related_result_type_compatibility_class)
141 << Context.getObjCInterfaceType(CurrentClass)
142 << ResultType
143 << ResultTypeRange;
144 } else {
145 Diag(NewMethod->getLocation(),
146 diag::warn_related_result_type_compatibility_protocol)
147 << ResultType
148 << ResultTypeRange;
149 }
150
Douglas Gregorbab8a962011-09-08 01:46:34 +0000151 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
152 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000153 diag::note_related_result_type_family)
154 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000155 << Family;
156 else
157 Diag(Overridden->getLocation(),
158 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000159 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000160 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000161 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
162 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
163 Diag(NewMethod->getLocation(),
164 diag::err_nsreturns_retained_attribute_mismatch) << 1;
165 Diag(Overridden->getLocation(), diag::note_previous_decl)
166 << "method";
167 }
168 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
169 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
170 Diag(NewMethod->getLocation(),
171 diag::err_nsreturns_retained_attribute_mismatch) << 0;
172 Diag(Overridden->getLocation(), diag::note_previous_decl)
173 << "method";
174 }
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000175 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
176 oe = Overridden->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000177 for (ObjCMethodDecl::param_iterator
178 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000179 ni != ne && oi != oe; ++ni, ++oi) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000180 const ParmVarDecl *oldDecl = (*oi);
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000181 ParmVarDecl *newDecl = (*ni);
182 if (newDecl->hasAttr<NSConsumedAttr>() !=
183 oldDecl->hasAttr<NSConsumedAttr>()) {
184 Diag(newDecl->getLocation(),
185 diag::err_nsconsumed_attribute_mismatch);
186 Diag(oldDecl->getLocation(), diag::note_previous_decl)
187 << "parameter";
188 }
189 }
190 }
Douglas Gregor33823722011-06-11 01:09:30 +0000191}
192
John McCall31168b02011-06-15 23:02:42 +0000193/// \brief Check a method declaration for compatibility with the Objective-C
194/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000195bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000196 ObjCMethodFamily family = method->getMethodFamily();
197 switch (family) {
198 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000199 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000200 case OMF_retain:
201 case OMF_release:
202 case OMF_autorelease:
203 case OMF_retainCount:
204 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000205 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000206 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000207 return false;
208
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000209 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000210 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000211 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000212 if (ResultTypeRange.isInvalid())
Alp Toker314cc812014-01-25 16:55:45 +0000213 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
214 << method->getReturnType()
215 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000216 else
Alp Toker314cc812014-01-25 16:55:45 +0000217 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
218 << method->getReturnType()
219 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000220 return true;
221 }
222 return false;
223
John McCall31168b02011-06-15 23:02:42 +0000224 case OMF_init:
225 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000226 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000227 return true;
228
Aaron Ballman36a53502014-01-16 13:03:14 +0000229 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000230
231 // Don't add a second copy of this attribute, but otherwise don't
232 // let it be suppressed.
233 if (method->hasAttr<NSReturnsRetainedAttr>())
234 return false;
235 break;
236
237 case OMF_alloc:
238 case OMF_copy:
239 case OMF_mutableCopy:
240 case OMF_new:
241 if (method->hasAttr<NSReturnsRetainedAttr>() ||
242 method->hasAttr<NSReturnsNotRetainedAttr>() ||
243 method->hasAttr<NSReturnsAutoreleasedAttr>())
244 return false;
245 break;
246 }
247
Aaron Ballman36a53502014-01-16 13:03:14 +0000248 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000249 return false;
250}
251
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000252static void DiagnoseObjCImplementedDeprecations(Sema &S,
253 NamedDecl *ND,
254 SourceLocation ImplLoc,
255 int select) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000256 if (ND && ND->isDeprecated()) {
Fariborz Jahanian6fd94352011-02-16 00:30:31 +0000257 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000258 if (select == 0)
Ted Kremenek59b10db2012-02-27 22:55:11 +0000259 S.Diag(ND->getLocation(), diag::note_method_declared_at)
260 << ND->getDeclName();
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000261 else
262 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
263 }
264}
265
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000266/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
267/// pool.
268void Sema::AddAnyMethodToGlobalPool(Decl *D) {
269 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
270
271 // If we don't have a valid method decl, simply return.
272 if (!MDecl)
273 return;
274 if (MDecl->isInstanceMethod())
275 AddInstanceMethodToGlobalPool(MDecl, true);
276 else
277 AddFactoryMethodToGlobalPool(MDecl, true);
278}
279
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000280/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
281/// has explicit ownership attribute; false otherwise.
282static bool
283HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
284 QualType T = Param->getType();
285
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000286 if (const PointerType *PT = T->getAs<PointerType>()) {
287 T = PT->getPointeeType();
288 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
289 T = RT->getPointeeType();
290 } else {
291 return true;
292 }
293
294 // If we have a lifetime qualifier, but it's local, we must have
295 // inferred it. So, it is implicit.
296 return !T.getLocalQualifiers().hasObjCLifetime();
297}
298
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000299/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
300/// and user declared, in the method definition's AST.
301void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000302 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000303 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000304
Steve Naroff542cd5d2008-07-25 17:57:26 +0000305 // If we don't have a valid method decl, simply return.
306 if (!MDecl)
307 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000308
Chris Lattnerda463fe2007-12-12 07:09:47 +0000309 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000310 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000311 PushFunctionScope();
312
Chris Lattnerda463fe2007-12-12 07:09:47 +0000313 // Create Decl objects for each parameter, entrring them in the scope for
314 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000315
316 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000317 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000318
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000319 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
320 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000321
Reid Kleckner5a115802013-06-24 14:38:26 +0000322 // The ObjC parser requires parameter names so there's no need to check.
323 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
324 /*CheckParameterNames=*/false);
325
Chris Lattner58258242008-04-10 02:22:51 +0000326 // Introduce all of the other parameters into this scope.
Aaron Ballman43b68be2014-03-07 17:50:17 +0000327 for (auto *Param : MDecl->params()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000328 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000329 getLangOpts().ObjCAutoRefCount &&
330 !HasExplicitOwnershipAttr(*this, Param))
331 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
332 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000333
Aaron Ballman43b68be2014-03-07 17:50:17 +0000334 if (Param->getIdentifier())
335 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000336 }
John McCall31168b02011-06-15 23:02:42 +0000337
338 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000339 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000340 switch (MDecl->getMethodFamily()) {
341 case OMF_retain:
342 case OMF_retainCount:
343 case OMF_release:
344 case OMF_autorelease:
345 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000346 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000347 break;
348
349 case OMF_None:
350 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000351 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000352 case OMF_alloc:
353 case OMF_init:
354 case OMF_mutableCopy:
355 case OMF_copy:
356 case OMF_new:
357 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000358 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000359 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000360 break;
361 }
362 }
363
Nico Weber715abaf2011-08-22 17:25:57 +0000364 // Warn on deprecated methods under -Wdeprecated-implementations,
365 // and prepare for warning on missing super calls.
366 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000367 ObjCMethodDecl *IMD =
368 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
369
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000370 if (IMD) {
371 ObjCImplDecl *ImplDeclOfMethodDef =
372 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
373 ObjCContainerDecl *ContDeclOfMethodDecl =
374 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000375 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000376 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
377 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000378 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
379 if (CD->IsClassExtension()) {
380 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
381 ImplDeclOfMethodDecl = OID->getImplementation();
382 } else
383 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000384 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000385 // No need to issue deprecated warning if deprecated mehod in class/category
386 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000387 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000388 DiagnoseObjCImplementedDeprecations(*this,
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000389 dyn_cast<NamedDecl>(IMD),
390 MDecl->getLocation(), 0);
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000391 }
Nico Weber715abaf2011-08-22 17:25:57 +0000392
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000393 if (MDecl->getMethodFamily() == OMF_init) {
394 if (MDecl->isDesignatedInitializerForTheInterface()) {
395 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000396 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000397 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000398 } else if (IC->hasDesignatedInitializers()) {
399 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000400 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000401 }
402 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000403
Nico Weber1fb82662011-08-28 22:35:17 +0000404 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000405 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
406 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
407 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000408 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000409 ObjCMethodFamily Family = MDecl->getMethodFamily();
410 if (Family == OMF_dealloc) {
411 if (!(getLangOpts().ObjCAutoRefCount ||
412 getLangOpts().getGC() == LangOptions::GCOnly))
413 getCurFunction()->ObjCShouldCallSuper = true;
414
415 } else if (Family == OMF_finalize) {
416 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
417 getCurFunction()->ObjCShouldCallSuper = true;
418
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000419 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000420 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000421 SuperClass->lookupMethod(MDecl->getSelector(),
422 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000423 getCurFunction()->ObjCShouldCallSuper =
424 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000425 }
Nico Weber1fb82662011-08-28 22:35:17 +0000426 }
Nico Weber715abaf2011-08-22 17:25:57 +0000427 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000428}
429
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000430namespace {
431
432// Callback to only accept typo corrections that are Objective-C classes.
433// If an ObjCInterfaceDecl* is given to the constructor, then the validation
434// function will reject corrections to that class.
435class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
436 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000437 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000438 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
439 : CurrentIDecl(IDecl) {}
440
Craig Toppere14c0f82014-03-12 04:55:44 +0000441 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000442 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
443 return ID && !declaresSameEntity(ID, CurrentIDecl);
444 }
445
446 private:
447 ObjCInterfaceDecl *CurrentIDecl;
448};
449
Hans Wennborgdcfba332015-10-06 23:40:43 +0000450} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000451
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000452static void diagnoseUseOfProtocols(Sema &TheSema,
453 ObjCContainerDecl *CD,
454 ObjCProtocolDecl *const *ProtoRefs,
455 unsigned NumProtoRefs,
456 const SourceLocation *ProtoLocs) {
457 assert(ProtoRefs);
458 // Diagnose availability in the context of the ObjC container.
459 Sema::ContextRAII SavedContext(TheSema, CD);
460 for (unsigned i = 0; i < NumProtoRefs; ++i) {
461 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]);
462 }
463}
464
Douglas Gregore9d95f12015-07-07 03:57:35 +0000465void Sema::
466ActOnSuperClassOfClassInterface(Scope *S,
467 SourceLocation AtInterfaceLoc,
468 ObjCInterfaceDecl *IDecl,
469 IdentifierInfo *ClassName,
470 SourceLocation ClassLoc,
471 IdentifierInfo *SuperName,
472 SourceLocation SuperLoc,
473 ArrayRef<ParsedType> SuperTypeArgs,
474 SourceRange SuperTypeArgsRange) {
475 // Check if a different kind of symbol declared in this scope.
476 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
477 LookupOrdinaryName);
478
479 if (!PrevDecl) {
480 // Try to correct for a typo in the superclass name without correcting
481 // to the class we're defining.
482 if (TypoCorrection Corrected = CorrectTypo(
483 DeclarationNameInfo(SuperName, SuperLoc),
484 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000485 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000486 CTK_ErrorRecovery)) {
487 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
488 << SuperName << ClassName);
489 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
490 }
491 }
492
493 if (declaresSameEntity(PrevDecl, IDecl)) {
494 Diag(SuperLoc, diag::err_recursive_superclass)
495 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
496 IDecl->setEndOfDefinitionLoc(ClassLoc);
497 } else {
498 ObjCInterfaceDecl *SuperClassDecl =
499 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
500 QualType SuperClassType;
501
502 // Diagnose classes that inherit from deprecated classes.
503 if (SuperClassDecl) {
504 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
505 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
506 }
507
Hans Wennborgdcfba332015-10-06 23:40:43 +0000508 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000509 // The previous declaration was not a class decl. Check if we have a
510 // typedef. If we do, get the underlying class type.
511 if (const TypedefNameDecl *TDecl =
512 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
513 QualType T = TDecl->getUnderlyingType();
514 if (T->isObjCObjectType()) {
515 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
516 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
517 SuperClassType = Context.getTypeDeclType(TDecl);
518
519 // This handles the following case:
520 // @interface NewI @end
521 // typedef NewI DeprI __attribute__((deprecated("blah")))
522 // @interface SI : DeprI /* warn here */ @end
523 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
524 }
525 }
526 }
527
528 // This handles the following case:
529 //
530 // typedef int SuperClass;
531 // @interface MyClass : SuperClass {} @end
532 //
533 if (!SuperClassDecl) {
534 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
535 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
536 }
537 }
538
539 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
540 if (!SuperClassDecl)
541 Diag(SuperLoc, diag::err_undef_superclass)
542 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
543 else if (RequireCompleteType(SuperLoc,
544 SuperClassType,
545 diag::err_forward_superclass,
546 SuperClassDecl->getDeclName(),
547 ClassName,
548 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000549 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000550 SuperClassType = QualType();
551 }
552 }
553
554 if (SuperClassType.isNull()) {
555 assert(!SuperClassDecl && "Failed to set SuperClassType?");
556 return;
557 }
558
559 // Handle type arguments on the superclass.
560 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000561 if (!SuperTypeArgs.empty()) {
562 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
563 S,
564 SuperLoc,
565 CreateParsedType(SuperClassType,
566 nullptr),
567 SuperTypeArgsRange.getBegin(),
568 SuperTypeArgs,
569 SuperTypeArgsRange.getEnd(),
570 SourceLocation(),
571 { },
572 { },
573 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000574 if (!fullSuperClassType.isUsable())
575 return;
576
577 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
578 &SuperClassTInfo);
579 }
580
581 if (!SuperClassTInfo) {
582 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
583 SuperLoc);
584 }
585
586 IDecl->setSuperClass(SuperClassTInfo);
587 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
588 }
589}
590
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000591DeclResult Sema::actOnObjCTypeParam(Scope *S,
592 ObjCTypeParamVariance variance,
593 SourceLocation varianceLoc,
594 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000595 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000596 SourceLocation paramLoc,
597 SourceLocation colonLoc,
598 ParsedType parsedTypeBound) {
599 // If there was an explicitly-provided type bound, check it.
600 TypeSourceInfo *typeBoundInfo = nullptr;
601 if (parsedTypeBound) {
602 // The type bound can be any Objective-C pointer type.
603 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
604 if (typeBound->isObjCObjectPointerType()) {
605 // okay
606 } else if (typeBound->isObjCObjectType()) {
607 // The user forgot the * on an Objective-C pointer type, e.g.,
608 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000609 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000610 typeBoundInfo->getTypeLoc().getEndLoc());
611 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
612 diag::err_objc_type_param_bound_missing_pointer)
613 << typeBound << paramName
614 << FixItHint::CreateInsertion(starLoc, " *");
615
616 // Create a new type location builder so we can update the type
617 // location information we have.
618 TypeLocBuilder builder;
619 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
620
621 // Create the Objective-C pointer type.
622 typeBound = Context.getObjCObjectPointerType(typeBound);
623 ObjCObjectPointerTypeLoc newT
624 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
625 newT.setStarLoc(starLoc);
626
627 // Form the new type source information.
628 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
629 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000630 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000631 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
632 diag::err_objc_type_param_bound_nonobject)
633 << typeBound << paramName;
634
635 // Forget the bound; we'll default to id later.
636 typeBoundInfo = nullptr;
637 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000638
John McCall69975252015-09-23 22:14:21 +0000639 // Type bounds cannot have qualifiers (even indirectly) or explicit
640 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000641 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000642 QualType typeBound = typeBoundInfo->getType();
643 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
644 if (qual || typeBound.hasQualifiers()) {
645 bool diagnosed = false;
646 SourceRange rangeToRemove;
647 if (qual) {
648 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
649 rangeToRemove = attr.getLocalSourceRange();
650 if (attr.getTypePtr()->getImmediateNullability()) {
651 Diag(attr.getLocStart(),
652 diag::err_objc_type_param_bound_explicit_nullability)
653 << paramName << typeBound
654 << FixItHint::CreateRemoval(rangeToRemove);
655 diagnosed = true;
656 }
657 }
658 }
659
660 if (!diagnosed) {
661 Diag(qual ? qual.getLocStart()
662 : typeBoundInfo->getTypeLoc().getLocStart(),
663 diag::err_objc_type_param_bound_qualified)
664 << paramName << typeBound << typeBound.getQualifiers().getAsString()
665 << FixItHint::CreateRemoval(rangeToRemove);
666 }
667
668 // If the type bound has qualifiers other than CVR, we need to strip
669 // them or we'll probably assert later when trying to apply new
670 // qualifiers.
671 Qualifiers quals = typeBound.getQualifiers();
672 quals.removeCVRQualifiers();
673 if (!quals.empty()) {
674 typeBoundInfo =
675 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
676 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000677 }
678 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000679 }
680
681 // If there was no explicit type bound (or we removed it due to an error),
682 // use 'id' instead.
683 if (!typeBoundInfo) {
684 colonLoc = SourceLocation();
685 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
686 }
687
688 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000689 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
690 index, paramLoc, paramName, colonLoc,
691 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000692}
693
694ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
695 SourceLocation lAngleLoc,
696 ArrayRef<Decl *> typeParamsIn,
697 SourceLocation rAngleLoc) {
698 // We know that the array only contains Objective-C type parameters.
699 ArrayRef<ObjCTypeParamDecl *>
700 typeParams(
701 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
702 typeParamsIn.size());
703
704 // Diagnose redeclarations of type parameters.
705 // We do this now because Objective-C type parameters aren't pushed into
706 // scope until later (after the instance variable block), but we want the
707 // diagnostics to occur right after we parse the type parameter list.
708 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
709 for (auto typeParam : typeParams) {
710 auto known = knownParams.find(typeParam->getIdentifier());
711 if (known != knownParams.end()) {
712 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
713 << typeParam->getIdentifier()
714 << SourceRange(known->second->getLocation());
715
716 typeParam->setInvalidDecl();
717 } else {
718 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
719
720 // Push the type parameter into scope.
721 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
722 }
723 }
724
725 // Create the parameter list.
726 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
727}
728
729void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
730 for (auto typeParam : *typeParamList) {
731 if (!typeParam->isInvalidDecl()) {
732 S->RemoveDecl(typeParam);
733 IdResolver.RemoveDecl(typeParam);
734 }
735 }
736}
737
738namespace {
739 /// The context in which an Objective-C type parameter list occurs, for use
740 /// in diagnostics.
741 enum class TypeParamListContext {
742 ForwardDeclaration,
743 Definition,
744 Category,
745 Extension
746 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000747} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000748
749/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000750/// between a category/extension and an \@interface or between an \@class and an
751/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000752static bool checkTypeParamListConsistency(Sema &S,
753 ObjCTypeParamList *prevTypeParams,
754 ObjCTypeParamList *newTypeParams,
755 TypeParamListContext newContext) {
756 // If the sizes don't match, complain about that.
757 if (prevTypeParams->size() != newTypeParams->size()) {
758 SourceLocation diagLoc;
759 if (newTypeParams->size() > prevTypeParams->size()) {
760 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
761 } else {
Craig Topper07fa1762015-11-15 02:31:46 +0000762 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000763 }
764
765 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
766 << static_cast<unsigned>(newContext)
767 << (newTypeParams->size() > prevTypeParams->size())
768 << prevTypeParams->size()
769 << newTypeParams->size();
770
771 return true;
772 }
773
774 // Match up the type parameters.
775 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
776 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
777 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
778
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000779 // Check for consistency of the variance.
780 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
781 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
782 newContext != TypeParamListContext::Definition) {
783 // When the new type parameter is invariant and is not part
784 // of the definition, just propagate the variance.
785 newTypeParam->setVariance(prevTypeParam->getVariance());
786 } else if (prevTypeParam->getVariance()
787 == ObjCTypeParamVariance::Invariant &&
788 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
789 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
790 ->getDefinition() == prevTypeParam->getDeclContext())) {
791 // When the old parameter is invariant and was not part of the
792 // definition, just ignore the difference because it doesn't
793 // matter.
794 } else {
795 {
796 // Diagnose the conflict and update the second declaration.
797 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
798 if (diagLoc.isInvalid())
799 diagLoc = newTypeParam->getLocStart();
800
801 auto diag = S.Diag(diagLoc,
802 diag::err_objc_type_param_variance_conflict)
803 << static_cast<unsigned>(newTypeParam->getVariance())
804 << newTypeParam->getDeclName()
805 << static_cast<unsigned>(prevTypeParam->getVariance())
806 << prevTypeParam->getDeclName();
807 switch (prevTypeParam->getVariance()) {
808 case ObjCTypeParamVariance::Invariant:
809 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
810 break;
811
812 case ObjCTypeParamVariance::Covariant:
813 case ObjCTypeParamVariance::Contravariant: {
814 StringRef newVarianceStr
815 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
816 ? "__covariant"
817 : "__contravariant";
818 if (newTypeParam->getVariance()
819 == ObjCTypeParamVariance::Invariant) {
820 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
821 (newVarianceStr + " ").str());
822 } else {
823 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
824 newVarianceStr);
825 }
826 }
827 }
828 }
829
830 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
831 << prevTypeParam->getDeclName();
832
833 // Override the variance.
834 newTypeParam->setVariance(prevTypeParam->getVariance());
835 }
836 }
837
Douglas Gregor85f3f952015-07-07 03:57:15 +0000838 // If the bound types match, there's nothing to do.
839 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
840 newTypeParam->getUnderlyingType()))
841 continue;
842
843 // If the new type parameter's bound was explicit, complain about it being
844 // different from the original.
845 if (newTypeParam->hasExplicitBound()) {
846 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
847 ->getTypeLoc().getSourceRange();
848 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
849 << newTypeParam->getUnderlyingType()
850 << newTypeParam->getDeclName()
851 << prevTypeParam->hasExplicitBound()
852 << prevTypeParam->getUnderlyingType()
853 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
854 << prevTypeParam->getDeclName()
855 << FixItHint::CreateReplacement(
856 newBoundRange,
857 prevTypeParam->getUnderlyingType().getAsString(
858 S.Context.getPrintingPolicy()));
859
860 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
861 << prevTypeParam->getDeclName();
862
863 // Override the new type parameter's bound type with the previous type,
864 // so that it's consistent.
865 newTypeParam->setTypeSourceInfo(
866 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
867 continue;
868 }
869
870 // The new type parameter got the implicit bound of 'id'. That's okay for
871 // categories and extensions (overwrite it later), but not for forward
872 // declarations and @interfaces, because those must be standalone.
873 if (newContext == TypeParamListContext::ForwardDeclaration ||
874 newContext == TypeParamListContext::Definition) {
875 // Diagnose this problem for forward declarations and definitions.
876 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000877 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000878 std::string newCode
879 = " : " + prevTypeParam->getUnderlyingType().getAsString(
880 S.Context.getPrintingPolicy());
881 S.Diag(newTypeParam->getLocation(),
882 diag::err_objc_type_param_bound_missing)
883 << prevTypeParam->getUnderlyingType()
884 << newTypeParam->getDeclName()
885 << (newContext == TypeParamListContext::ForwardDeclaration)
886 << FixItHint::CreateInsertion(insertionLoc, newCode);
887
888 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
889 << prevTypeParam->getDeclName();
890 }
891
892 // Update the new type parameter's bound to match the previous one.
893 newTypeParam->setTypeSourceInfo(
894 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
895 }
896
897 return false;
898}
899
John McCall48871652010-08-21 09:40:31 +0000900Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000901ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000902 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000903 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000904 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000905 ArrayRef<ParsedType> SuperTypeArgs,
906 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000907 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000908 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000909 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000910 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000911
Chris Lattnerda463fe2007-12-12 07:09:47 +0000912 // Check for another declaration kind with the same name.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000913 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000914 LookupOrdinaryName, ForRedeclaration);
Douglas Gregor5101c242008-12-05 18:15:24 +0000915
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000916 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000917 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000918 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000919 }
Mike Stump11289f42009-09-09 15:08:12 +0000920
Douglas Gregordc9166c2011-12-15 20:29:51 +0000921 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000922 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000923
924 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
925 // A previous decl with a different name is because of
926 // @compatibility_alias, for example:
927 // \code
928 // @class NewImage;
929 // @compatibility_alias OldImage NewImage;
930 // \endcode
931 // A lookup for 'OldImage' will return the 'NewImage' decl.
932 //
933 // In such a case use the real declaration name, instead of the alias one,
934 // otherwise we will break IdentifierResolver and redecls-chain invariants.
935 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
936 // has been aliased.
937 ClassName = PrevIDecl->getIdentifier();
938 }
939
Douglas Gregor85f3f952015-07-07 03:57:15 +0000940 // If there was a forward declaration with type parameters, check
941 // for consistency.
942 if (PrevIDecl) {
943 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
944 if (typeParamList) {
945 // Both have type parameter lists; check for consistency.
946 if (checkTypeParamListConsistency(*this, prevTypeParamList,
947 typeParamList,
948 TypeParamListContext::Definition)) {
949 typeParamList = nullptr;
950 }
951 } else {
952 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
953 << ClassName;
954 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
955 << ClassName;
956
957 // Clone the type parameter list.
958 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
959 for (auto typeParam : *prevTypeParamList) {
960 clonedTypeParams.push_back(
961 ObjCTypeParamDecl::Create(
962 Context,
963 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000964 typeParam->getVariance(),
965 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000966 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +0000967 SourceLocation(),
968 typeParam->getIdentifier(),
969 SourceLocation(),
970 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
971 }
972
973 typeParamList = ObjCTypeParamList::create(Context,
974 SourceLocation(),
975 clonedTypeParams,
976 SourceLocation());
977 }
978 }
979 }
980
Douglas Gregordc9166c2011-12-15 20:29:51 +0000981 ObjCInterfaceDecl *IDecl
982 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000983 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000984 if (PrevIDecl) {
985 // Class already seen. Was it a definition?
986 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
987 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
988 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +0000989 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000990 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +0000991 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000992 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000993
994 if (AttrList)
995 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
996 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +0000997
Douglas Gregordc9166c2011-12-15 20:29:51 +0000998 // Start the definition of this class. If we're in a redefinition case, there
999 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001000 if (!IDecl->hasDefinition())
1001 IDecl->startDefinition();
1002
Chris Lattnerda463fe2007-12-12 07:09:47 +00001003 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001004 // Diagnose availability in the context of the @interface.
1005 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001006
Douglas Gregore9d95f12015-07-07 03:57:35 +00001007 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1008 ClassName, ClassLoc,
1009 SuperName, SuperLoc, SuperTypeArgs,
1010 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001011 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001012 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001013 }
Mike Stump11289f42009-09-09 15:08:12 +00001014
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001015 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001016 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001017 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1018 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001019 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001020 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001021 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001022 }
Mike Stump11289f42009-09-09 15:08:12 +00001023
Anders Carlssona6b508a2008-11-04 16:57:32 +00001024 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001025 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001026}
1027
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001028/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1029/// typedef'ed use for a qualified super class and adds them to the list
1030/// of the protocols.
1031void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1032 IdentifierInfo *SuperName,
1033 SourceLocation SuperLoc) {
1034 if (!SuperName)
1035 return;
1036 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1037 LookupOrdinaryName);
1038 if (!IDecl)
1039 return;
1040
1041 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1042 QualType T = TDecl->getUnderlyingType();
1043 if (T->isObjCObjectType())
1044 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
Benjamin Kramerf9890422015-02-17 16:48:30 +00001045 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001046 }
1047}
1048
Richard Smithac4e36d2012-08-08 23:32:13 +00001049/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001050/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001051Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1052 IdentifierInfo *AliasName,
1053 SourceLocation AliasLocation,
1054 IdentifierInfo *ClassName,
1055 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001056 // Look for previous declaration of alias name
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001057 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001058 LookupOrdinaryName, ForRedeclaration);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001059 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001060 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001061 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001062 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001063 }
1064 // Check for class declaration
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001065 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001066 LookupOrdinaryName, ForRedeclaration);
Richard Smithdda56e42011-04-15 14:24:37 +00001067 if (const TypedefNameDecl *TDecl =
1068 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001069 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001070 if (T->isObjCObjectType()) {
1071 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001072 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001073 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001074 LookupOrdinaryName, ForRedeclaration);
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001075 }
1076 }
1077 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001078 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001079 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001080 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001081 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001082 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001083 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001084 }
Mike Stump11289f42009-09-09 15:08:12 +00001085
Chris Lattner219b3e92008-03-16 21:17:37 +00001086 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001087 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001088 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001089
Anders Carlssona6b508a2008-11-04 16:57:32 +00001090 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001091 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001092
John McCall48871652010-08-21 09:40:31 +00001093 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001094}
1095
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001096bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001097 IdentifierInfo *PName,
1098 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001099 const ObjCList<ObjCProtocolDecl> &PList) {
1100
1101 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001102 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1103 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001104 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1105 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001106 if (PDecl->getIdentifier() == PName) {
1107 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1108 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001109 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001110 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001111
1112 if (!PDecl->hasDefinition())
1113 continue;
1114
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001115 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1116 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1117 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001118 }
1119 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001120 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001121}
1122
John McCall48871652010-08-21 09:40:31 +00001123Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001124Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1125 IdentifierInfo *ProtocolName,
1126 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001127 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001128 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001129 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001130 SourceLocation EndProtoLoc,
1131 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001132 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001133 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001134 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001135 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1136 ForRedeclaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001137 ObjCProtocolDecl *PDecl = nullptr;
1138 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001139 // If we already have a definition, complain.
1140 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1141 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001142
Douglas Gregor32c17572012-01-01 20:30:41 +00001143 // Create a new protocol that is completely distinct from previous
1144 // declarations, and do not make this protocol available for name lookup.
1145 // That way, we'll end up completely ignoring the duplicate.
1146 // FIXME: Can we turn this into an error?
1147 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1148 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001149 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001150 PDecl->startDefinition();
1151 } else {
1152 if (PrevDecl) {
1153 // Check for circular dependencies among protocol declarations. This can
1154 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001155 ObjCList<ObjCProtocolDecl> PList;
1156 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1157 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001158 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001159 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001160
1161 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001162 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001163 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001164 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001165
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001166 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001167 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001168 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001169
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001170 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001171 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001172
1173 // Merge attributes from previous declarations.
1174 if (PrevDecl)
1175 mergeDeclAttributes(PDecl, PrevDecl);
1176
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001177 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001178 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001179 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1180 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001181 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001182 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001183 }
Mike Stump11289f42009-09-09 15:08:12 +00001184
1185 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001186 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001187}
1188
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001189static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1190 ObjCProtocolDecl *&UndefinedProtocol) {
1191 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1192 UndefinedProtocol = PDecl;
1193 return true;
1194 }
1195
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001196 for (auto *PI : PDecl->protocols())
1197 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1198 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001199 return true;
1200 }
1201 return false;
1202}
1203
Chris Lattnerda463fe2007-12-12 07:09:47 +00001204/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001205/// issues an error if they are not declared. It returns list of
1206/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001207void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001208Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001209 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001210 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001211 for (const IdentifierLocPair &Pair : ProtocolId) {
1212 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001213 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001214 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001215 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001216 LookupObjCProtocolName, TUScope, nullptr,
1217 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001218 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001219 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1220 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001221 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001222 }
1223
1224 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001225 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001226 continue;
1227 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001228 // If this is a forward protocol declaration, get its definition.
1229 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1230 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001231
1232 // For an objc container, delay protocol reference checking until after we
1233 // can set the objc decl as the availability context, otherwise check now.
1234 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001235 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001236 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001237
1238 // If this is a forward declaration and we are supposed to warn in this
1239 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001240 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001241 ObjCProtocolDecl *UndefinedProtocol;
1242
Douglas Gregoreed49792013-01-17 00:38:46 +00001243 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001244 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001245 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001246 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1247 << UndefinedProtocol;
1248 }
John McCall48871652010-08-21 09:40:31 +00001249 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001250 }
1251}
1252
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001253namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001254// Callback to only accept typo corrections that are either
1255// Objective-C protocols or valid Objective-C type arguments.
1256class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1257 ASTContext &Context;
1258 Sema::LookupNameKind LookupKind;
1259 public:
1260 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1261 Sema::LookupNameKind lookupKind)
1262 : Context(context), LookupKind(lookupKind) { }
1263
1264 bool ValidateCandidate(const TypoCorrection &candidate) override {
1265 // If we're allowed to find protocols and we have a protocol, accept it.
1266 if (LookupKind != Sema::LookupOrdinaryName) {
1267 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1268 return true;
1269 }
1270
1271 // If we're allowed to find type names and we have one, accept it.
1272 if (LookupKind != Sema::LookupObjCProtocolName) {
1273 // If we have a type declaration, we might accept this result.
1274 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1275 // If we found a tag declaration outside of C++, skip it. This
1276 // can happy because we look for any name when there is no
1277 // bias to protocol or type names.
1278 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1279 return false;
1280
1281 // Make sure the type is something we would accept as a type
1282 // argument.
1283 auto type = Context.getTypeDeclType(typeDecl);
1284 if (type->isObjCObjectPointerType() ||
1285 type->isBlockPointerType() ||
1286 type->isDependentType() ||
1287 type->isObjCObjectType())
1288 return true;
1289
1290 return false;
1291 }
1292
1293 // If we have an Objective-C class type, accept it; there will
1294 // be another fix to add the '*'.
1295 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1296 return true;
1297
1298 return false;
1299 }
1300
1301 return false;
1302 }
1303};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001304} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001305
1306void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1307 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001308 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001309 SourceLocation lAngleLoc,
1310 ArrayRef<IdentifierInfo *> identifiers,
1311 ArrayRef<SourceLocation> identifierLocs,
1312 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001313 SourceLocation &typeArgsLAngleLoc,
1314 SmallVectorImpl<ParsedType> &typeArgs,
1315 SourceLocation &typeArgsRAngleLoc,
1316 SourceLocation &protocolLAngleLoc,
1317 SmallVectorImpl<Decl *> &protocols,
1318 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001319 bool warnOnIncompleteProtocols) {
1320 // Local function that updates the declaration specifiers with
1321 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001322 unsigned numProtocolsResolved = 0;
1323 auto resolvedAsProtocols = [&] {
1324 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1325
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001326 // Determine whether the base type is a parameterized class, in
1327 // which case we want to warn about typos such as
1328 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1329 ObjCInterfaceDecl *baseClass = nullptr;
1330 QualType base = GetTypeFromParser(baseType, nullptr);
1331 bool allAreTypeNames = false;
1332 SourceLocation firstClassNameLoc;
1333 if (!base.isNull()) {
1334 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1335 baseClass = objcObjectType->getInterface();
1336 if (baseClass) {
1337 if (auto typeParams = baseClass->getTypeParamList()) {
1338 if (typeParams->size() == numProtocolsResolved) {
1339 // Note that we should be looking for type names, too.
1340 allAreTypeNames = true;
1341 }
1342 }
1343 }
1344 }
1345 }
1346
Douglas Gregore9d95f12015-07-07 03:57:35 +00001347 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001348 ObjCProtocolDecl *&proto
1349 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001350 // For an objc container, delay protocol reference checking until after we
1351 // can set the objc decl as the availability context, otherwise check now.
1352 if (!warnOnIncompleteProtocols) {
1353 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1354 }
1355
1356 // If this is a forward protocol declaration, get its definition.
1357 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1358 proto = proto->getDefinition();
1359
1360 // If this is a forward declaration and we are supposed to warn in this
1361 // case, do it.
1362 // FIXME: Recover nicely in the hidden case.
1363 ObjCProtocolDecl *forwardDecl = nullptr;
1364 if (warnOnIncompleteProtocols &&
1365 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1366 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1367 << proto->getDeclName();
1368 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1369 << forwardDecl;
1370 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001371
1372 // If everything this far has been a type name (and we care
1373 // about such things), check whether this name refers to a type
1374 // as well.
1375 if (allAreTypeNames) {
1376 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1377 LookupOrdinaryName)) {
1378 if (isa<ObjCInterfaceDecl>(decl)) {
1379 if (firstClassNameLoc.isInvalid())
1380 firstClassNameLoc = identifierLocs[i];
1381 } else if (!isa<TypeDecl>(decl)) {
1382 // Not a type.
1383 allAreTypeNames = false;
1384 }
1385 } else {
1386 allAreTypeNames = false;
1387 }
1388 }
1389 }
1390
1391 // All of the protocols listed also have type names, and at least
1392 // one is an Objective-C class name. Check whether all of the
1393 // protocol conformances are declared by the base class itself, in
1394 // which case we warn.
1395 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1396 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1397 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1398 bool allProtocolsDeclared = true;
1399 for (auto proto : protocols) {
1400 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1401 allProtocolsDeclared = false;
1402 break;
1403 }
1404 }
1405
1406 if (allProtocolsDeclared) {
1407 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1408 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001409 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1410 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001411 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001412 }
1413
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001414 protocolLAngleLoc = lAngleLoc;
1415 protocolRAngleLoc = rAngleLoc;
1416 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001417 };
1418
1419 // Attempt to resolve all of the identifiers as protocols.
1420 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1421 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1422 protocols.push_back(proto);
1423 if (proto)
1424 ++numProtocolsResolved;
1425 }
1426
1427 // If all of the names were protocols, these were protocol qualifiers.
1428 if (numProtocolsResolved == identifiers.size())
1429 return resolvedAsProtocols();
1430
1431 // Attempt to resolve all of the identifiers as type names or
1432 // Objective-C class names. The latter is technically ill-formed,
1433 // but is probably something like \c NSArray<NSView *> missing the
1434 // \c*.
1435 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1436 SmallVector<TypeOrClassDecl, 4> typeDecls;
1437 unsigned numTypeDeclsResolved = 0;
1438 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1439 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1440 LookupOrdinaryName);
1441 if (!decl) {
1442 typeDecls.push_back(TypeOrClassDecl());
1443 continue;
1444 }
1445
1446 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1447 typeDecls.push_back(typeDecl);
1448 ++numTypeDeclsResolved;
1449 continue;
1450 }
1451
1452 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1453 typeDecls.push_back(objcClass);
1454 ++numTypeDeclsResolved;
1455 continue;
1456 }
1457
1458 typeDecls.push_back(TypeOrClassDecl());
1459 }
1460
1461 AttributeFactory attrFactory;
1462
1463 // Local function that forms a reference to the given type or
1464 // Objective-C class declaration.
1465 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1466 -> TypeResult {
1467 // Form declaration specifiers. They simply refer to the type.
1468 DeclSpec DS(attrFactory);
1469 const char* prevSpec; // unused
1470 unsigned diagID; // unused
1471 QualType type;
1472 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1473 type = Context.getTypeDeclType(actualTypeDecl);
1474 else
1475 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1476 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1477 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1478 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1479 parsedType, Context.getPrintingPolicy());
1480 // Use the identifier location for the type source range.
1481 DS.SetRangeStart(loc);
1482 DS.SetRangeEnd(loc);
1483
1484 // Form the declarator.
1485 Declarator D(DS, Declarator::TypeNameContext);
1486
1487 // If we have a typedef of an Objective-C class type that is missing a '*',
1488 // add the '*'.
1489 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001490 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001491 ParsedAttributes parsedAttrs(attrFactory);
1492 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1493 SourceLocation(),
1494 SourceLocation(),
1495 SourceLocation(),
1496 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001497 parsedAttrs,
1498 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001499
1500 // Diagnose the missing '*'.
1501 Diag(loc, diag::err_objc_type_arg_missing_star)
1502 << type
1503 << FixItHint::CreateInsertion(starLoc, " *");
1504 }
1505
1506 // Convert this to a type.
1507 return ActOnTypeName(S, D);
1508 };
1509
1510 // Local function that updates the declaration specifiers with
1511 // type argument information.
1512 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001513 // We did not resolve these as protocols.
1514 protocols.clear();
1515
Douglas Gregore9d95f12015-07-07 03:57:35 +00001516 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1517 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001518 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1519 // Map type reference to a type.
1520 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001521 if (!type.isUsable()) {
1522 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001523 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001524 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001525
1526 typeArgs.push_back(type.get());
1527 }
1528
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001529 typeArgsLAngleLoc = lAngleLoc;
1530 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001531 };
1532
1533 // If all of the identifiers can be resolved as type names or
1534 // Objective-C class names, we have type arguments.
1535 if (numTypeDeclsResolved == identifiers.size())
1536 return resolvedAsTypeDecls();
1537
1538 // Error recovery: some names weren't found, or we have a mix of
1539 // type and protocol names. Go resolve all of the unresolved names
1540 // and complain if we can't find a consistent answer.
1541 LookupNameKind lookupKind = LookupAnyName;
1542 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1543 // If we already have a protocol or type. Check whether it is the
1544 // right thing.
1545 if (protocols[i] || typeDecls[i]) {
1546 // If we haven't figured out whether we want types or protocols
1547 // yet, try to figure it out from this name.
1548 if (lookupKind == LookupAnyName) {
1549 // If this name refers to both a protocol and a type (e.g., \c
1550 // NSObject), don't conclude anything yet.
1551 if (protocols[i] && typeDecls[i])
1552 continue;
1553
1554 // Otherwise, let this name decide whether we'll be correcting
1555 // toward types or protocols.
1556 lookupKind = protocols[i] ? LookupObjCProtocolName
1557 : LookupOrdinaryName;
1558 continue;
1559 }
1560
1561 // If we want protocols and we have a protocol, there's nothing
1562 // more to do.
1563 if (lookupKind == LookupObjCProtocolName && protocols[i])
1564 continue;
1565
1566 // If we want types and we have a type declaration, there's
1567 // nothing more to do.
1568 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1569 continue;
1570
1571 // We have a conflict: some names refer to protocols and others
1572 // refer to types.
1573 Diag(identifierLocs[i], diag::err_objc_type_args_and_protocols)
1574 << (protocols[i] != nullptr)
1575 << identifiers[i]
1576 << identifiers[0]
1577 << SourceRange(identifierLocs[0]);
1578
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001579 protocols.clear();
1580 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001581 return;
1582 }
1583
1584 // Perform typo correction on the name.
1585 TypoCorrection corrected = CorrectTypo(
1586 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1587 nullptr,
1588 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1589 lookupKind),
1590 CTK_ErrorRecovery);
1591 if (corrected) {
1592 // Did we find a protocol?
1593 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1594 diagnoseTypo(corrected,
1595 PDiag(diag::err_undeclared_protocol_suggest)
1596 << identifiers[i]);
1597 lookupKind = LookupObjCProtocolName;
1598 protocols[i] = proto;
1599 ++numProtocolsResolved;
1600 continue;
1601 }
1602
1603 // Did we find a type?
1604 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1605 diagnoseTypo(corrected,
1606 PDiag(diag::err_unknown_typename_suggest)
1607 << identifiers[i]);
1608 lookupKind = LookupOrdinaryName;
1609 typeDecls[i] = typeDecl;
1610 ++numTypeDeclsResolved;
1611 continue;
1612 }
1613
1614 // Did we find an Objective-C class?
1615 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1616 diagnoseTypo(corrected,
1617 PDiag(diag::err_unknown_type_or_class_name_suggest)
1618 << identifiers[i] << true);
1619 lookupKind = LookupOrdinaryName;
1620 typeDecls[i] = objcClass;
1621 ++numTypeDeclsResolved;
1622 continue;
1623 }
1624 }
1625
1626 // We couldn't find anything.
1627 Diag(identifierLocs[i],
1628 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1629 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1630 : diag::err_unknown_typename))
1631 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001632 protocols.clear();
1633 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001634 return;
1635 }
1636
1637 // If all of the names were (corrected to) protocols, these were
1638 // protocol qualifiers.
1639 if (numProtocolsResolved == identifiers.size())
1640 return resolvedAsProtocols();
1641
1642 // Otherwise, all of the names were (corrected to) types.
1643 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1644 return resolvedAsTypeDecls();
1645}
1646
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001647/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001648/// a class method in its extension.
1649///
Mike Stump11289f42009-09-09 15:08:12 +00001650void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001651 ObjCInterfaceDecl *ID) {
1652 if (!ID)
1653 return; // Possibly due to previous error
1654
1655 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001656 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001657 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001658
1659 if (MethodMap.empty())
1660 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001661 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001662 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001663 if (PrevMethod &&
1664 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1665 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001666 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1667 << Method->getDeclName();
1668 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1669 }
1670 }
1671}
1672
James Dennett634962f2012-06-14 21:40:34 +00001673/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001674Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001675Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001676 ArrayRef<IdentifierLocPair> IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001677 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001678 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001679 for (const IdentifierLocPair &IdentPair : IdentList) {
1680 IdentifierInfo *Ident = IdentPair.first;
1681 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Douglas Gregor32c17572012-01-01 20:30:41 +00001682 ForRedeclaration);
1683 ObjCProtocolDecl *PDecl
1684 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001685 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001686 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001687
1688 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001689 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001690
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001691 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001692 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001693
1694 if (PrevDecl)
1695 mergeDeclAttributes(PDecl, PrevDecl);
1696
Douglas Gregorf6102672012-01-01 21:23:57 +00001697 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001698 }
Mike Stump11289f42009-09-09 15:08:12 +00001699
Rafael Espindolaab417692013-07-09 12:05:01 +00001700 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001701}
1702
John McCall48871652010-08-21 09:40:31 +00001703Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001704ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1705 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001706 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001707 IdentifierInfo *CategoryName,
1708 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001709 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001710 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001711 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001712 SourceLocation EndProtoLoc) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001713 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001714 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001715
1716 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001717
1718 if (!IDecl
1719 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001720 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001721 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001722 // Create an invalid ObjCCategoryDecl to serve as context for
1723 // the enclosing method declarations. We mark the decl invalid
1724 // to make it clear that this isn't a valid AST.
1725 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001726 ClassLoc, CategoryLoc, CategoryName,
1727 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001728 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001729 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001730
1731 if (!IDecl)
1732 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001733 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001734 }
1735
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001736 if (!CategoryName && IDecl->getImplementation()) {
1737 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1738 Diag(IDecl->getImplementation()->getLocation(),
1739 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001740 }
1741
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001742 if (CategoryName) {
1743 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001744 if (ObjCCategoryDecl *Previous
1745 = IDecl->FindCategoryDeclaration(CategoryName)) {
1746 // Class extensions can be declared multiple times, categories cannot.
1747 Diag(CategoryLoc, diag::warn_dup_category_def)
1748 << ClassName << CategoryName;
1749 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001750 }
1751 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001752
Douglas Gregor85f3f952015-07-07 03:57:15 +00001753 // If we have a type parameter list, check it.
1754 if (typeParamList) {
1755 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1756 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1757 CategoryName
1758 ? TypeParamListContext::Category
1759 : TypeParamListContext::Extension))
1760 typeParamList = nullptr;
1761 } else {
1762 Diag(typeParamList->getLAngleLoc(),
1763 diag::err_objc_parameterized_category_nonclass)
1764 << (CategoryName != nullptr)
1765 << ClassName
1766 << typeParamList->getSourceRange();
1767
1768 typeParamList = nullptr;
1769 }
1770 }
1771
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001772 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001773 ClassLoc, CategoryLoc, CategoryName, IDecl,
1774 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001775 // FIXME: PushOnScopeChains?
1776 CurContext->addDecl(CDecl);
1777
Chris Lattnerda463fe2007-12-12 07:09:47 +00001778 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001779 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1780 NumProtoRefs, ProtoLocs);
1781 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001782 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001783 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001784 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001785 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001786 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001787 }
Mike Stump11289f42009-09-09 15:08:12 +00001788
Anders Carlssona6b508a2008-11-04 16:57:32 +00001789 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001790 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001791}
1792
1793/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001794/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001795/// object.
John McCall48871652010-08-21 09:40:31 +00001796Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001797 SourceLocation AtCatImplLoc,
1798 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1799 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001800 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001801 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001802 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001803 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1804 if (!CatIDecl) {
1805 // Category @implementation with no corresponding @interface.
1806 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001807 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1808 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001809 CatName, IDecl,
1810 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001811 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001812 }
1813 }
1814
Mike Stump11289f42009-09-09 15:08:12 +00001815 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001816 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001817 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001818 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001819 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001820 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001821 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001822 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1823 diag::err_undef_interface)) {
1824 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001825 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001826
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001827 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001828 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001829
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +00001830 // If the interface is deprecated/unavailable, warn/error about it.
1831 if (IDecl)
1832 DiagnoseUseOfDecl(IDecl, ClassLoc);
1833
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001834 /// Check that CatName, category name, is not used in another implementation.
1835 if (CatIDecl) {
1836 if (CatIDecl->getImplementation()) {
1837 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1838 << CatName;
1839 Diag(CatIDecl->getImplementation()->getLocation(),
1840 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001841 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001842 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001843 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001844 // Warn on implementating category of deprecated class under
1845 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001846 DiagnoseObjCImplementedDeprecations(*this,
1847 dyn_cast<NamedDecl>(IDecl),
1848 CDecl->getLocation(), 2);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001849 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001850 }
Mike Stump11289f42009-09-09 15:08:12 +00001851
Anders Carlssona6b508a2008-11-04 16:57:32 +00001852 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001853 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001854}
1855
John McCall48871652010-08-21 09:40:31 +00001856Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001857 SourceLocation AtClassImplLoc,
1858 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001859 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001860 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001861 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001862 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001863 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001864 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1865 ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001866 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001867 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001868 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001869 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001870 // FIXME: This will produce an error if the definition of the interface has
1871 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001872 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1873 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001874 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001875 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001876 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001877 TypoCorrection Corrected = CorrectTypo(
1878 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1879 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001880 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1881 // Suggest the (potentially) correct interface name. Don't provide a
1882 // code-modification hint or use the typo name for recovery, because
1883 // this is just a warning. The program may actually be correct.
1884 diagnoseTypo(Corrected,
1885 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1886 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001887 } else {
1888 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1889 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001890 }
Mike Stump11289f42009-09-09 15:08:12 +00001891
Chris Lattnerda463fe2007-12-12 07:09:47 +00001892 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001893 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001894 if (SuperClassname) {
1895 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001896 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1897 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001898 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001899 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1900 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001901 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001902 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001903 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001904 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001905 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001906 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001907 Diag(SuperClassLoc, diag::err_undef_superclass)
1908 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001909 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001910 // This implementation and its interface do not have the same
1911 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001912 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001913 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001914 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001915 }
1916 }
1917 }
Mike Stump11289f42009-09-09 15:08:12 +00001918
Chris Lattnerda463fe2007-12-12 07:09:47 +00001919 if (!IDecl) {
1920 // Legacy case of @implementation with no corresponding @interface.
1921 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001922
Mike Stump87c57ac2009-05-16 07:39:55 +00001923 // FIXME: Do we support attributes on the @implementation? If so we should
1924 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001925 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001926 ClassName, /*typeParamList=*/nullptr,
1927 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001928 true);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001929 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00001930 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001931 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1932 Context.getObjCInterfaceType(SDecl),
1933 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00001934 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1935 } else {
1936 IDecl->setEndOfDefinitionLoc(ClassLoc);
1937 }
1938
Douglas Gregorac345a32009-04-24 00:16:12 +00001939 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00001940 } else {
1941 // Mark the interface as being completed, even if it was just as
1942 // @class ....;
1943 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001944 if (!IDecl->hasDefinition())
1945 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001946 }
Mike Stump11289f42009-09-09 15:08:12 +00001947
1948 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001949 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00001950 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001951
Anders Carlssona6b508a2008-11-04 16:57:32 +00001952 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001953 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001954
Chris Lattnerda463fe2007-12-12 07:09:47 +00001955 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00001956 if (IDecl->getImplementation()) {
1957 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001958 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001959 Diag(IDecl->getImplementation()->getLocation(),
1960 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001961 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00001962 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001963 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00001964 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001965 // Warn on implementating deprecated class under
1966 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001967 DiagnoseObjCImplementedDeprecations(*this,
1968 dyn_cast<NamedDecl>(IDecl),
1969 IMPDecl->getLocation(), 1);
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001970 }
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001971 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001972}
1973
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001974Sema::DeclGroupPtrTy
1975Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1976 SmallVector<Decl *, 64> DeclsInGroup;
1977 DeclsInGroup.reserve(Decls.size() + 1);
1978
1979 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1980 Decl *Dcl = Decls[i];
1981 if (!Dcl)
1982 continue;
1983 if (Dcl->getDeclContext()->isFileContext())
1984 Dcl->setTopLevelDeclInObjCContainer();
1985 DeclsInGroup.push_back(Dcl);
1986 }
1987
1988 DeclsInGroup.push_back(ObjCImpDecl);
1989
Rafael Espindolaab417692013-07-09 12:05:01 +00001990 return BuildDeclaratorGroup(DeclsInGroup, false);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001991}
1992
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001993void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1994 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001995 SourceLocation RBrace) {
1996 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001997 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001998 if (!IDecl)
1999 return;
James Dennett634962f2012-06-14 21:40:34 +00002000 /// Check case of non-existing \@interface decl.
2001 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002002 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002003 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002004 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002005 // Add ivar's to class's DeclContext.
2006 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002007 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002008 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002009 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002010 }
2011
Chris Lattnerda463fe2007-12-12 07:09:47 +00002012 return;
2013 }
2014 // If implementation has empty ivar list, just return.
2015 if (numIvars == 0)
2016 return;
Mike Stump11289f42009-09-09 15:08:12 +00002017
Chris Lattnerda463fe2007-12-12 07:09:47 +00002018 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002019 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002020 if (ImpDecl->getSuperClass())
2021 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2022 for (unsigned i = 0; i < numIvars; i++) {
2023 ObjCIvarDecl* ImplIvar = ivars[i];
2024 if (const ObjCIvarDecl *ClsIvar =
2025 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2026 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2027 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2028 continue;
2029 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002030 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002031 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002032 if (const ObjCIvarDecl *ClsExtIvar =
2033 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2034 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2035 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2036 continue;
2037 }
2038 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002039 // Instance ivar to Implementation's DeclContext.
2040 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002041 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002042 ImpDecl->addDecl(ImplIvar);
2043 }
2044 return;
2045 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002046 // Check interface's Ivar list against those in the implementation.
2047 // names and types must match.
2048 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002049 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002050 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002051 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2052 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002053 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002054 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002055 assert (ImplIvar && "missing implementation ivar");
2056 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002057
Steve Naroff157599f2009-03-03 14:49:36 +00002058 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002059 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002060 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002061 << ImplIvar->getIdentifier()
2062 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002063 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002064 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2065 ImplIvar->getBitWidthValue(Context) !=
2066 ClsIvar->getBitWidthValue(Context)) {
2067 Diag(ImplIvar->getBitWidth()->getLocStart(),
2068 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2069 Diag(ClsIvar->getBitWidth()->getLocStart(),
2070 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002071 }
Steve Naroff157599f2009-03-03 14:49:36 +00002072 // Make sure the names are identical.
2073 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002074 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002075 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002076 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002077 }
2078 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002079 }
Mike Stump11289f42009-09-09 15:08:12 +00002080
Chris Lattner0f29d982007-12-12 18:11:49 +00002081 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002082 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002083 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002084 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002085}
2086
Ted Kremenekf87decd2013-12-13 05:58:44 +00002087static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2088 ObjCMethodDecl *method,
2089 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002090 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002091 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002092 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002093 switch (method->getAvailability()) {
2094 case AR_Available:
2095 case AR_Deprecated:
2096 break;
2097
2098 // Don't warn about unavailable or not-yet-introduced methods.
2099 case AR_NotYetIntroduced:
2100 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002101 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002102 }
2103
Ted Kremenek65d63572013-03-27 00:02:21 +00002104 // FIXME: For now ignore 'IncompleteImpl'.
2105 // Previously we grouped all unimplemented methods under a single
2106 // warning, but some users strongly voiced that they would prefer
2107 // separate warnings. We will give that approach a try, as that
2108 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002109 {
2110 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2111 B << method;
2112 if (NeededFor)
2113 B << NeededFor;
2114 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002115
2116 // Issue a note to the original declaration.
2117 SourceLocation MethodLoc = method->getLocStart();
2118 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002119 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002120}
2121
David Chisnallb62d15c2010-10-25 17:23:52 +00002122/// Determines if type B can be substituted for type A. Returns true if we can
2123/// guarantee that anything that the user will do to an object of type A can
2124/// also be done to an object of type B. This is trivially true if the two
2125/// types are the same, or if B is a subclass of A. It becomes more complex
2126/// in cases where protocols are involved.
2127///
2128/// Object types in Objective-C describe the minimum requirements for an
2129/// object, rather than providing a complete description of a type. For
2130/// example, if A is a subclass of B, then B* may refer to an instance of A.
2131/// The principle of substitutability means that we may use an instance of A
2132/// anywhere that we may use an instance of B - it will implement all of the
2133/// ivars of B and all of the methods of B.
2134///
2135/// This substitutability is important when type checking methods, because
2136/// the implementation may have stricter type definitions than the interface.
2137/// The interface specifies minimum requirements, but the implementation may
2138/// have more accurate ones. For example, a method may privately accept
2139/// instances of B, but only publish that it accepts instances of A. Any
2140/// object passed to it will be type checked against B, and so will implicitly
2141/// by a valid A*. Similarly, a method may return a subclass of the class that
2142/// it is declared as returning.
2143///
2144/// This is most important when considering subclassing. A method in a
2145/// subclass must accept any object as an argument that its superclass's
2146/// implementation accepts. It may, however, accept a more general type
2147/// without breaking substitutability (i.e. you can still use the subclass
2148/// anywhere that you can use the superclass, but not vice versa). The
2149/// converse requirement applies to return types: the return type for a
2150/// subclass method must be a valid object of the kind that the superclass
2151/// advertises, but it may be specified more accurately. This avoids the need
2152/// for explicit down-casting by callers.
2153///
2154/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002155static bool isObjCTypeSubstitutable(ASTContext &Context,
2156 const ObjCObjectPointerType *A,
2157 const ObjCObjectPointerType *B,
2158 bool rejectId) {
2159 // Reject a protocol-unqualified id.
2160 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002161
2162 // If B is a qualified id, then A must also be a qualified id and it must
2163 // implement all of the protocols in B. It may not be a qualified class.
2164 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2165 // stricter definition so it is not substitutable for id<A>.
2166 if (B->isObjCQualifiedIdType()) {
2167 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002168 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2169 QualType(B,0),
2170 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002171 }
2172
2173 /*
2174 // id is a special type that bypasses type checking completely. We want a
2175 // warning when it is used in one place but not another.
2176 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2177
2178
2179 // If B is a qualified id, then A must also be a qualified id (which it isn't
2180 // if we've got this far)
2181 if (B->isObjCQualifiedIdType()) return false;
2182 */
2183
2184 // Now we know that A and B are (potentially-qualified) class types. The
2185 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002186 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002187}
2188
John McCall071df462010-10-28 02:34:38 +00002189static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2190 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2191}
2192
Douglas Gregor813a0662015-06-19 18:14:38 +00002193/// Determine whether two set of Objective-C declaration qualifiers conflict.
2194static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2195 Decl::ObjCDeclQualifier y) {
2196 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2197 (y & ~Decl::OBJC_TQ_CSNullability);
2198}
2199
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002200static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002201 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002202 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002203 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002204 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002205 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002206 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002207 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2208 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002209 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002210 S.Diag(MethodImpl->getLocation(),
2211 (IsOverridingMode
2212 ? diag::warn_conflicting_overriding_ret_type_modifiers
2213 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002214 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002215 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002216 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002217 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002218 }
2219 else
2220 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002221 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002222 if (Warn && IsOverridingMode &&
2223 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2224 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2225 MethodDecl->getReturnType(),
2226 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002227 auto nullabilityMethodImpl =
2228 *MethodImpl->getReturnType()->getNullability(S.Context);
2229 auto nullabilityMethodDecl =
2230 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002231 S.Diag(MethodImpl->getLocation(),
2232 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002233 << DiagNullabilityKind(
2234 nullabilityMethodImpl,
2235 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2236 != 0))
2237 << DiagNullabilityKind(
2238 nullabilityMethodDecl,
2239 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2240 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002241 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2242 }
2243
Alp Toker314cc812014-01-25 16:55:45 +00002244 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2245 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002246 return true;
2247 if (!Warn)
2248 return false;
John McCall071df462010-10-28 02:34:38 +00002249
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002250 unsigned DiagID =
2251 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2252 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002253
2254 // Mismatches between ObjC pointers go into a different warning
2255 // category, and sometimes they're even completely whitelisted.
2256 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002257 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002258 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002259 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002260 // Allow non-matching return types as long as they don't violate
2261 // the principle of substitutability. Specifically, we permit
2262 // return types that are subclasses of the declared return type,
2263 // or that are more-qualified versions of the declared type.
2264 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002265 return false;
John McCall071df462010-10-28 02:34:38 +00002266
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002267 DiagID =
2268 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002269 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002270 }
2271 }
2272
2273 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002274 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2275 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002276 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002277 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2278 ? diag::note_previous_declaration
2279 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002280 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002281 return false;
John McCall071df462010-10-28 02:34:38 +00002282}
2283
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002284static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002285 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002286 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002287 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002288 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002289 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002290 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002291 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002292 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002293 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2294 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002295 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002296 if (IsOverridingMode)
2297 S.Diag(ImplVar->getLocation(),
2298 diag::warn_conflicting_overriding_param_modifiers)
2299 << getTypeRange(ImplVar->getTypeSourceInfo())
2300 << MethodImpl->getDeclName();
2301 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002302 diag::warn_conflicting_param_modifiers)
2303 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002304 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002305 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2306 << getTypeRange(IfaceVar->getTypeSourceInfo());
2307 }
2308 else
2309 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002310 }
2311
John McCall071df462010-10-28 02:34:38 +00002312 QualType ImplTy = ImplVar->getType();
2313 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002314 if (Warn && IsOverridingMode &&
2315 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2316 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002317 S.Diag(ImplVar->getLocation(),
2318 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002319 << DiagNullabilityKind(
2320 *ImplTy->getNullability(S.Context),
2321 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2322 != 0))
2323 << DiagNullabilityKind(
2324 *IfaceTy->getNullability(S.Context),
2325 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2326 != 0));
2327 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002328 }
John McCall071df462010-10-28 02:34:38 +00002329 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002330 return true;
2331
2332 if (!Warn)
2333 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002334 unsigned DiagID =
2335 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2336 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002337
2338 // Mismatches between ObjC pointers go into a different warning
2339 // category, and sometimes they're even completely whitelisted.
2340 if (const ObjCObjectPointerType *ImplPtrTy =
2341 ImplTy->getAs<ObjCObjectPointerType>()) {
2342 if (const ObjCObjectPointerType *IfacePtrTy =
2343 IfaceTy->getAs<ObjCObjectPointerType>()) {
2344 // Allow non-matching argument types as long as they don't
2345 // violate the principle of substitutability. Specifically, the
2346 // implementation must accept any objects that the superclass
2347 // accepts, however it may also accept others.
2348 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002349 return false;
John McCall071df462010-10-28 02:34:38 +00002350
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002351 DiagID =
2352 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002353 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002354 }
2355 }
2356
2357 S.Diag(ImplVar->getLocation(), DiagID)
2358 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002359 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2360 S.Diag(IfaceVar->getLocation(),
2361 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002362 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002363 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002364 return false;
John McCall071df462010-10-28 02:34:38 +00002365}
John McCall31168b02011-06-15 23:02:42 +00002366
2367/// In ARC, check whether the conventional meanings of the two methods
2368/// match. If they don't, it's a hard error.
2369static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2370 ObjCMethodDecl *decl) {
2371 ObjCMethodFamily implFamily = impl->getMethodFamily();
2372 ObjCMethodFamily declFamily = decl->getMethodFamily();
2373 if (implFamily == declFamily) return false;
2374
2375 // Since conventions are sorted by selector, the only possibility is
2376 // that the types differ enough to cause one selector or the other
2377 // to fall out of the family.
2378 assert(implFamily == OMF_None || declFamily == OMF_None);
2379
2380 // No further diagnostics required on invalid declarations.
2381 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2382
2383 const ObjCMethodDecl *unmatched = impl;
2384 ObjCMethodFamily family = declFamily;
2385 unsigned errorID = diag::err_arc_lost_method_convention;
2386 unsigned noteID = diag::note_arc_lost_method_convention;
2387 if (declFamily == OMF_None) {
2388 unmatched = decl;
2389 family = implFamily;
2390 errorID = diag::err_arc_gained_method_convention;
2391 noteID = diag::note_arc_gained_method_convention;
2392 }
2393
2394 // Indexes into a %select clause in the diagnostic.
2395 enum FamilySelector {
2396 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2397 };
2398 FamilySelector familySelector = FamilySelector();
2399
2400 switch (family) {
2401 case OMF_None: llvm_unreachable("logic error, no method convention");
2402 case OMF_retain:
2403 case OMF_release:
2404 case OMF_autorelease:
2405 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002406 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002407 case OMF_retainCount:
2408 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002409 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002410 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002411 // Mismatches for these methods don't change ownership
2412 // conventions, so we don't care.
2413 return false;
2414
2415 case OMF_init: familySelector = F_init; break;
2416 case OMF_alloc: familySelector = F_alloc; break;
2417 case OMF_copy: familySelector = F_copy; break;
2418 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2419 case OMF_new: familySelector = F_new; break;
2420 }
2421
2422 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2423 ReasonSelector reasonSelector;
2424
2425 // The only reason these methods don't fall within their families is
2426 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002427 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002428 reasonSelector = R_UnrelatedReturn;
2429 } else {
2430 reasonSelector = R_NonObjectReturn;
2431 }
2432
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002433 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2434 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002435
2436 return true;
2437}
John McCall071df462010-10-28 02:34:38 +00002438
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002439void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002440 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002441 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002442 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002443 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2444 return;
2445
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002446 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002447 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002448 true);
Mike Stump11289f42009-09-09 15:08:12 +00002449
Chris Lattner67f35b02009-04-11 19:58:42 +00002450 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002451 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2452 EF = MethodDecl->param_end();
2453 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002454 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002455 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002456 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002457
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002458 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002459 Diag(ImpMethodDecl->getLocation(),
2460 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002461 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002462 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002463}
2464
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002465void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2466 ObjCMethodDecl *Overridden,
2467 bool IsProtocolMethodDecl) {
2468
2469 CheckMethodOverrideReturn(*this, Method, Overridden,
2470 IsProtocolMethodDecl, true,
2471 true);
2472
2473 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002474 IF = Overridden->param_begin(), EM = Method->param_end(),
2475 EF = Overridden->param_end();
2476 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002477 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2478 IsProtocolMethodDecl, true, true);
2479 }
2480
2481 if (Method->isVariadic() != Overridden->isVariadic()) {
2482 Diag(Method->getLocation(),
2483 diag::warn_conflicting_overriding_variadic);
2484 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2485 }
2486}
2487
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002488/// WarnExactTypedMethods - This routine issues a warning if method
2489/// implementation declaration matches exactly that of its declaration.
2490void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2491 ObjCMethodDecl *MethodDecl,
2492 bool IsProtocolMethodDecl) {
2493 // don't issue warning when protocol method is optional because primary
2494 // class is not required to implement it and it is safe for protocol
2495 // to implement it.
2496 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2497 return;
2498 // don't issue warning when primary class's method is
2499 // depecated/unavailable.
2500 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2501 MethodDecl->hasAttr<DeprecatedAttr>())
2502 return;
2503
2504 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2505 IsProtocolMethodDecl, false, false);
2506 if (match)
2507 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002508 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2509 EF = MethodDecl->param_end();
2510 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002511 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2512 *IM, *IF,
2513 IsProtocolMethodDecl, false, false);
2514 if (!match)
2515 break;
2516 }
2517 if (match)
2518 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002519 if (match)
2520 match = !(MethodDecl->isClassMethod() &&
2521 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002522
2523 if (match) {
2524 Diag(ImpMethodDecl->getLocation(),
2525 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002526 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2527 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002528 }
2529}
2530
Mike Stump87c57ac2009-05-16 07:39:55 +00002531/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2532/// improve the efficiency of selector lookups and type checking by associating
2533/// with each protocol / interface / category the flattened instance tables. If
2534/// we used an immutable set to keep the table then it wouldn't add significant
2535/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002536
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002537typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002538typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002539
2540static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2541 ProtocolNameSet &PNS) {
2542 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2543 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002544 for (const auto *PI : PDecl->protocols())
2545 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002546}
2547
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002548/// Recursively populates a set with all conformed protocols in a class
2549/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2550/// attribute.
2551static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2552 ProtocolNameSet &PNS) {
2553 if (!Super)
2554 return;
2555
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002556 for (const auto *I : Super->all_referenced_protocols())
2557 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002558
2559 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002560}
2561
Steve Naroffa36992242008-02-08 22:06:17 +00002562/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002563/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002564static void CheckProtocolMethodDefs(Sema &S,
2565 SourceLocation ImpLoc,
2566 ObjCProtocolDecl *PDecl,
2567 bool& IncompleteImpl,
2568 const Sema::SelectorSet &InsMap,
2569 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002570 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002571 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002572 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2573 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2574 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002575 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2576
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002577 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002578 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002579
2580 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2581 // then we should check if any class in the super class hierarchy also
2582 // conforms to this protocol, either directly or via protocol inheritance.
2583 // If so, we can skip checking this protocol completely because we
2584 // know that a parent class already satisfies this protocol.
2585 //
2586 // Note: we could generalize this logic for all protocols, and merely
2587 // add the limit on looking at the super class chain for just
2588 // specially marked protocols. This may be a good optimization. This
2589 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2590 // protocols for now for controlled evaluation.
2591 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002592 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002593 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2594 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2595 }
2596 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2597 ProtocolsExplictImpl->end())
2598 return;
2599
2600 // If no super class conforms to the protocol, we should not search
2601 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002602 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002603 }
2604
Ted Kremenek285ee852013-12-13 06:26:10 +00002605 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002606 // check to see if class implements forwardInvocation method and objects
2607 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002608 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002609 // Under such conditions, which means that every method possible is
2610 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002611 // found" warnings.
2612 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002613 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2614 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002615 if (InsMap.count(fISelector))
2616 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2617 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002618 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002619 }
Mike Stump11289f42009-09-09 15:08:12 +00002620
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002621 // If this is a forward protocol declaration, get its definition.
2622 if (!PDecl->isThisDeclarationADefinition() &&
2623 PDecl->getDefinition())
2624 PDecl = PDecl->getDefinition();
2625
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002626 // If a method lookup fails locally we still need to look and see if
2627 // the method was implemented by a base class or an inherited
2628 // protocol. This lookup is slow, but occurs rarely in correct code
2629 // and otherwise would terminate in a warning.
2630
Chris Lattnerda463fe2007-12-12 07:09:47 +00002631 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002632 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002633 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002634 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002635 !method->isPropertyAccessor() &&
2636 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002637 (!Super || !Super->lookupMethod(method->getSelector(),
2638 true /* instance */,
2639 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002640 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002641 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002642 // If a method is not implemented in the category implementation but
2643 // has been declared in its primary class, superclass,
2644 // or in one of their protocols, no need to issue the warning.
2645 // This is because method will be implemented in the primary class
2646 // or one of its super class implementation.
2647
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002648 // Ugly, but necessary. Method declared in protcol might have
2649 // have been synthesized due to a property declared in the class which
2650 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002651 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002652 IDecl->lookupMethod(method->getSelector(),
2653 true /* instance */,
2654 true /* shallowCategoryLookup */,
2655 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002656 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002657 continue;
2658 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002659 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002660 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002661 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002662 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002663 }
2664 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002665 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002666 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002667 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2668 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002669 (!Super || !Super->lookupMethod(method->getSelector(),
2670 false /* class method */,
2671 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002672 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002673 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002674 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002675 if (C && IDecl->lookupMethod(method->getSelector(),
2676 false /* class */,
2677 true /* shallowCategoryLookup */,
2678 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002679 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002680
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002681 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002682 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002683 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002684 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002685 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002686 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002687 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002688 for (auto *PI : PDecl->protocols())
2689 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002690 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002691}
2692
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002693/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002694/// or protocol against those declared in their implementations.
2695///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002696void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2697 const SelectorSet &ClsMap,
2698 SelectorSet &InsMapSeen,
2699 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002700 ObjCImplDecl* IMPDecl,
2701 ObjCContainerDecl* CDecl,
2702 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002703 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002704 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002705 // Check and see if instance methods in class interface have been
2706 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002707 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002708 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002709 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002710 if (!I->isPropertyAccessor() &&
2711 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002712 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002713 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002714 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002715 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002716 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002717 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002718 IMPDecl->getInstanceMethod(I->getSelector());
2719 assert(CDecl->getInstanceMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002720 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002721 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002722 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002723 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002724 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002725 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002726 else if (!I->isPropertyAccessor())
2727 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002728 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002729 }
2730 }
Mike Stump11289f42009-09-09 15:08:12 +00002731
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002732 // Check and see if class methods in class interface have been
2733 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002734 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002735 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002736 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002737 if (!I->isPropertyAccessor() &&
2738 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002739 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002740 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002741 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002742 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002743 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002744 IMPDecl->getClassMethod(I->getSelector());
2745 assert(CDecl->getClassMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002746 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002747 // ImpMethodDecl may be null as in a @dynamic property.
2748 if (ImpMethodDecl) {
2749 if (!WarnCategoryMethodImpl)
2750 WarnConflictingTypedMethods(ImpMethodDecl, I,
2751 isa<ObjCProtocolDecl>(CDecl));
2752 else if (!I->isPropertyAccessor())
2753 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2754 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002755 }
2756 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002757
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002758 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2759 // Also, check for methods declared in protocols inherited by
2760 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002761 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002762 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002763 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002764 WarnCategoryMethodImpl);
2765 }
2766
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002767 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002768 // when checking that methods in implementation match their declaration,
2769 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2770 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002771 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002772 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002773 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002774 IMPDecl, Cat, IncompleteImpl,
2775 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002776 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002777 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002778 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002779 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002780 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002781 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002782 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002783 }
2784
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002785 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002786 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002787 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002788 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002789 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002790
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002791 // FIXME. For now, we are not checking for extact match of methods
2792 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002793 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002794 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002795 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002796 I->getSuperClass(), IncompleteImpl, false);
2797 }
2798}
2799
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002800/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2801/// category matches with those implemented in its primary class and
2802/// warns each time an exact match is found.
2803void Sema::CheckCategoryVsClassMethodMatches(
2804 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002805 // Get category's primary class.
2806 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2807 if (!CatDecl)
2808 return;
2809 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2810 if (!IDecl)
2811 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002812 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2813 SelectorSet InsMap, ClsMap;
2814
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002815 for (const auto *I : CatIMPDecl->instance_methods()) {
2816 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002817 // When checking for methods implemented in the category, skip over
2818 // those declared in category class's super class. This is because
2819 // the super class must implement the method.
2820 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2821 continue;
2822 InsMap.insert(Sel);
2823 }
2824
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002825 for (const auto *I : CatIMPDecl->class_methods()) {
2826 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002827 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2828 continue;
2829 ClsMap.insert(Sel);
2830 }
2831 if (InsMap.empty() && ClsMap.empty())
2832 return;
2833
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002834 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002835 bool IncompleteImpl = false;
2836 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2837 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002838 IncompleteImpl, false,
2839 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002840}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002841
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002842void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002843 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002844 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002845 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002846 // Check and see if instance methods in class interface have been
2847 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002848 for (const auto *I : IMPDecl->instance_methods())
2849 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002850
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002851 // Add the selectors for getters/setters of @dynamic properties.
2852 for (const auto *PImpl : IMPDecl->property_impls()) {
2853 // We only care about @dynamic implementations.
2854 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2855 continue;
2856
2857 const auto *P = PImpl->getPropertyDecl();
2858 if (!P) continue;
2859
2860 InsMap.insert(P->getGetterName());
2861 if (!P->getSetterName().isNull())
2862 InsMap.insert(P->getSetterName());
2863 }
2864
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002865 // Check and see if properties declared in the interface have either 1)
2866 // an implementation or 2) there is a @synthesize/@dynamic implementation
2867 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002868 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2869 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2870 LangOpts.ObjCRuntime.isNonFragile() &&
2871 !IDecl->isObjCRequiresPropertyDefs();
2872 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2873 }
2874
Douglas Gregor849ebc22015-06-19 18:14:46 +00002875 // Diagnose null-resettable synthesized setters.
2876 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2877
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002878 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002879 for (const auto *I : IMPDecl->class_methods())
2880 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002881
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002882 // Check for type conflict of methods declared in a class/protocol and
2883 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002884 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002885 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2886 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002887 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002888
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002889 // check all methods implemented in category against those declared
2890 // in its primary class.
2891 if (ObjCCategoryImplDecl *CatDecl =
2892 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2893 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002894
Chris Lattnerda463fe2007-12-12 07:09:47 +00002895 // Check the protocol list for unimplemented methods in the @implementation
2896 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002897 // Check and see if class methods in class interface have been
2898 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002899
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002900 LazyProtocolNameSet ExplicitImplProtocols;
2901
Chris Lattner9ef10f42009-03-01 00:56:52 +00002902 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002903 for (auto *PI : I->all_referenced_protocols())
2904 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2905 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002906 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002907 // For extended class, unimplemented methods in its protocols will
2908 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002909 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002910 for (auto *P : C->protocols())
2911 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002912 IncompleteImpl, InsMap, ClsMap, CDecl,
2913 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002914 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00002915 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002916 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002917 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002918 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002919}
2920
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002921Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00002922Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00002923 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00002924 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002925 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00002926 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002927 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002928 for (unsigned i = 0; i != NumElts; ++i) {
2929 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002930 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002931 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Douglas Gregorb8eaf292010-04-15 23:40:53 +00002932 LookupOrdinaryName, ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002933 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00002934 // GCC apparently allows the following idiom:
2935 //
2936 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2937 // @class XCElementToggler;
2938 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002939 // Here we have chosen to ignore the forward class declaration
2940 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00002941 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00002942 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002943 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00002944 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00002945 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00002946 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002947 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00002948 // as this will force the intended behavior which is to lookup the
2949 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002950 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00002951 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2952 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002953 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2954 continue;
2955 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00002956 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002957 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00002958
2959 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002960 ObjCInterfaceDecl *PrevIDecl
2961 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00002962
2963 IdentifierInfo *ClassName = IdentList[i];
2964 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2965 // A previous decl with a different name is because of
2966 // @compatibility_alias, for example:
2967 // \code
2968 // @class NewImage;
2969 // @compatibility_alias OldImage NewImage;
2970 // \endcode
2971 // A lookup for 'OldImage' will return the 'NewImage' decl.
2972 //
2973 // In such a case use the real declaration name, instead of the alias one,
2974 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2975 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2976 // has been aliased.
2977 ClassName = PrevIDecl->getIdentifier();
2978 }
2979
Douglas Gregor85f3f952015-07-07 03:57:15 +00002980 // If this forward declaration has type parameters, compare them with the
2981 // type parameters of the previous declaration.
2982 ObjCTypeParamList *TypeParams = TypeParamLists[i];
2983 if (PrevIDecl && TypeParams) {
2984 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
2985 // Check for consistency with the previous declaration.
2986 if (checkTypeParamListConsistency(
2987 *this, PrevTypeParams, TypeParams,
2988 TypeParamListContext::ForwardDeclaration)) {
2989 TypeParams = nullptr;
2990 }
2991 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
2992 // The @interface does not have type parameters. Complain.
2993 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
2994 << ClassName
2995 << TypeParams->getSourceRange();
2996 Diag(Def->getLocation(), diag::note_defined_here)
2997 << ClassName;
2998
2999 TypeParams = nullptr;
3000 }
3001 }
3002
Douglas Gregordc9166c2011-12-15 20:29:51 +00003003 ObjCInterfaceDecl *IDecl
3004 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003005 ClassName, TypeParams, PrevIDecl,
3006 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003007 IDecl->setAtEndRange(IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003008
Douglas Gregordc9166c2011-12-15 20:29:51 +00003009 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003010 CheckObjCDeclScope(IDecl);
3011 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003012 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003013
3014 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003015}
3016
John McCall54507ab2011-06-16 01:15:19 +00003017static bool tryMatchRecordTypes(ASTContext &Context,
3018 Sema::MethodMatchStrategy strategy,
3019 const Type *left, const Type *right);
3020
John McCall31168b02011-06-15 23:02:42 +00003021static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3022 QualType leftQT, QualType rightQT) {
3023 const Type *left =
3024 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3025 const Type *right =
3026 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3027
3028 if (left == right) return true;
3029
3030 // If we're doing a strict match, the types have to match exactly.
3031 if (strategy == Sema::MMS_strict) return false;
3032
3033 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3034
3035 // Otherwise, use this absurdly complicated algorithm to try to
3036 // validate the basic, low-level compatibility of the two types.
3037
3038 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003039 TypeInfo LeftTI = Context.getTypeInfo(left);
3040 TypeInfo RightTI = Context.getTypeInfo(right);
3041 if (LeftTI.Width != RightTI.Width)
3042 return false;
3043
3044 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003045 return false;
3046
3047 // Consider all the kinds of non-dependent canonical types:
3048 // - functions and arrays aren't possible as return and parameter types
3049
3050 // - vector types of equal size can be arbitrarily mixed
3051 if (isa<VectorType>(left)) return isa<VectorType>(right);
3052 if (isa<VectorType>(right)) return false;
3053
3054 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003055 // - structs, unions, and Objective-C objects must match more-or-less
3056 // exactly
John McCall31168b02011-06-15 23:02:42 +00003057 // - everything else should be a scalar
3058 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003059 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003060
John McCall9320b872011-09-09 05:25:32 +00003061 // Make scalars agree in kind, except count bools as chars, and group
3062 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003063 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3064 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3065 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3066 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003067 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3068 leftSK = Type::STK_ObjCObjectPointer;
3069 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3070 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003071
3072 // Note that data member pointers and function member pointers don't
3073 // intermix because of the size differences.
3074
3075 return (leftSK == rightSK);
3076}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003077
John McCall54507ab2011-06-16 01:15:19 +00003078static bool tryMatchRecordTypes(ASTContext &Context,
3079 Sema::MethodMatchStrategy strategy,
3080 const Type *lt, const Type *rt) {
3081 assert(lt && rt && lt != rt);
3082
3083 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3084 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3085 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3086
3087 // Require union-hood to match.
3088 if (left->isUnion() != right->isUnion()) return false;
3089
3090 // Require an exact match if either is non-POD.
3091 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3092 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3093 return false;
3094
3095 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003096 TypeInfo LeftTI = Context.getTypeInfo(lt);
3097 TypeInfo RightTI = Context.getTypeInfo(rt);
3098 if (LeftTI.Width != RightTI.Width)
3099 return false;
3100
3101 if (LeftTI.Align != RightTI.Align)
3102 return false;
John McCall54507ab2011-06-16 01:15:19 +00003103
3104 // Require fields to match.
3105 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3106 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3107 for (; li != le && ri != re; ++li, ++ri) {
3108 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3109 return false;
3110 }
3111 return (li == le && ri == re);
3112}
3113
Chris Lattnerda463fe2007-12-12 07:09:47 +00003114/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3115/// returns true, or false, accordingly.
3116/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003117bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3118 const ObjCMethodDecl *right,
3119 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003120 if (!matchTypes(Context, strategy, left->getReturnType(),
3121 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003122 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003123
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003124 // If either is hidden, it is not considered to match.
3125 if (left->isHidden() || right->isHidden())
3126 return false;
3127
David Blaikiebbafb8a2012-03-11 07:00:24 +00003128 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003129 (left->hasAttr<NSReturnsRetainedAttr>()
3130 != right->hasAttr<NSReturnsRetainedAttr>() ||
3131 left->hasAttr<NSConsumesSelfAttr>()
3132 != right->hasAttr<NSConsumesSelfAttr>()))
3133 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003134
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003135 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003136 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3137 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003138
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003139 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003140 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003141 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003142
3143 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3144 return false;
3145
David Blaikiebbafb8a2012-03-11 07:00:24 +00003146 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003147 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3148 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003149 }
3150 return true;
3151}
3152
Nico Weber2e0c8f72014-12-27 03:58:08 +00003153void Sema::addMethodToGlobalList(ObjCMethodList *List,
3154 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003155 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3156 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003157 if (ObjCCategoryDecl *CD =
3158 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003159 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003160 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003161
Douglas Gregorc454afe2012-01-25 00:19:56 +00003162 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003163 if (List->getMethod() == nullptr) {
3164 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003165 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003166 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003167 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003168
Douglas Gregorc454afe2012-01-25 00:19:56 +00003169 // We've seen a method with this name, see if we have already seen this type
3170 // signature.
3171 ObjCMethodList *Previous = List;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003172 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003173 // If we are building a module, keep all of the methods.
3174 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
3175 continue;
3176
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003177 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) {
3178 // Even if two method types do not match, we would like to say
3179 // there is more than one declaration so unavailability/deprecated
3180 // warning is not too noisy.
3181 if (!Method->isDefined())
3182 List->setHasMoreThanOneDecl(true);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003183 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003184 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003185
3186 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003187
3188 // Propagate the 'defined' bit.
3189 if (Method->isDefined())
3190 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003191 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003192 // Objective-C doesn't allow an @interface for a class after its
3193 // @implementation. So if Method is not defined and there already is
3194 // an entry for this type signature, Method has to be for a different
3195 // class than PrevObjCMethod.
3196 List->setHasMoreThanOneDecl(true);
3197 }
3198
Douglas Gregorc454afe2012-01-25 00:19:56 +00003199 // If a method is deprecated, push it in the global pool.
3200 // This is used for better diagnostics.
3201 if (Method->isDeprecated()) {
3202 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003203 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003204 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003205 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003206 // unless previous one is deprecated.
3207 if (Method->isUnavailable()) {
3208 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003209 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003210 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003211
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003212 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003213 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003214
Douglas Gregorc454afe2012-01-25 00:19:56 +00003215 // We have a new signature for an existing method - add it.
3216 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003217 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Nico Weber2e0c8f72014-12-27 03:58:08 +00003218 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003219}
3220
Sebastian Redl75d8a322010-08-02 23:18:59 +00003221/// \brief Read the contents of the method pool for a given selector from
3222/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003223void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003224 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003225 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003226}
3227
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003228void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003229 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003230 // Ignore methods of invalid containers.
3231 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003232 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003233
Douglas Gregor70f449b2012-01-25 00:59:09 +00003234 if (ExternalSource)
3235 ReadMethodPool(Method->getSelector());
3236
Sebastian Redl75d8a322010-08-02 23:18:59 +00003237 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003238 if (Pos == MethodPool.end())
3239 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3240 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003241
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003242 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003243
Sebastian Redl75d8a322010-08-02 23:18:59 +00003244 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003245 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003246}
3247
John McCall31168b02011-06-15 23:02:42 +00003248/// Determines if this is an "acceptable" loose mismatch in the global
3249/// method pool. This exists mostly as a hack to get around certain
3250/// global mismatches which we can't afford to make warnings / errors.
3251/// Really, what we want is a way to take a method out of the global
3252/// method pool.
3253static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3254 ObjCMethodDecl *other) {
3255 if (!chosen->isInstanceMethod())
3256 return false;
3257
3258 Selector sel = chosen->getSelector();
3259 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3260 return false;
3261
3262 // Don't complain about mismatches for -length if the method we
3263 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003264 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003265}
3266
Nico Weber2e0c8f72014-12-27 03:58:08 +00003267bool Sema::CollectMultipleMethodsInGlobalPool(
3268 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003269 if (ExternalSource)
3270 ReadMethodPool(Sel);
3271
3272 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3273 if (Pos == MethodPool.end())
3274 return false;
3275 // Gather the non-hidden methods.
3276 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3277 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003278 if (M->getMethod() && !M->getMethod()->isHidden())
3279 Methods.push_back(M->getMethod());
3280 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003281}
3282
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003283bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3284 SourceRange R,
3285 bool receiverIdOrClass) {
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003286 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003287 // Test for no method in the pool which should not trigger any warning by
3288 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003289 if (Pos == MethodPool.end())
3290 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003291 ObjCMethodList &MethList =
3292 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3293
3294 // Diagnose finding more than one method in global pool
3295 SmallVector<ObjCMethodDecl *, 4> Methods;
3296 Methods.push_back(BestMethod);
Jonathan Roelofs74411362015-04-28 18:04:44 +00003297 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext())
3298 if (ObjCMethodDecl *M = ML->getMethod())
3299 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>())
3300 Methods.push_back(M);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003301 if (Methods.size() > 1)
3302 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass);
3303
Nico Weber2e0c8f72014-12-27 03:58:08 +00003304 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003305}
3306
Sebastian Redl75d8a322010-08-02 23:18:59 +00003307ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003308 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003309 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003310 if (ExternalSource)
3311 ReadMethodPool(Sel);
3312
Sebastian Redl75d8a322010-08-02 23:18:59 +00003313 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003314 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003315 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003316
Douglas Gregor77f49a42013-01-16 18:47:38 +00003317 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003318 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003319 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003320 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003321 if (M->getMethod() && !M->getMethod()->isHidden())
3322 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003323 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003324 return nullptr;
3325}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003326
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003327void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3328 Selector Sel, SourceRange R,
3329 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003330 // We found multiple methods, so we may have to complain.
3331 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003332
Douglas Gregor77f49a42013-01-16 18:47:38 +00003333 // We support a warning which complains about *any* difference in
3334 // method signature.
3335 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003336 receiverIdOrClass &&
3337 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003338 if (strictSelectorMatch) {
3339 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3340 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3341 issueDiagnostic = true;
3342 break;
3343 }
3344 }
3345 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003346
Douglas Gregor77f49a42013-01-16 18:47:38 +00003347 // If we didn't see any strict differences, we won't see any loose
3348 // differences. In ARC, however, we also need to check for loose
3349 // mismatches, because most of them are errors.
3350 if (!strictSelectorMatch ||
3351 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3352 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3353 // This checks if the methods differ in type mismatch.
3354 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3355 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3356 issueDiagnostic = true;
3357 if (getLangOpts().ObjCAutoRefCount)
3358 issueError = true;
3359 break;
3360 }
3361 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003362
Douglas Gregor77f49a42013-01-16 18:47:38 +00003363 if (issueDiagnostic) {
3364 if (issueError)
3365 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3366 else if (strictSelectorMatch)
3367 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3368 else
3369 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003370
Douglas Gregor77f49a42013-01-16 18:47:38 +00003371 Diag(Methods[0]->getLocStart(),
3372 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003373 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003374 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3375 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003376 << Methods[I]->getSourceRange();
3377 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003378 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003379}
3380
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003381ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003382 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3383 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003384 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003385
3386 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003387 for (const ObjCMethodList *Method = &Methods.first; Method;
3388 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003389 if (Method->getMethod() &&
3390 (Method->getMethod()->isDefined() ||
3391 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003392 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003393
3394 for (const ObjCMethodList *Method = &Methods.second; Method;
3395 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003396 if (Method->getMethod() &&
3397 (Method->getMethod()->isDefined() ||
3398 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003399 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003400 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003401}
3402
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003403static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003404HelperSelectorsForTypoCorrection(
3405 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3406 StringRef Typo, const ObjCMethodDecl * Method) {
3407 const unsigned MaxEditDistance = 1;
3408 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003409 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003410
3411 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3412 if (MinPossibleEditDistance > 0 &&
3413 Typo.size() / MinPossibleEditDistance < 1)
3414 return;
3415 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3416 if (EditDistance > MaxEditDistance)
3417 return;
3418 if (EditDistance == BestEditDistance)
3419 BestMethod.push_back(Method);
3420 else if (EditDistance < BestEditDistance) {
3421 BestMethod.clear();
3422 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003423 }
3424}
3425
Fariborz Jahanian75481672013-06-17 17:10:54 +00003426static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3427 QualType ObjectType) {
3428 if (ObjectType.isNull())
3429 return true;
3430 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3431 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003432 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3433 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003434}
3435
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003436const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003437Sema::SelectorsForTypoCorrection(Selector Sel,
3438 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003439 unsigned NumArgs = Sel.getNumArgs();
3440 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003441 bool ObjectIsId = true, ObjectIsClass = true;
3442 if (ObjectType.isNull())
3443 ObjectIsId = ObjectIsClass = false;
3444 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003445 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003446 else if (const ObjCObjectPointerType *ObjCPtr =
3447 ObjectType->getAsObjCInterfacePointerType()) {
3448 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3449 ObjectIsId = ObjectIsClass = false;
3450 }
3451 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3452 ObjectIsClass = false;
3453 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3454 ObjectIsId = false;
3455 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003456 return nullptr;
3457
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003458 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3459 e = MethodPool.end(); b != e; b++) {
3460 // instance methods
3461 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003462 if (M->getMethod() &&
3463 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3464 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003465 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003466 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003467 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003468 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3469 ObjectType))
3470 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003471 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003472 // class methods
3473 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003474 if (M->getMethod() &&
3475 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3476 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003477 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003478 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003479 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003480 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3481 ObjectType))
3482 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003483 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003484 }
3485
3486 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3487 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3488 HelperSelectorsForTypoCorrection(SelectedMethods,
3489 Sel.getAsString(), Methods[i]);
3490 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003491 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003492}
3493
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003494/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003495/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003496/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003497/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003498/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003499void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3500 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003501 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003502 if (Ivar->isInvalidDecl())
3503 continue;
3504 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3505 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3506 if (prevIvar) {
3507 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3508 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3509 Ivar->setInvalidDecl();
3510 }
3511 }
3512 }
3513}
3514
John McCallb61e14e2015-10-27 04:54:50 +00003515/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3516static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3517 if (S.getLangOpts().ObjCWeak) return;
3518
3519 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3520 ivar; ivar = ivar->getNextIvar()) {
3521 if (ivar->isInvalidDecl()) continue;
3522 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3523 if (S.getLangOpts().ObjCWeakRuntime) {
3524 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3525 } else {
3526 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3527 }
3528 }
3529 }
3530}
3531
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003532Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3533 switch (CurContext->getDeclKind()) {
3534 case Decl::ObjCInterface:
3535 return Sema::OCK_Interface;
3536 case Decl::ObjCProtocol:
3537 return Sema::OCK_Protocol;
3538 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003539 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003540 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003541 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003542 case Decl::ObjCImplementation:
3543 return Sema::OCK_Implementation;
3544 case Decl::ObjCCategoryImpl:
3545 return Sema::OCK_CategoryImplementation;
3546
3547 default:
3548 return Sema::OCK_None;
3549 }
3550}
3551
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003552// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003553Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003554 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003555 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003556 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003557
3558 assert(AtEnd.isValid() && "Invalid location for '@end'");
3559
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003560 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3561 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian9290ede2009-11-16 18:57:01 +00003562
Mike Stump11289f42009-09-09 15:08:12 +00003563 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003564 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3565 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003566 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003567
Steve Naroff35c62ae2009-01-08 17:28:14 +00003568 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3569 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3570 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3571
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003572 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003573 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003574 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003575
3576 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003577 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003578 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003579 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003580 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003581 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003582 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003583 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003584 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003585 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003586 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003587 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003588 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003589 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003590 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003591 if (!Context.getSourceManager().isInSystemHeader(
3592 Method->getLocation()))
3593 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3594 << Method->getDeclName();
3595 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3596 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003597 InsMap[Method->getSelector()] = Method;
3598 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003599 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003600 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003601 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003602 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003603 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003604 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003605 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003606 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003607 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003608 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003609 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003610 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003611 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003612 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003613 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003614 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003615 if (!Context.getSourceManager().isInSystemHeader(
3616 Method->getLocation()))
3617 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3618 << Method->getDeclName();
3619 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3620 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003621 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003622 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003623 }
3624 }
3625 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003626 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3627 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003628 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003629 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003630 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003631 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003632
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003633 if (C->IsClassExtension()) {
3634 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3635 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003636 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003637 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003638 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003639 if (CDecl->getIdentifier())
3640 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3641 // user-defined setter/getter. It also synthesizes setter/getter methods
3642 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003643 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003644 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003645 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003646 }
3647 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003648 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003649 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003650 // Any property declared in a class extension might have user
3651 // declared setter or getter in current class extension or one
3652 // of the other class extensions. Mark them as synthesized as
3653 // property will be synthesized when property with same name is
3654 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003655 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003656 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003657 // Skip over properties declared @dynamic
3658 if (const ObjCPropertyImplDecl *PIDecl
3659 = IC->FindPropertyImplDecl(Property->getIdentifier()))
3660 if (PIDecl->getPropertyImplementation()
3661 == ObjCPropertyImplDecl::Dynamic)
3662 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003663
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003664 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003665 if (ObjCMethodDecl *GetterMethod
3666 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003667 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003668 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003669 if (ObjCMethodDecl *SetterMethod
3670 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003671 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003672 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003673 }
3674 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003675 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003676 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003677 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003678 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003679 if (IDecl->hasDesignatedInitializers())
3680 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00003681 DiagnoseWeakIvars(*this, IC);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003682
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003683 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00003684 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003685 // This class has no superclass, so check that it has been marked with
3686 // __attribute((objc_root_class)).
3687 if (!HasRootClassAttr) {
3688 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00003689 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003690 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3691 << IDecl->getIdentifier();
3692 // See if NSObject is in the current scope, and if it is, suggest
3693 // adding " : NSObject " to the class declaration.
3694 NamedDecl *IF = LookupSingleName(TUScope,
3695 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3696 DeclLoc, LookupOrdinaryName);
3697 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3698 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3699 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3700 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3701 } else {
3702 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3703 }
3704 }
3705 } else if (HasRootClassAttr) {
3706 // Complain that only root classes may have this attribute.
3707 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3708 }
3709
John McCall5fb5df92012-06-20 06:18:46 +00003710 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003711 while (IDecl->getSuperClass()) {
3712 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3713 IDecl = IDecl->getSuperClass();
3714 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003715 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003716 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003717 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00003718 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00003719 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003720 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003721
Chris Lattnerda463fe2007-12-12 07:09:47 +00003722 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00003723 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00003724 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003725 if (ObjCCategoryDecl *Cat
3726 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3727 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003728 }
3729 }
3730 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003731 if (isInterfaceDeclKind) {
3732 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003733 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003734 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003735 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3736 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003737 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00003738 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00003739 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003740 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003741 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00003742 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003743
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003744 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003745 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003746 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3747 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003748 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3749 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003750
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00003751 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003752 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003753}
3754
Chris Lattnerda463fe2007-12-12 07:09:47 +00003755/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3756/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00003757static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003758CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00003759 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003760}
3761
Douglas Gregor33823722011-06-11 01:09:30 +00003762/// \brief Check whether the declared result type of the given Objective-C
3763/// method declaration is compatible with the method's class.
3764///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003765static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00003766CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3767 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00003768 QualType ResultType = Method->getReturnType();
3769
Douglas Gregor33823722011-06-11 01:09:30 +00003770 // If an Objective-C method inherits its related result type, then its
3771 // declared result type must be compatible with its own class type. The
3772 // declared result type is compatible if:
3773 if (const ObjCObjectPointerType *ResultObjectType
3774 = ResultType->getAs<ObjCObjectPointerType>()) {
3775 // - it is id or qualified id, or
3776 if (ResultObjectType->isObjCIdType() ||
3777 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003778 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003779
3780 if (CurrentClass) {
3781 if (ObjCInterfaceDecl *ResultClass
3782 = ResultObjectType->getInterfaceDecl()) {
3783 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00003784 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003785 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003786
3787 // - it is a superclass of the method's class type
3788 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003789 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003790 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00003791 } else {
3792 // Any Objective-C pointer type might be acceptable for a protocol
3793 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003794 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00003795 }
3796 }
3797
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003798 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003799}
3800
John McCalld2930c22011-07-22 02:45:48 +00003801namespace {
3802/// A helper class for searching for methods which a particular method
3803/// overrides.
3804class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003805public:
John McCalld2930c22011-07-22 02:45:48 +00003806 Sema &S;
3807 ObjCMethodDecl *Method;
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003808 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00003809 bool Recursive;
3810
3811public:
3812 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
3813 Selector selector = method->getSelector();
3814
3815 // Bypass this search if we've never seen an instance/class method
3816 // with this selector before.
3817 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
3818 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00003819 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00003820 S.ReadMethodPool(selector);
3821
3822 it = S.MethodPool.find(selector);
3823 if (it == S.MethodPool.end())
3824 return;
John McCalld2930c22011-07-22 02:45:48 +00003825 }
3826 ObjCMethodList &list =
3827 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003828 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00003829
3830 ObjCContainerDecl *container
3831 = cast<ObjCContainerDecl>(method->getDeclContext());
3832
3833 // Prevent the search from reaching this container again. This is
3834 // important with categories, which override methods from the
3835 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003836 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
3837 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003838 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
3839 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003840 } else {
3841 searchFromContainer(container);
3842 }
Douglas Gregor33823722011-06-11 01:09:30 +00003843 }
John McCalld2930c22011-07-22 02:45:48 +00003844
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003845 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00003846 iterator begin() const { return Overridden.begin(); }
3847 iterator end() const { return Overridden.end(); }
3848
3849private:
3850 void searchFromContainer(ObjCContainerDecl *container) {
3851 if (container->isInvalidDecl()) return;
3852
3853 switch (container->getDeclKind()) {
3854#define OBJCCONTAINER(type, base) \
3855 case Decl::type: \
3856 searchFrom(cast<type##Decl>(container)); \
3857 break;
3858#define ABSTRACT_DECL(expansion)
3859#define DECL(type, base) \
3860 case Decl::type:
3861#include "clang/AST/DeclNodes.inc"
3862 llvm_unreachable("not an ObjC container!");
3863 }
3864 }
3865
3866 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00003867 if (!protocol->hasDefinition())
3868 return;
3869
John McCalld2930c22011-07-22 02:45:48 +00003870 // A method in a protocol declaration overrides declarations from
3871 // referenced ("parent") protocols.
3872 search(protocol->getReferencedProtocols());
3873 }
3874
3875 void searchFrom(ObjCCategoryDecl *category) {
3876 // A method in a category declaration overrides declarations from
3877 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003878 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00003879 search(category->getReferencedProtocols());
3880 }
3881
3882 void searchFrom(ObjCCategoryImplDecl *impl) {
3883 // A method in a category definition that has a category
3884 // declaration overrides declarations from the category
3885 // declaration.
3886 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
3887 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003888 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
3889 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003890
3891 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003892 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
3893 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003894 }
3895 }
3896
3897 void searchFrom(ObjCInterfaceDecl *iface) {
3898 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00003899 if (!iface->hasDefinition())
3900 return;
3901
John McCalld2930c22011-07-22 02:45:48 +00003902 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00003903 for (auto *Cat : iface->known_categories())
3904 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00003905
3906 // - the super class, and
3907 if (ObjCInterfaceDecl *super = iface->getSuperClass())
3908 search(super);
3909
3910 // - any referenced protocols.
3911 search(iface->getReferencedProtocols());
3912 }
3913
3914 void searchFrom(ObjCImplementationDecl *impl) {
3915 // A method in a class implementation overrides declarations from
3916 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003917 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
3918 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003919 }
3920
John McCalld2930c22011-07-22 02:45:48 +00003921 void search(const ObjCProtocolList &protocols) {
3922 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
3923 i != e; ++i)
3924 search(*i);
3925 }
3926
3927 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00003928 // Check for a method in this container which matches this selector.
3929 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00003930 Method->isInstanceMethod(),
3931 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00003932
3933 // If we find one, record it and bail out.
3934 if (meth) {
3935 Overridden.insert(meth);
3936 return;
3937 }
3938
3939 // Otherwise, search for methods that a hypothetical method here
3940 // would have overridden.
3941
3942 // Note that we're now in a recursive case.
3943 Recursive = true;
3944
3945 searchFromContainer(container);
3946 }
3947};
Hans Wennborgdcfba332015-10-06 23:40:43 +00003948} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00003949
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003950void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
3951 ObjCInterfaceDecl *CurrentClass,
3952 ResultTypeCompatibilityKind RTC) {
3953 // Search for overridden methods and merge information down from them.
3954 OverrideSearch overrides(*this, ObjCMethod);
3955 // Keep track if the method overrides any method in the class's base classes,
3956 // its protocols, or its categories' protocols; we will keep that info
3957 // in the ObjCMethodDecl.
3958 // For this info, a method in an implementation is not considered as
3959 // overriding the same method in the interface or its categories.
3960 bool hasOverriddenMethodsInBaseOrProtocol = false;
3961 for (OverrideSearch::iterator
3962 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
3963 ObjCMethodDecl *overridden = *i;
3964
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003965 if (!hasOverriddenMethodsInBaseOrProtocol) {
3966 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3967 CurrentClass != overridden->getClassInterface() ||
3968 overridden->isOverriding()) {
3969 hasOverriddenMethodsInBaseOrProtocol = true;
3970
3971 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3972 // OverrideSearch will return as "overridden" the same method in the
3973 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3974 // check whether a category of a base class introduced a method with the
3975 // same selector, after the interface method declaration.
3976 // To avoid unnecessary lookups in the majority of cases, we use the
3977 // extra info bits in GlobalMethodPool to check whether there were any
3978 // category methods with this selector.
3979 GlobalMethodPool::iterator It =
3980 MethodPool.find(ObjCMethod->getSelector());
3981 if (It != MethodPool.end()) {
3982 ObjCMethodList &List =
3983 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3984 unsigned CategCount = List.getBits();
3985 if (CategCount > 0) {
3986 // If the method is in a category we'll do lookup if there were at
3987 // least 2 category methods recorded, otherwise only one will do.
3988 if (CategCount > 1 ||
3989 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3990 OverrideSearch overrides(*this, overridden);
3991 for (OverrideSearch::iterator
3992 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3993 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003994 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3995 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003996 hasOverriddenMethodsInBaseOrProtocol = true;
3997 overridden->setOverriding(true);
3998 break;
3999 }
4000 }
4001 }
4002 }
4003 }
4004 }
4005 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004006
4007 // Propagate down the 'related result type' bit from overridden methods.
4008 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4009 ObjCMethod->SetRelatedResultType();
4010
4011 // Then merge the declarations.
4012 mergeObjCMethodDecls(ObjCMethod, overridden);
4013
4014 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4015 continue; // Conflicting properties are detected elsewhere.
4016
4017 // Check for overriding methods
4018 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4019 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4020 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4021 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4022
4023 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004024 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4025 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004026 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4027 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004028 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4029 PrevE = overridden->param_end();
4030 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004031 assert(PrevI != overridden->param_end() && "Param mismatch");
4032 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4033 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4034 // If type of argument of method in this class does not match its
4035 // respective argument type in the super class method, issue warning;
4036 if (!Context.typesAreCompatible(T1, T2)) {
4037 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4038 << T1 << T2;
4039 Diag(overridden->getLocation(), diag::note_previous_declaration);
4040 break;
4041 }
4042 }
4043 }
4044 }
4045
4046 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4047}
4048
Douglas Gregor813a0662015-06-19 18:14:38 +00004049/// Merge type nullability from for a redeclaration of the same entity,
4050/// producing the updated type of the redeclared entity.
4051static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4052 QualType type,
4053 bool usesCSKeyword,
4054 SourceLocation prevLoc,
4055 QualType prevType,
4056 bool prevUsesCSKeyword) {
4057 // Determine the nullability of both types.
4058 auto nullability = type->getNullability(S.Context);
4059 auto prevNullability = prevType->getNullability(S.Context);
4060
4061 // Easy case: both have nullability.
4062 if (nullability.hasValue() == prevNullability.hasValue()) {
4063 // Neither has nullability; continue.
4064 if (!nullability)
4065 return type;
4066
4067 // The nullabilities are equivalent; do nothing.
4068 if (*nullability == *prevNullability)
4069 return type;
4070
4071 // Complain about mismatched nullability.
4072 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004073 << DiagNullabilityKind(*nullability, usesCSKeyword)
4074 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004075 return type;
4076 }
4077
4078 // If it's the redeclaration that has nullability, don't change anything.
4079 if (nullability)
4080 return type;
4081
4082 // Otherwise, provide the result with the same nullability.
4083 return S.Context.getAttributedType(
4084 AttributedType::getNullabilityAttrKind(*prevNullability),
4085 type, type);
4086}
4087
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004088/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004089/// (or a category/extension) into the corresponding method in the
4090/// @implementation (for a class or category).
4091static void mergeInterfaceMethodToImpl(Sema &S,
4092 ObjCMethodDecl *method,
4093 ObjCMethodDecl *prevMethod) {
4094 // Merge the objc_requires_super attribute.
4095 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4096 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4097 // merge the attribute into implementation.
4098 method->addAttr(
4099 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4100 method->getLocation()));
4101 }
4102
4103 // Merge nullability of the result type.
4104 QualType newReturnType
4105 = mergeTypeNullabilityForRedecl(
4106 S, method->getReturnTypeSourceRange().getBegin(),
4107 method->getReturnType(),
4108 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4109 prevMethod->getReturnTypeSourceRange().getBegin(),
4110 prevMethod->getReturnType(),
4111 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4112 method->setReturnType(newReturnType);
4113
4114 // Handle each of the parameters.
4115 unsigned numParams = method->param_size();
4116 unsigned numPrevParams = prevMethod->param_size();
4117 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4118 ParmVarDecl *param = method->param_begin()[i];
4119 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4120
4121 // Merge nullability.
4122 QualType newParamType
4123 = mergeTypeNullabilityForRedecl(
4124 S, param->getLocation(), param->getType(),
4125 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4126 prevParam->getLocation(), prevParam->getType(),
4127 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4128 param->setType(newParamType);
4129 }
4130}
4131
John McCall48871652010-08-21 09:40:31 +00004132Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004133 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004134 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004135 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004136 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004137 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004138 Selector Sel,
4139 // optional arguments. The number of types/arguments is obtained
4140 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004141 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004142 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004143 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004144 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004145 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004146 if (!CurContext->isObjCContainer()) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004147 Diag(MethodLoc, diag::error_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004148 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004149 }
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004150 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4151 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004152 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004153
Douglas Gregorbab8a962011-09-08 01:46:34 +00004154 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004155 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004156 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004157 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004158
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004159 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004160 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004161
Douglas Gregor813a0662015-06-19 18:14:38 +00004162 QualType bareResultType = resultDeclType;
4163 (void)AttributedType::stripOuterNullability(bareResultType);
4164 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004165 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004166 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004167 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004168 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004169 }
Mike Stump11289f42009-09-09 15:08:12 +00004170
Alp Toker314cc812014-01-25 16:55:45 +00004171 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4172 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4173 MethodType == tok::minus, isVariadic,
4174 /*isPropertyAccessor=*/false,
4175 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4176 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4177 : ObjCMethodDecl::Required,
4178 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004179
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004180 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004181
Chris Lattner23b0faf2009-04-11 19:42:43 +00004182 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004183 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004184 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004185
David Blaikie7d170102013-05-15 07:37:26 +00004186 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004187 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004188 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004189 } else {
John McCall856bbea2009-10-23 21:48:59 +00004190 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004191 }
Mike Stump11289f42009-09-09 15:08:12 +00004192
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004193 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4194 LookupOrdinaryName, ForRedeclaration);
4195 LookupName(R, S);
4196 if (R.isSingleResult()) {
4197 NamedDecl *PrevDecl = R.getFoundDecl();
4198 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004199 Diag(ArgInfo[i].NameLoc,
4200 (MethodDefinition ? diag::warn_method_param_redefinition
4201 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004202 << ArgInfo[i].Name;
4203 Diag(PrevDecl->getLocation(),
4204 diag::note_previous_declaration);
4205 }
4206 }
4207
Abramo Bagnaradff19302011-03-08 08:55:46 +00004208 SourceLocation StartLoc = DI
4209 ? DI->getTypeLoc().getBeginLoc()
4210 : ArgInfo[i].NameLoc;
4211
John McCalld44f4d72011-04-23 02:46:06 +00004212 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4213 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004214 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004215
John McCall82490832011-05-02 00:30:12 +00004216 Param->setObjCMethodScopeInfo(i);
4217
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004218 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004219 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004220
Chris Lattner9713a1c2009-04-11 19:34:56 +00004221 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004222 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Mike Stump11289f42009-09-09 15:08:12 +00004223
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004224 if (Param->hasAttr<BlocksAttr>()) {
4225 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4226 Param->setInvalidDecl();
4227 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004228 S->AddDecl(Param);
4229 IdResolver.AddDecl(Param);
4230
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004231 Params.push_back(Param);
4232 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004233
Fariborz Jahanian60462092010-04-08 00:30:06 +00004234 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004235 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004236 QualType ArgType = Param->getType();
4237 if (ArgType.isNull())
4238 ArgType = Context.getObjCIdType();
4239 else
4240 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004241 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004242
Fariborz Jahanian60462092010-04-08 00:30:06 +00004243 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004244 Params.push_back(Param);
4245 }
4246
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004247 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004248 ObjCMethod->setObjCDeclQualifier(
4249 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004250
4251 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004252 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Mike Stump11289f42009-09-09 15:08:12 +00004253
Douglas Gregor87e92752010-12-21 17:34:17 +00004254 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004255 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004256 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004257 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004258 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4259 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004260 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004261 PrevMethod = ImpDecl->getClassMethod(Sel);
4262 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004263 }
Douglas Gregor33823722011-06-11 01:09:30 +00004264
Douglas Gregor813a0662015-06-19 18:14:38 +00004265 // Merge information from the @interface declaration into the
4266 // @implementation.
4267 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4268 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4269 ObjCMethod->isInstanceMethod())) {
4270 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4271
4272 // Warn about defining -dealloc in a category.
4273 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4274 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4275 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4276 << ObjCMethod->getDeclName();
4277 }
4278 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004279 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004280 } else {
4281 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004282 }
John McCalld2930c22011-07-22 02:45:48 +00004283
Chris Lattnerda463fe2007-12-12 07:09:47 +00004284 if (PrevMethod) {
4285 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004286 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004287 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004288 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004289 ObjCMethod->setInvalidDecl();
4290 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004291 }
John McCall28a6aea2009-11-04 02:18:39 +00004292
Douglas Gregor33823722011-06-11 01:09:30 +00004293 // If this Objective-C method does not have a related result type, but we
4294 // are allowed to infer related result types, try to do so based on the
4295 // method family.
4296 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4297 if (!CurrentClass) {
4298 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4299 CurrentClass = Cat->getClassInterface();
4300 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4301 CurrentClass = Impl->getClassInterface();
4302 else if (ObjCCategoryImplDecl *CatImpl
4303 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4304 CurrentClass = CatImpl->getClassInterface();
4305 }
John McCalld2930c22011-07-22 02:45:48 +00004306
Douglas Gregorbab8a962011-09-08 01:46:34 +00004307 ResultTypeCompatibilityKind RTC
4308 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004309
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004310 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004311
John McCall31168b02011-06-15 23:02:42 +00004312 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004313 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004314 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004315
Douglas Gregorbab8a962011-09-08 01:46:34 +00004316 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004317 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004318 !ObjCMethod->hasRelatedResultType() &&
4319 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004320 bool InferRelatedResultType = false;
4321 switch (ObjCMethod->getMethodFamily()) {
4322 case OMF_None:
4323 case OMF_copy:
4324 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004325 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004326 case OMF_mutableCopy:
4327 case OMF_release:
4328 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004329 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004330 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004331 break;
4332
4333 case OMF_alloc:
4334 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004335 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004336 break;
4337
4338 case OMF_init:
4339 case OMF_autorelease:
4340 case OMF_retain:
4341 case OMF_self:
4342 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4343 break;
4344 }
4345
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004346 if (InferRelatedResultType &&
4347 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004348 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004349 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004350
4351 ActOnDocumentableDecl(ObjCMethod);
4352
John McCall48871652010-08-21 09:40:31 +00004353 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004354}
4355
Chris Lattner438e5012008-12-17 07:13:27 +00004356bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004357 // Following is also an error. But it is caused by a missing @end
4358 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004359 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004360 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004361
4362 // If we switched context to translation unit while we are still lexically in
4363 // an objc container, it means the parser missed emitting an error.
4364 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4365 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004366
Anders Carlssona6b508a2008-11-04 16:57:32 +00004367 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4368 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004369
Anders Carlssona6b508a2008-11-04 16:57:32 +00004370 return true;
4371}
Chris Lattner438e5012008-12-17 07:13:27 +00004372
James Dennett634962f2012-06-14 21:40:34 +00004373/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004374/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004375void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004376 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004377 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004378 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004379 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004380 if (!Class) {
4381 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4382 return;
4383 }
John McCall5fb5df92012-06-20 06:18:46 +00004384 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004385 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4386 return;
4387 }
Mike Stump11289f42009-09-09 15:08:12 +00004388
Chris Lattner438e5012008-12-17 07:13:27 +00004389 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004390 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004391 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004392 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004393 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004394 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCall48871652010-08-21 09:40:31 +00004395 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004396 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4397 /*FIXME: StartL=*/ID->getLocation(),
4398 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004399 ID->getIdentifier(), ID->getType(),
4400 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004401 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004402 }
Mike Stump11289f42009-09-09 15:08:12 +00004403
Chris Lattner438e5012008-12-17 07:13:27 +00004404 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004405 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004406 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004407 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004408 if (getLangOpts().CPlusPlus)
Chris Lattner438e5012008-12-17 07:13:27 +00004409 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCall48871652010-08-21 09:40:31 +00004410 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004411 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004412 }
4413}
4414
Douglas Gregorf3564192010-04-26 17:32:49 +00004415/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004416VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4417 SourceLocation StartLoc,
4418 SourceLocation IdLoc,
4419 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004420 bool Invalid) {
4421 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4422 // duration shall not be qualified by an address-space qualifier."
4423 // Since all parameters have automatic store duration, they can not have
4424 // an address space.
4425 if (T.getAddressSpace() != 0) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004426 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004427 Invalid = true;
4428 }
4429
4430 // An @catch parameter must be an unqualified object pointer type;
4431 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4432 if (Invalid) {
4433 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004434 } else if (T->isDependentType()) {
4435 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004436 } else if (!T->isObjCObjectPointerType()) {
4437 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004438 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004439 } else if (T->isObjCQualifiedIdType()) {
4440 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004441 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004442 }
4443
Abramo Bagnaradff19302011-03-08 08:55:46 +00004444 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004445 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004446 New->setExceptionVariable(true);
4447
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004448 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004449 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004450 Invalid = true;
4451
Douglas Gregorf3564192010-04-26 17:32:49 +00004452 if (Invalid)
4453 New->setInvalidDecl();
4454 return New;
4455}
4456
John McCall48871652010-08-21 09:40:31 +00004457Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004458 const DeclSpec &DS = D.getDeclSpec();
4459
4460 // We allow the "register" storage class on exception variables because
4461 // GCC did, but we drop it completely. Any other storage class is an error.
4462 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4463 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4464 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004465 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004466 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004467 << DeclSpec::getSpecifierName(SCS);
4468 }
4469 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4470 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4471 diag::err_invalid_thread)
4472 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004473 D.getMutableDeclSpec().ClearStorageClassSpecs();
4474
Richard Smithb1402ae2013-03-18 22:52:47 +00004475 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004476
4477 // Check that there are no default arguments inside the type of this
4478 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004479 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004480 CheckExtraCXXDefaultArguments(D);
4481
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004482 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004483 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004484
Abramo Bagnaradff19302011-03-08 08:55:46 +00004485 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4486 D.getSourceRange().getBegin(),
4487 D.getIdentifierLoc(),
4488 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004489 D.isInvalidType());
4490
4491 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4492 if (D.getCXXScopeSpec().isSet()) {
4493 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4494 << D.getCXXScopeSpec().getRange();
4495 New->setInvalidDecl();
4496 }
4497
4498 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004499 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004500 if (D.getIdentifier())
4501 IdResolver.AddDecl(New);
4502
4503 ProcessDeclAttributes(S, New, D);
4504
4505 if (New->hasAttr<BlocksAttr>())
4506 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004507 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004508}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004509
4510/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004511/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004512void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004513 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004514 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4515 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004516 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004517 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004518 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004519 }
4520}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004521
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004522void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004523 // Load referenced selectors from the external source.
4524 if (ExternalSource) {
4525 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4526 ExternalSource->ReadReferencedSelectors(Sels);
4527 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4528 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4529 }
4530
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004531 // Warning will be issued only when selector table is
4532 // generated (which means there is at lease one implementation
4533 // in the TU). This is to match gcc's behavior.
4534 if (ReferencedSelectors.empty() ||
4535 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004536 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004537 for (auto &SelectorAndLocation : ReferencedSelectors) {
4538 Selector Sel = SelectorAndLocation.first;
4539 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004540 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004541 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004542 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004543}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004544
4545ObjCIvarDecl *
4546Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4547 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004548 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004549 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004550 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4551 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004552 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004553 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4554 /*shallowCategoryLookup=*/false,
4555 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004556 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004557 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004558 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004559 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4560 // property backing ivar must belong to property's class
4561 // or be a private ivar in class's implementation.
4562 // FIXME. fix the const-ness issue.
4563 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4564 IV->getIdentifier());
4565 return IV;
4566 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004567 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004568}
4569
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004570namespace {
4571 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4572 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004573 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00004574 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004575 public:
4576 Sema &S;
4577 const ObjCMethodDecl *Method;
4578 const ObjCIvarDecl *IvarD;
4579 bool AccessedIvar;
4580 bool InvokedSelfMethod;
4581
4582 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4583 const ObjCIvarDecl *IvarD)
4584 : S(S), Method(Method), IvarD(IvarD),
4585 AccessedIvar(false), InvokedSelfMethod(false) {
4586 assert(IvarD);
4587 }
4588
4589 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4590 if (E->getDecl() == IvarD) {
4591 AccessedIvar = true;
4592 return false;
4593 }
4594 return true;
4595 }
4596
4597 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4598 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4599 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4600 InvokedSelfMethod = true;
4601 }
4602 return true;
4603 }
4604 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00004605} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004606
4607void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4608 const ObjCImplementationDecl *ImplD) {
4609 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004610 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004611
Aaron Ballmanf26acce2014-03-13 19:50:17 +00004612 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004613 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4614 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004615 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004616 continue;
4617
4618 const ObjCPropertyDecl *PDecl;
4619 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4620 if (!IV)
4621 continue;
4622
4623 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4624 Checker.TraverseStmt(CurMethod->getBody());
4625 if (Checker.AccessedIvar)
4626 continue;
4627
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004628 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004629 // implementation makes a self call. This is to prevent false positive in
4630 // cases where the ivar is accessed by another method that the accessor
4631 // delegates to.
4632 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00004633 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004634 Diag(PDecl->getLocation(), diag::note_property_declare);
4635 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004636 }
4637}