blob: 2622e5ed83139647cde1318536c4074b6ff49dd7 [file] [log] [blame]
Chris Lattnerda463fe2007-12-12 07:09:47 +00001//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerda463fe2007-12-12 07:09:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall31168b02011-06-15 23:02:42 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +000018#include "clang/AST/DataRecursiveASTVisitor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/AST/DeclObjC.h"
Steve Naroff157599f2009-03-03 14:49:36 +000020#include "clang/AST/Expr.h"
John McCall31168b02011-06-15 23:02:42 +000021#include "clang/AST/ExprObjC.h"
John McCall31168b02011-06-15 23:02:42 +000022#include "clang/Basic/SourceManager.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000023#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/DeclSpec.h"
25#include "clang/Sema/ExternalSemaSource.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/Scope.h"
28#include "clang/Sema/ScopeInfo.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000029#include "llvm/ADT/DenseMap.h"
John McCalla1e130b2010-08-25 07:03:20 +000030#include "llvm/ADT/DenseSet.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000031#include "TypeLocBuilder.h"
John McCalla1e130b2010-08-25 07:03:20 +000032
Chris Lattnerda463fe2007-12-12 07:09:47 +000033using namespace clang;
34
John McCall31168b02011-06-15 23:02:42 +000035/// Check whether the given method, which must be in the 'init'
36/// family, is a valid member of that family.
37///
38/// \param receiverTypeIfCall - if null, check this as if declaring it;
39/// if non-null, check this as if making a call to it with the given
40/// receiver type
41///
42/// \return true to indicate that there was an error and appropriate
43/// actions were taken
44bool Sema::checkInitMethod(ObjCMethodDecl *method,
45 QualType receiverTypeIfCall) {
46 if (method->isInvalidDecl()) return true;
47
48 // This castAs is safe: methods that don't return an object
49 // pointer won't be inferred as inits and will reject an explicit
50 // objc_method_family(init).
51
52 // We ignore protocols here. Should we? What about Class?
53
Alp Toker314cc812014-01-25 16:55:45 +000054 const ObjCObjectType *result =
55 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCall31168b02011-06-15 23:02:42 +000056
57 if (result->isObjCId()) {
58 return false;
59 } else if (result->isObjCClass()) {
60 // fall through: always an error
61 } else {
62 ObjCInterfaceDecl *resultClass = result->getInterface();
63 assert(resultClass && "unexpected object type!");
64
65 // It's okay for the result type to still be a forward declaration
66 // if we're checking an interface declaration.
Douglas Gregordc9166c2011-12-15 20:29:51 +000067 if (!resultClass->hasDefinition()) {
John McCall31168b02011-06-15 23:02:42 +000068 if (receiverTypeIfCall.isNull() &&
69 !isa<ObjCImplementationDecl>(method->getDeclContext()))
70 return false;
71
72 // Otherwise, we try to compare class types.
73 } else {
74 // If this method was declared in a protocol, we can't check
75 // anything unless we have a receiver type that's an interface.
Craig Topperc3ec1492014-05-26 06:22:03 +000076 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCall31168b02011-06-15 23:02:42 +000077 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
78 if (receiverTypeIfCall.isNull())
79 return false;
80
81 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
82 ->getInterfaceDecl();
83
84 // This can be null for calls to e.g. id<Foo>.
85 if (!receiverClass) return false;
86 } else {
87 receiverClass = method->getClassInterface();
88 assert(receiverClass && "method not associated with a class!");
89 }
90
91 // If either class is a subclass of the other, it's fine.
92 if (receiverClass->isSuperClassOf(resultClass) ||
93 resultClass->isSuperClassOf(receiverClass))
94 return false;
95 }
96 }
97
98 SourceLocation loc = method->getLocation();
99
100 // If we're in a system header, and this is not a call, just make
101 // the method unusable.
102 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
John McCallc6af8c62015-10-28 05:03:19 +0000103 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
104 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
John McCall31168b02011-06-15 23:02:42 +0000105 return true;
106 }
107
108 // Otherwise, it's an error.
109 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
110 method->setInvalidDecl();
111 return true;
112}
113
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000114void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000115 const ObjCMethodDecl *Overridden) {
Douglas Gregor33823722011-06-11 01:09:30 +0000116 if (Overridden->hasRelatedResultType() &&
117 !NewMethod->hasRelatedResultType()) {
118 // This can only happen when the method follows a naming convention that
119 // implies a related result type, and the original (overridden) method has
120 // a suitable return type, but the new (overriding) method does not have
121 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000122 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000123 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +0000124
125 // Figure out which class this method is part of, if any.
126 ObjCInterfaceDecl *CurrentClass
127 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
128 if (!CurrentClass) {
129 DeclContext *DC = NewMethod->getDeclContext();
130 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
131 CurrentClass = Cat->getClassInterface();
132 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
133 CurrentClass = Impl->getClassInterface();
134 else if (ObjCCategoryImplDecl *CatImpl
135 = dyn_cast<ObjCCategoryImplDecl>(DC))
136 CurrentClass = CatImpl->getClassInterface();
137 }
138
139 if (CurrentClass) {
140 Diag(NewMethod->getLocation(),
141 diag::warn_related_result_type_compatibility_class)
142 << Context.getObjCInterfaceType(CurrentClass)
143 << ResultType
144 << ResultTypeRange;
145 } else {
146 Diag(NewMethod->getLocation(),
147 diag::warn_related_result_type_compatibility_protocol)
148 << ResultType
149 << ResultTypeRange;
150 }
151
Douglas Gregorbab8a962011-09-08 01:46:34 +0000152 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
153 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000154 diag::note_related_result_type_family)
155 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000156 << Family;
157 else
158 Diag(Overridden->getLocation(),
159 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000160 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000161 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000162 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
163 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
164 Diag(NewMethod->getLocation(),
165 diag::err_nsreturns_retained_attribute_mismatch) << 1;
166 Diag(Overridden->getLocation(), diag::note_previous_decl)
167 << "method";
168 }
169 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
170 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
171 Diag(NewMethod->getLocation(),
172 diag::err_nsreturns_retained_attribute_mismatch) << 0;
173 Diag(Overridden->getLocation(), diag::note_previous_decl)
174 << "method";
175 }
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000176 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
177 oe = Overridden->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000178 for (ObjCMethodDecl::param_iterator
179 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000180 ni != ne && oi != oe; ++ni, ++oi) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000181 const ParmVarDecl *oldDecl = (*oi);
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000182 ParmVarDecl *newDecl = (*ni);
183 if (newDecl->hasAttr<NSConsumedAttr>() !=
184 oldDecl->hasAttr<NSConsumedAttr>()) {
185 Diag(newDecl->getLocation(),
186 diag::err_nsconsumed_attribute_mismatch);
187 Diag(oldDecl->getLocation(), diag::note_previous_decl)
188 << "parameter";
189 }
190 }
191 }
Douglas Gregor33823722011-06-11 01:09:30 +0000192}
193
John McCall31168b02011-06-15 23:02:42 +0000194/// \brief Check a method declaration for compatibility with the Objective-C
195/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000196bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000197 ObjCMethodFamily family = method->getMethodFamily();
198 switch (family) {
199 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000200 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000201 case OMF_retain:
202 case OMF_release:
203 case OMF_autorelease:
204 case OMF_retainCount:
205 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000206 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000207 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000208 return false;
209
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000210 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000211 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000212 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000213 if (ResultTypeRange.isInvalid())
Alp Toker314cc812014-01-25 16:55:45 +0000214 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
215 << method->getReturnType()
216 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000217 else
Alp Toker314cc812014-01-25 16:55:45 +0000218 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
219 << method->getReturnType()
220 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000221 return true;
222 }
223 return false;
224
John McCall31168b02011-06-15 23:02:42 +0000225 case OMF_init:
226 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000227 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000228 return true;
229
Aaron Ballman36a53502014-01-16 13:03:14 +0000230 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000231
232 // Don't add a second copy of this attribute, but otherwise don't
233 // let it be suppressed.
234 if (method->hasAttr<NSReturnsRetainedAttr>())
235 return false;
236 break;
237
238 case OMF_alloc:
239 case OMF_copy:
240 case OMF_mutableCopy:
241 case OMF_new:
242 if (method->hasAttr<NSReturnsRetainedAttr>() ||
243 method->hasAttr<NSReturnsNotRetainedAttr>() ||
244 method->hasAttr<NSReturnsAutoreleasedAttr>())
245 return false;
246 break;
247 }
248
Aaron Ballman36a53502014-01-16 13:03:14 +0000249 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000250 return false;
251}
252
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000253static void DiagnoseObjCImplementedDeprecations(Sema &S,
254 NamedDecl *ND,
255 SourceLocation ImplLoc,
256 int select) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000257 if (ND && ND->isDeprecated()) {
Fariborz Jahanian6fd94352011-02-16 00:30:31 +0000258 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000259 if (select == 0)
Ted Kremenek59b10db2012-02-27 22:55:11 +0000260 S.Diag(ND->getLocation(), diag::note_method_declared_at)
261 << ND->getDeclName();
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000262 else
263 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
264 }
265}
266
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000267/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
268/// pool.
269void Sema::AddAnyMethodToGlobalPool(Decl *D) {
270 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
271
272 // If we don't have a valid method decl, simply return.
273 if (!MDecl)
274 return;
275 if (MDecl->isInstanceMethod())
276 AddInstanceMethodToGlobalPool(MDecl, true);
277 else
278 AddFactoryMethodToGlobalPool(MDecl, true);
279}
280
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000281/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
282/// has explicit ownership attribute; false otherwise.
283static bool
284HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
285 QualType T = Param->getType();
286
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000287 if (const PointerType *PT = T->getAs<PointerType>()) {
288 T = PT->getPointeeType();
289 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
290 T = RT->getPointeeType();
291 } else {
292 return true;
293 }
294
295 // If we have a lifetime qualifier, but it's local, we must have
296 // inferred it. So, it is implicit.
297 return !T.getLocalQualifiers().hasObjCLifetime();
298}
299
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000300/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
301/// and user declared, in the method definition's AST.
302void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000303 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000304 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000305
Steve Naroff542cd5d2008-07-25 17:57:26 +0000306 // If we don't have a valid method decl, simply return.
307 if (!MDecl)
308 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000309
Chris Lattnerda463fe2007-12-12 07:09:47 +0000310 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000311 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000312 PushFunctionScope();
313
Chris Lattnerda463fe2007-12-12 07:09:47 +0000314 // Create Decl objects for each parameter, entrring them in the scope for
315 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000316
317 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000318 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000319
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000320 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
321 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000322
Reid Kleckner5a115802013-06-24 14:38:26 +0000323 // The ObjC parser requires parameter names so there's no need to check.
324 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
325 /*CheckParameterNames=*/false);
326
Chris Lattner58258242008-04-10 02:22:51 +0000327 // Introduce all of the other parameters into this scope.
Aaron Ballman43b68be2014-03-07 17:50:17 +0000328 for (auto *Param : MDecl->params()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000329 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000330 getLangOpts().ObjCAutoRefCount &&
331 !HasExplicitOwnershipAttr(*this, Param))
332 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
333 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000334
Aaron Ballman43b68be2014-03-07 17:50:17 +0000335 if (Param->getIdentifier())
336 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000337 }
John McCall31168b02011-06-15 23:02:42 +0000338
339 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000340 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000341 switch (MDecl->getMethodFamily()) {
342 case OMF_retain:
343 case OMF_retainCount:
344 case OMF_release:
345 case OMF_autorelease:
346 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000347 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000348 break;
349
350 case OMF_None:
351 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000352 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000353 case OMF_alloc:
354 case OMF_init:
355 case OMF_mutableCopy:
356 case OMF_copy:
357 case OMF_new:
358 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000359 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000360 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000361 break;
362 }
363 }
364
Nico Weber715abaf2011-08-22 17:25:57 +0000365 // Warn on deprecated methods under -Wdeprecated-implementations,
366 // and prepare for warning on missing super calls.
367 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000368 ObjCMethodDecl *IMD =
369 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
370
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000371 if (IMD) {
372 ObjCImplDecl *ImplDeclOfMethodDef =
373 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
374 ObjCContainerDecl *ContDeclOfMethodDecl =
375 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000376 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000377 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
378 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000379 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
380 if (CD->IsClassExtension()) {
381 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
382 ImplDeclOfMethodDecl = OID->getImplementation();
383 } else
384 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000385 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000386 // No need to issue deprecated warning if deprecated mehod in class/category
387 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000388 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000389 DiagnoseObjCImplementedDeprecations(*this,
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000390 dyn_cast<NamedDecl>(IMD),
391 MDecl->getLocation(), 0);
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000392 }
Nico Weber715abaf2011-08-22 17:25:57 +0000393
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000394 if (MDecl->getMethodFamily() == OMF_init) {
395 if (MDecl->isDesignatedInitializerForTheInterface()) {
396 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000397 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000398 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000399 } else if (IC->hasDesignatedInitializers()) {
400 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000401 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000402 }
403 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000404
Nico Weber1fb82662011-08-28 22:35:17 +0000405 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000406 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
407 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
408 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000409 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000410 ObjCMethodFamily Family = MDecl->getMethodFamily();
411 if (Family == OMF_dealloc) {
412 if (!(getLangOpts().ObjCAutoRefCount ||
413 getLangOpts().getGC() == LangOptions::GCOnly))
414 getCurFunction()->ObjCShouldCallSuper = true;
415
416 } else if (Family == OMF_finalize) {
417 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
418 getCurFunction()->ObjCShouldCallSuper = true;
419
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000420 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000421 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000422 SuperClass->lookupMethod(MDecl->getSelector(),
423 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000424 getCurFunction()->ObjCShouldCallSuper =
425 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000426 }
Nico Weber1fb82662011-08-28 22:35:17 +0000427 }
Nico Weber715abaf2011-08-22 17:25:57 +0000428 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000429}
430
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000431namespace {
432
433// Callback to only accept typo corrections that are Objective-C classes.
434// If an ObjCInterfaceDecl* is given to the constructor, then the validation
435// function will reject corrections to that class.
436class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
437 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000438 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000439 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
440 : CurrentIDecl(IDecl) {}
441
Craig Toppere14c0f82014-03-12 04:55:44 +0000442 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000443 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
444 return ID && !declaresSameEntity(ID, CurrentIDecl);
445 }
446
447 private:
448 ObjCInterfaceDecl *CurrentIDecl;
449};
450
Hans Wennborgdcfba332015-10-06 23:40:43 +0000451} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000452
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000453static void diagnoseUseOfProtocols(Sema &TheSema,
454 ObjCContainerDecl *CD,
455 ObjCProtocolDecl *const *ProtoRefs,
456 unsigned NumProtoRefs,
457 const SourceLocation *ProtoLocs) {
458 assert(ProtoRefs);
459 // Diagnose availability in the context of the ObjC container.
460 Sema::ContextRAII SavedContext(TheSema, CD);
461 for (unsigned i = 0; i < NumProtoRefs; ++i) {
462 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]);
463 }
464}
465
Douglas Gregore9d95f12015-07-07 03:57:35 +0000466void Sema::
467ActOnSuperClassOfClassInterface(Scope *S,
468 SourceLocation AtInterfaceLoc,
469 ObjCInterfaceDecl *IDecl,
470 IdentifierInfo *ClassName,
471 SourceLocation ClassLoc,
472 IdentifierInfo *SuperName,
473 SourceLocation SuperLoc,
474 ArrayRef<ParsedType> SuperTypeArgs,
475 SourceRange SuperTypeArgsRange) {
476 // Check if a different kind of symbol declared in this scope.
477 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
478 LookupOrdinaryName);
479
480 if (!PrevDecl) {
481 // Try to correct for a typo in the superclass name without correcting
482 // to the class we're defining.
483 if (TypoCorrection Corrected = CorrectTypo(
484 DeclarationNameInfo(SuperName, SuperLoc),
485 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000486 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000487 CTK_ErrorRecovery)) {
488 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
489 << SuperName << ClassName);
490 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
491 }
492 }
493
494 if (declaresSameEntity(PrevDecl, IDecl)) {
495 Diag(SuperLoc, diag::err_recursive_superclass)
496 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
497 IDecl->setEndOfDefinitionLoc(ClassLoc);
498 } else {
499 ObjCInterfaceDecl *SuperClassDecl =
500 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
501 QualType SuperClassType;
502
503 // Diagnose classes that inherit from deprecated classes.
504 if (SuperClassDecl) {
505 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
506 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
507 }
508
Hans Wennborgdcfba332015-10-06 23:40:43 +0000509 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000510 // The previous declaration was not a class decl. Check if we have a
511 // typedef. If we do, get the underlying class type.
512 if (const TypedefNameDecl *TDecl =
513 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
514 QualType T = TDecl->getUnderlyingType();
515 if (T->isObjCObjectType()) {
516 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
517 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
518 SuperClassType = Context.getTypeDeclType(TDecl);
519
520 // This handles the following case:
521 // @interface NewI @end
522 // typedef NewI DeprI __attribute__((deprecated("blah")))
523 // @interface SI : DeprI /* warn here */ @end
524 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
525 }
526 }
527 }
528
529 // This handles the following case:
530 //
531 // typedef int SuperClass;
532 // @interface MyClass : SuperClass {} @end
533 //
534 if (!SuperClassDecl) {
535 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
536 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
537 }
538 }
539
540 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
541 if (!SuperClassDecl)
542 Diag(SuperLoc, diag::err_undef_superclass)
543 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
544 else if (RequireCompleteType(SuperLoc,
545 SuperClassType,
546 diag::err_forward_superclass,
547 SuperClassDecl->getDeclName(),
548 ClassName,
549 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000550 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000551 SuperClassType = QualType();
552 }
553 }
554
555 if (SuperClassType.isNull()) {
556 assert(!SuperClassDecl && "Failed to set SuperClassType?");
557 return;
558 }
559
560 // Handle type arguments on the superclass.
561 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000562 if (!SuperTypeArgs.empty()) {
563 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
564 S,
565 SuperLoc,
566 CreateParsedType(SuperClassType,
567 nullptr),
568 SuperTypeArgsRange.getBegin(),
569 SuperTypeArgs,
570 SuperTypeArgsRange.getEnd(),
571 SourceLocation(),
572 { },
573 { },
574 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000575 if (!fullSuperClassType.isUsable())
576 return;
577
578 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
579 &SuperClassTInfo);
580 }
581
582 if (!SuperClassTInfo) {
583 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
584 SuperLoc);
585 }
586
587 IDecl->setSuperClass(SuperClassTInfo);
588 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
589 }
590}
591
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000592DeclResult Sema::actOnObjCTypeParam(Scope *S,
593 ObjCTypeParamVariance variance,
594 SourceLocation varianceLoc,
595 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000596 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000597 SourceLocation paramLoc,
598 SourceLocation colonLoc,
599 ParsedType parsedTypeBound) {
600 // If there was an explicitly-provided type bound, check it.
601 TypeSourceInfo *typeBoundInfo = nullptr;
602 if (parsedTypeBound) {
603 // The type bound can be any Objective-C pointer type.
604 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
605 if (typeBound->isObjCObjectPointerType()) {
606 // okay
607 } else if (typeBound->isObjCObjectType()) {
608 // The user forgot the * on an Objective-C pointer type, e.g.,
609 // "T : NSView".
610 SourceLocation starLoc = PP.getLocForEndOfToken(
611 typeBoundInfo->getTypeLoc().getEndLoc());
612 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
613 diag::err_objc_type_param_bound_missing_pointer)
614 << typeBound << paramName
615 << FixItHint::CreateInsertion(starLoc, " *");
616
617 // Create a new type location builder so we can update the type
618 // location information we have.
619 TypeLocBuilder builder;
620 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
621
622 // Create the Objective-C pointer type.
623 typeBound = Context.getObjCObjectPointerType(typeBound);
624 ObjCObjectPointerTypeLoc newT
625 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
626 newT.setStarLoc(starLoc);
627
628 // Form the new type source information.
629 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
630 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000631 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000632 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
633 diag::err_objc_type_param_bound_nonobject)
634 << typeBound << paramName;
635
636 // Forget the bound; we'll default to id later.
637 typeBoundInfo = nullptr;
638 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000639
John McCall69975252015-09-23 22:14:21 +0000640 // Type bounds cannot have qualifiers (even indirectly) or explicit
641 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000642 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000643 QualType typeBound = typeBoundInfo->getType();
644 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
645 if (qual || typeBound.hasQualifiers()) {
646 bool diagnosed = false;
647 SourceRange rangeToRemove;
648 if (qual) {
649 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
650 rangeToRemove = attr.getLocalSourceRange();
651 if (attr.getTypePtr()->getImmediateNullability()) {
652 Diag(attr.getLocStart(),
653 diag::err_objc_type_param_bound_explicit_nullability)
654 << paramName << typeBound
655 << FixItHint::CreateRemoval(rangeToRemove);
656 diagnosed = true;
657 }
658 }
659 }
660
661 if (!diagnosed) {
662 Diag(qual ? qual.getLocStart()
663 : typeBoundInfo->getTypeLoc().getLocStart(),
664 diag::err_objc_type_param_bound_qualified)
665 << paramName << typeBound << typeBound.getQualifiers().getAsString()
666 << FixItHint::CreateRemoval(rangeToRemove);
667 }
668
669 // If the type bound has qualifiers other than CVR, we need to strip
670 // them or we'll probably assert later when trying to apply new
671 // qualifiers.
672 Qualifiers quals = typeBound.getQualifiers();
673 quals.removeCVRQualifiers();
674 if (!quals.empty()) {
675 typeBoundInfo =
676 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
677 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000678 }
679 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000680 }
681
682 // If there was no explicit type bound (or we removed it due to an error),
683 // use 'id' instead.
684 if (!typeBoundInfo) {
685 colonLoc = SourceLocation();
686 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
687 }
688
689 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000690 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
691 index, paramLoc, paramName, colonLoc,
692 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000693}
694
695ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
696 SourceLocation lAngleLoc,
697 ArrayRef<Decl *> typeParamsIn,
698 SourceLocation rAngleLoc) {
699 // We know that the array only contains Objective-C type parameters.
700 ArrayRef<ObjCTypeParamDecl *>
701 typeParams(
702 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
703 typeParamsIn.size());
704
705 // Diagnose redeclarations of type parameters.
706 // We do this now because Objective-C type parameters aren't pushed into
707 // scope until later (after the instance variable block), but we want the
708 // diagnostics to occur right after we parse the type parameter list.
709 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
710 for (auto typeParam : typeParams) {
711 auto known = knownParams.find(typeParam->getIdentifier());
712 if (known != knownParams.end()) {
713 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
714 << typeParam->getIdentifier()
715 << SourceRange(known->second->getLocation());
716
717 typeParam->setInvalidDecl();
718 } else {
719 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
720
721 // Push the type parameter into scope.
722 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
723 }
724 }
725
726 // Create the parameter list.
727 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
728}
729
730void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
731 for (auto typeParam : *typeParamList) {
732 if (!typeParam->isInvalidDecl()) {
733 S->RemoveDecl(typeParam);
734 IdResolver.RemoveDecl(typeParam);
735 }
736 }
737}
738
739namespace {
740 /// The context in which an Objective-C type parameter list occurs, for use
741 /// in diagnostics.
742 enum class TypeParamListContext {
743 ForwardDeclaration,
744 Definition,
745 Category,
746 Extension
747 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000748} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000749
750/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000751/// between a category/extension and an \@interface or between an \@class and an
752/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000753static bool checkTypeParamListConsistency(Sema &S,
754 ObjCTypeParamList *prevTypeParams,
755 ObjCTypeParamList *newTypeParams,
756 TypeParamListContext newContext) {
757 // If the sizes don't match, complain about that.
758 if (prevTypeParams->size() != newTypeParams->size()) {
759 SourceLocation diagLoc;
760 if (newTypeParams->size() > prevTypeParams->size()) {
761 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
762 } else {
763 diagLoc = S.PP.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
764 }
765
766 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
767 << static_cast<unsigned>(newContext)
768 << (newTypeParams->size() > prevTypeParams->size())
769 << prevTypeParams->size()
770 << newTypeParams->size();
771
772 return true;
773 }
774
775 // Match up the type parameters.
776 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
777 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
778 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
779
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000780 // Check for consistency of the variance.
781 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
782 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
783 newContext != TypeParamListContext::Definition) {
784 // When the new type parameter is invariant and is not part
785 // of the definition, just propagate the variance.
786 newTypeParam->setVariance(prevTypeParam->getVariance());
787 } else if (prevTypeParam->getVariance()
788 == ObjCTypeParamVariance::Invariant &&
789 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
790 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
791 ->getDefinition() == prevTypeParam->getDeclContext())) {
792 // When the old parameter is invariant and was not part of the
793 // definition, just ignore the difference because it doesn't
794 // matter.
795 } else {
796 {
797 // Diagnose the conflict and update the second declaration.
798 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
799 if (diagLoc.isInvalid())
800 diagLoc = newTypeParam->getLocStart();
801
802 auto diag = S.Diag(diagLoc,
803 diag::err_objc_type_param_variance_conflict)
804 << static_cast<unsigned>(newTypeParam->getVariance())
805 << newTypeParam->getDeclName()
806 << static_cast<unsigned>(prevTypeParam->getVariance())
807 << prevTypeParam->getDeclName();
808 switch (prevTypeParam->getVariance()) {
809 case ObjCTypeParamVariance::Invariant:
810 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
811 break;
812
813 case ObjCTypeParamVariance::Covariant:
814 case ObjCTypeParamVariance::Contravariant: {
815 StringRef newVarianceStr
816 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
817 ? "__covariant"
818 : "__contravariant";
819 if (newTypeParam->getVariance()
820 == ObjCTypeParamVariance::Invariant) {
821 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
822 (newVarianceStr + " ").str());
823 } else {
824 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
825 newVarianceStr);
826 }
827 }
828 }
829 }
830
831 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
832 << prevTypeParam->getDeclName();
833
834 // Override the variance.
835 newTypeParam->setVariance(prevTypeParam->getVariance());
836 }
837 }
838
Douglas Gregor85f3f952015-07-07 03:57:15 +0000839 // If the bound types match, there's nothing to do.
840 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
841 newTypeParam->getUnderlyingType()))
842 continue;
843
844 // If the new type parameter's bound was explicit, complain about it being
845 // different from the original.
846 if (newTypeParam->hasExplicitBound()) {
847 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
848 ->getTypeLoc().getSourceRange();
849 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
850 << newTypeParam->getUnderlyingType()
851 << newTypeParam->getDeclName()
852 << prevTypeParam->hasExplicitBound()
853 << prevTypeParam->getUnderlyingType()
854 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
855 << prevTypeParam->getDeclName()
856 << FixItHint::CreateReplacement(
857 newBoundRange,
858 prevTypeParam->getUnderlyingType().getAsString(
859 S.Context.getPrintingPolicy()));
860
861 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
862 << prevTypeParam->getDeclName();
863
864 // Override the new type parameter's bound type with the previous type,
865 // so that it's consistent.
866 newTypeParam->setTypeSourceInfo(
867 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
868 continue;
869 }
870
871 // The new type parameter got the implicit bound of 'id'. That's okay for
872 // categories and extensions (overwrite it later), but not for forward
873 // declarations and @interfaces, because those must be standalone.
874 if (newContext == TypeParamListContext::ForwardDeclaration ||
875 newContext == TypeParamListContext::Definition) {
876 // Diagnose this problem for forward declarations and definitions.
877 SourceLocation insertionLoc
878 = S.PP.getLocForEndOfToken(newTypeParam->getLocation());
879 std::string newCode
880 = " : " + prevTypeParam->getUnderlyingType().getAsString(
881 S.Context.getPrintingPolicy());
882 S.Diag(newTypeParam->getLocation(),
883 diag::err_objc_type_param_bound_missing)
884 << prevTypeParam->getUnderlyingType()
885 << newTypeParam->getDeclName()
886 << (newContext == TypeParamListContext::ForwardDeclaration)
887 << FixItHint::CreateInsertion(insertionLoc, newCode);
888
889 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
890 << prevTypeParam->getDeclName();
891 }
892
893 // Update the new type parameter's bound to match the previous one.
894 newTypeParam->setTypeSourceInfo(
895 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
896 }
897
898 return false;
899}
900
John McCall48871652010-08-21 09:40:31 +0000901Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000902ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000903 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000904 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000905 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000906 ArrayRef<ParsedType> SuperTypeArgs,
907 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000908 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000909 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000910 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000911 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000912
Chris Lattnerda463fe2007-12-12 07:09:47 +0000913 // Check for another declaration kind with the same name.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000914 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000915 LookupOrdinaryName, ForRedeclaration);
Douglas Gregor5101c242008-12-05 18:15:24 +0000916
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000917 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000918 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000919 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000920 }
Mike Stump11289f42009-09-09 15:08:12 +0000921
Douglas Gregordc9166c2011-12-15 20:29:51 +0000922 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000923 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000924
925 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
926 // A previous decl with a different name is because of
927 // @compatibility_alias, for example:
928 // \code
929 // @class NewImage;
930 // @compatibility_alias OldImage NewImage;
931 // \endcode
932 // A lookup for 'OldImage' will return the 'NewImage' decl.
933 //
934 // In such a case use the real declaration name, instead of the alias one,
935 // otherwise we will break IdentifierResolver and redecls-chain invariants.
936 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
937 // has been aliased.
938 ClassName = PrevIDecl->getIdentifier();
939 }
940
Douglas Gregor85f3f952015-07-07 03:57:15 +0000941 // If there was a forward declaration with type parameters, check
942 // for consistency.
943 if (PrevIDecl) {
944 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
945 if (typeParamList) {
946 // Both have type parameter lists; check for consistency.
947 if (checkTypeParamListConsistency(*this, prevTypeParamList,
948 typeParamList,
949 TypeParamListContext::Definition)) {
950 typeParamList = nullptr;
951 }
952 } else {
953 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
954 << ClassName;
955 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
956 << ClassName;
957
958 // Clone the type parameter list.
959 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
960 for (auto typeParam : *prevTypeParamList) {
961 clonedTypeParams.push_back(
962 ObjCTypeParamDecl::Create(
963 Context,
964 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000965 typeParam->getVariance(),
966 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000967 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +0000968 SourceLocation(),
969 typeParam->getIdentifier(),
970 SourceLocation(),
971 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
972 }
973
974 typeParamList = ObjCTypeParamList::create(Context,
975 SourceLocation(),
976 clonedTypeParams,
977 SourceLocation());
978 }
979 }
980 }
981
Douglas Gregordc9166c2011-12-15 20:29:51 +0000982 ObjCInterfaceDecl *IDecl
983 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000984 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000985 if (PrevIDecl) {
986 // Class already seen. Was it a definition?
987 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
988 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
989 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +0000990 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000991 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +0000992 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000993 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000994
995 if (AttrList)
996 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
997 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +0000998
Douglas Gregordc9166c2011-12-15 20:29:51 +0000999 // Start the definition of this class. If we're in a redefinition case, there
1000 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001001 if (!IDecl->hasDefinition())
1002 IDecl->startDefinition();
1003
Chris Lattnerda463fe2007-12-12 07:09:47 +00001004 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001005 // Diagnose availability in the context of the @interface.
1006 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001007
Douglas Gregore9d95f12015-07-07 03:57:35 +00001008 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1009 ClassName, ClassLoc,
1010 SuperName, SuperLoc, SuperTypeArgs,
1011 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001012 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001013 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001016 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001017 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001018 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1019 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001020 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001021 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001022 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001023 }
Mike Stump11289f42009-09-09 15:08:12 +00001024
Anders Carlssona6b508a2008-11-04 16:57:32 +00001025 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001026 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001027}
1028
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001029/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1030/// typedef'ed use for a qualified super class and adds them to the list
1031/// of the protocols.
1032void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1033 IdentifierInfo *SuperName,
1034 SourceLocation SuperLoc) {
1035 if (!SuperName)
1036 return;
1037 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1038 LookupOrdinaryName);
1039 if (!IDecl)
1040 return;
1041
1042 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1043 QualType T = TDecl->getUnderlyingType();
1044 if (T->isObjCObjectType())
1045 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
Benjamin Kramerf9890422015-02-17 16:48:30 +00001046 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001047 }
1048}
1049
Richard Smithac4e36d2012-08-08 23:32:13 +00001050/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001051/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001052Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1053 IdentifierInfo *AliasName,
1054 SourceLocation AliasLocation,
1055 IdentifierInfo *ClassName,
1056 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001057 // Look for previous declaration of alias name
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001058 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001059 LookupOrdinaryName, ForRedeclaration);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001060 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001061 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001062 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001063 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001064 }
1065 // Check for class declaration
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001066 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001067 LookupOrdinaryName, ForRedeclaration);
Richard Smithdda56e42011-04-15 14:24:37 +00001068 if (const TypedefNameDecl *TDecl =
1069 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001070 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001071 if (T->isObjCObjectType()) {
1072 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001073 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001074 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001075 LookupOrdinaryName, ForRedeclaration);
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001076 }
1077 }
1078 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001079 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001080 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001081 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001082 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001083 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001084 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001085 }
Mike Stump11289f42009-09-09 15:08:12 +00001086
Chris Lattner219b3e92008-03-16 21:17:37 +00001087 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001088 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001089 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001090
Anders Carlssona6b508a2008-11-04 16:57:32 +00001091 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001092 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001093
John McCall48871652010-08-21 09:40:31 +00001094 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001095}
1096
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001097bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001098 IdentifierInfo *PName,
1099 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001100 const ObjCList<ObjCProtocolDecl> &PList) {
1101
1102 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001103 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1104 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001105 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1106 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001107 if (PDecl->getIdentifier() == PName) {
1108 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1109 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001110 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001111 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001112
1113 if (!PDecl->hasDefinition())
1114 continue;
1115
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001116 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1117 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1118 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001119 }
1120 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001121 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001122}
1123
John McCall48871652010-08-21 09:40:31 +00001124Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001125Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1126 IdentifierInfo *ProtocolName,
1127 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001128 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001129 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001130 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001131 SourceLocation EndProtoLoc,
1132 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001133 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001134 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001135 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001136 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1137 ForRedeclaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 ObjCProtocolDecl *PDecl = nullptr;
1139 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001140 // If we already have a definition, complain.
1141 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1142 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001143
Douglas Gregor32c17572012-01-01 20:30:41 +00001144 // Create a new protocol that is completely distinct from previous
1145 // declarations, and do not make this protocol available for name lookup.
1146 // That way, we'll end up completely ignoring the duplicate.
1147 // FIXME: Can we turn this into an error?
1148 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1149 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001150 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001151 PDecl->startDefinition();
1152 } else {
1153 if (PrevDecl) {
1154 // Check for circular dependencies among protocol declarations. This can
1155 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001156 ObjCList<ObjCProtocolDecl> PList;
1157 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1158 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001159 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001160 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001161
1162 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001163 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001164 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001165 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001166
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001167 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001168 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001169 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001170
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001171 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001172 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001173
1174 // Merge attributes from previous declarations.
1175 if (PrevDecl)
1176 mergeDeclAttributes(PDecl, PrevDecl);
1177
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001178 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001179 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001180 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1181 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001182 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001183 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001184 }
Mike Stump11289f42009-09-09 15:08:12 +00001185
1186 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001187 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001188}
1189
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001190static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1191 ObjCProtocolDecl *&UndefinedProtocol) {
1192 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1193 UndefinedProtocol = PDecl;
1194 return true;
1195 }
1196
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001197 for (auto *PI : PDecl->protocols())
1198 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1199 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001200 return true;
1201 }
1202 return false;
1203}
1204
Chris Lattnerda463fe2007-12-12 07:09:47 +00001205/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001206/// issues an error if they are not declared. It returns list of
1207/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001208void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001209Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001210 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001211 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001212 for (const IdentifierLocPair &Pair : ProtocolId) {
1213 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001214 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001215 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001216 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001217 LookupObjCProtocolName, TUScope, nullptr,
1218 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001219 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001220 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1221 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001222 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001223 }
1224
1225 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001226 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001227 continue;
1228 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001229 // If this is a forward protocol declaration, get its definition.
1230 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1231 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001232
1233 // For an objc container, delay protocol reference checking until after we
1234 // can set the objc decl as the availability context, otherwise check now.
1235 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001236 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001237 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001238
1239 // If this is a forward declaration and we are supposed to warn in this
1240 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001241 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001242 ObjCProtocolDecl *UndefinedProtocol;
1243
Douglas Gregoreed49792013-01-17 00:38:46 +00001244 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001245 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001246 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001247 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1248 << UndefinedProtocol;
1249 }
John McCall48871652010-08-21 09:40:31 +00001250 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001251 }
1252}
1253
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001254namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001255// Callback to only accept typo corrections that are either
1256// Objective-C protocols or valid Objective-C type arguments.
1257class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1258 ASTContext &Context;
1259 Sema::LookupNameKind LookupKind;
1260 public:
1261 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1262 Sema::LookupNameKind lookupKind)
1263 : Context(context), LookupKind(lookupKind) { }
1264
1265 bool ValidateCandidate(const TypoCorrection &candidate) override {
1266 // If we're allowed to find protocols and we have a protocol, accept it.
1267 if (LookupKind != Sema::LookupOrdinaryName) {
1268 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1269 return true;
1270 }
1271
1272 // If we're allowed to find type names and we have one, accept it.
1273 if (LookupKind != Sema::LookupObjCProtocolName) {
1274 // If we have a type declaration, we might accept this result.
1275 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1276 // If we found a tag declaration outside of C++, skip it. This
1277 // can happy because we look for any name when there is no
1278 // bias to protocol or type names.
1279 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1280 return false;
1281
1282 // Make sure the type is something we would accept as a type
1283 // argument.
1284 auto type = Context.getTypeDeclType(typeDecl);
1285 if (type->isObjCObjectPointerType() ||
1286 type->isBlockPointerType() ||
1287 type->isDependentType() ||
1288 type->isObjCObjectType())
1289 return true;
1290
1291 return false;
1292 }
1293
1294 // If we have an Objective-C class type, accept it; there will
1295 // be another fix to add the '*'.
1296 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1297 return true;
1298
1299 return false;
1300 }
1301
1302 return false;
1303 }
1304};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001305} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001306
1307void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1308 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001309 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001310 SourceLocation lAngleLoc,
1311 ArrayRef<IdentifierInfo *> identifiers,
1312 ArrayRef<SourceLocation> identifierLocs,
1313 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001314 SourceLocation &typeArgsLAngleLoc,
1315 SmallVectorImpl<ParsedType> &typeArgs,
1316 SourceLocation &typeArgsRAngleLoc,
1317 SourceLocation &protocolLAngleLoc,
1318 SmallVectorImpl<Decl *> &protocols,
1319 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001320 bool warnOnIncompleteProtocols) {
1321 // Local function that updates the declaration specifiers with
1322 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001323 unsigned numProtocolsResolved = 0;
1324 auto resolvedAsProtocols = [&] {
1325 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1326
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001327 // Determine whether the base type is a parameterized class, in
1328 // which case we want to warn about typos such as
1329 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1330 ObjCInterfaceDecl *baseClass = nullptr;
1331 QualType base = GetTypeFromParser(baseType, nullptr);
1332 bool allAreTypeNames = false;
1333 SourceLocation firstClassNameLoc;
1334 if (!base.isNull()) {
1335 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1336 baseClass = objcObjectType->getInterface();
1337 if (baseClass) {
1338 if (auto typeParams = baseClass->getTypeParamList()) {
1339 if (typeParams->size() == numProtocolsResolved) {
1340 // Note that we should be looking for type names, too.
1341 allAreTypeNames = true;
1342 }
1343 }
1344 }
1345 }
1346 }
1347
Douglas Gregore9d95f12015-07-07 03:57:35 +00001348 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001349 ObjCProtocolDecl *&proto
1350 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001351 // For an objc container, delay protocol reference checking until after we
1352 // can set the objc decl as the availability context, otherwise check now.
1353 if (!warnOnIncompleteProtocols) {
1354 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1355 }
1356
1357 // If this is a forward protocol declaration, get its definition.
1358 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1359 proto = proto->getDefinition();
1360
1361 // If this is a forward declaration and we are supposed to warn in this
1362 // case, do it.
1363 // FIXME: Recover nicely in the hidden case.
1364 ObjCProtocolDecl *forwardDecl = nullptr;
1365 if (warnOnIncompleteProtocols &&
1366 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1367 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1368 << proto->getDeclName();
1369 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1370 << forwardDecl;
1371 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001372
1373 // If everything this far has been a type name (and we care
1374 // about such things), check whether this name refers to a type
1375 // as well.
1376 if (allAreTypeNames) {
1377 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1378 LookupOrdinaryName)) {
1379 if (isa<ObjCInterfaceDecl>(decl)) {
1380 if (firstClassNameLoc.isInvalid())
1381 firstClassNameLoc = identifierLocs[i];
1382 } else if (!isa<TypeDecl>(decl)) {
1383 // Not a type.
1384 allAreTypeNames = false;
1385 }
1386 } else {
1387 allAreTypeNames = false;
1388 }
1389 }
1390 }
1391
1392 // All of the protocols listed also have type names, and at least
1393 // one is an Objective-C class name. Check whether all of the
1394 // protocol conformances are declared by the base class itself, in
1395 // which case we warn.
1396 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1397 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1398 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1399 bool allProtocolsDeclared = true;
1400 for (auto proto : protocols) {
1401 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1402 allProtocolsDeclared = false;
1403 break;
1404 }
1405 }
1406
1407 if (allProtocolsDeclared) {
1408 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1409 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1410 << FixItHint::CreateInsertion(
1411 PP.getLocForEndOfToken(firstClassNameLoc), " *");
1412 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001413 }
1414
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001415 protocolLAngleLoc = lAngleLoc;
1416 protocolRAngleLoc = rAngleLoc;
1417 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001418 };
1419
1420 // Attempt to resolve all of the identifiers as protocols.
1421 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1422 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1423 protocols.push_back(proto);
1424 if (proto)
1425 ++numProtocolsResolved;
1426 }
1427
1428 // If all of the names were protocols, these were protocol qualifiers.
1429 if (numProtocolsResolved == identifiers.size())
1430 return resolvedAsProtocols();
1431
1432 // Attempt to resolve all of the identifiers as type names or
1433 // Objective-C class names. The latter is technically ill-formed,
1434 // but is probably something like \c NSArray<NSView *> missing the
1435 // \c*.
1436 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1437 SmallVector<TypeOrClassDecl, 4> typeDecls;
1438 unsigned numTypeDeclsResolved = 0;
1439 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1440 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1441 LookupOrdinaryName);
1442 if (!decl) {
1443 typeDecls.push_back(TypeOrClassDecl());
1444 continue;
1445 }
1446
1447 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1448 typeDecls.push_back(typeDecl);
1449 ++numTypeDeclsResolved;
1450 continue;
1451 }
1452
1453 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1454 typeDecls.push_back(objcClass);
1455 ++numTypeDeclsResolved;
1456 continue;
1457 }
1458
1459 typeDecls.push_back(TypeOrClassDecl());
1460 }
1461
1462 AttributeFactory attrFactory;
1463
1464 // Local function that forms a reference to the given type or
1465 // Objective-C class declaration.
1466 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1467 -> TypeResult {
1468 // Form declaration specifiers. They simply refer to the type.
1469 DeclSpec DS(attrFactory);
1470 const char* prevSpec; // unused
1471 unsigned diagID; // unused
1472 QualType type;
1473 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1474 type = Context.getTypeDeclType(actualTypeDecl);
1475 else
1476 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1477 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1478 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1479 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1480 parsedType, Context.getPrintingPolicy());
1481 // Use the identifier location for the type source range.
1482 DS.SetRangeStart(loc);
1483 DS.SetRangeEnd(loc);
1484
1485 // Form the declarator.
1486 Declarator D(DS, Declarator::TypeNameContext);
1487
1488 // If we have a typedef of an Objective-C class type that is missing a '*',
1489 // add the '*'.
1490 if (type->getAs<ObjCInterfaceType>()) {
1491 SourceLocation starLoc = PP.getLocForEndOfToken(loc);
1492 ParsedAttributes parsedAttrs(attrFactory);
1493 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1494 SourceLocation(),
1495 SourceLocation(),
1496 SourceLocation(),
1497 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001498 parsedAttrs,
1499 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001500
1501 // Diagnose the missing '*'.
1502 Diag(loc, diag::err_objc_type_arg_missing_star)
1503 << type
1504 << FixItHint::CreateInsertion(starLoc, " *");
1505 }
1506
1507 // Convert this to a type.
1508 return ActOnTypeName(S, D);
1509 };
1510
1511 // Local function that updates the declaration specifiers with
1512 // type argument information.
1513 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001514 // We did not resolve these as protocols.
1515 protocols.clear();
1516
Douglas Gregore9d95f12015-07-07 03:57:35 +00001517 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1518 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001519 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1520 // Map type reference to a type.
1521 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001522 if (!type.isUsable()) {
1523 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001524 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001525 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001526
1527 typeArgs.push_back(type.get());
1528 }
1529
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001530 typeArgsLAngleLoc = lAngleLoc;
1531 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001532 };
1533
1534 // If all of the identifiers can be resolved as type names or
1535 // Objective-C class names, we have type arguments.
1536 if (numTypeDeclsResolved == identifiers.size())
1537 return resolvedAsTypeDecls();
1538
1539 // Error recovery: some names weren't found, or we have a mix of
1540 // type and protocol names. Go resolve all of the unresolved names
1541 // and complain if we can't find a consistent answer.
1542 LookupNameKind lookupKind = LookupAnyName;
1543 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1544 // If we already have a protocol or type. Check whether it is the
1545 // right thing.
1546 if (protocols[i] || typeDecls[i]) {
1547 // If we haven't figured out whether we want types or protocols
1548 // yet, try to figure it out from this name.
1549 if (lookupKind == LookupAnyName) {
1550 // If this name refers to both a protocol and a type (e.g., \c
1551 // NSObject), don't conclude anything yet.
1552 if (protocols[i] && typeDecls[i])
1553 continue;
1554
1555 // Otherwise, let this name decide whether we'll be correcting
1556 // toward types or protocols.
1557 lookupKind = protocols[i] ? LookupObjCProtocolName
1558 : LookupOrdinaryName;
1559 continue;
1560 }
1561
1562 // If we want protocols and we have a protocol, there's nothing
1563 // more to do.
1564 if (lookupKind == LookupObjCProtocolName && protocols[i])
1565 continue;
1566
1567 // If we want types and we have a type declaration, there's
1568 // nothing more to do.
1569 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1570 continue;
1571
1572 // We have a conflict: some names refer to protocols and others
1573 // refer to types.
1574 Diag(identifierLocs[i], diag::err_objc_type_args_and_protocols)
1575 << (protocols[i] != nullptr)
1576 << identifiers[i]
1577 << identifiers[0]
1578 << SourceRange(identifierLocs[0]);
1579
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001580 protocols.clear();
1581 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001582 return;
1583 }
1584
1585 // Perform typo correction on the name.
1586 TypoCorrection corrected = CorrectTypo(
1587 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1588 nullptr,
1589 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1590 lookupKind),
1591 CTK_ErrorRecovery);
1592 if (corrected) {
1593 // Did we find a protocol?
1594 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1595 diagnoseTypo(corrected,
1596 PDiag(diag::err_undeclared_protocol_suggest)
1597 << identifiers[i]);
1598 lookupKind = LookupObjCProtocolName;
1599 protocols[i] = proto;
1600 ++numProtocolsResolved;
1601 continue;
1602 }
1603
1604 // Did we find a type?
1605 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1606 diagnoseTypo(corrected,
1607 PDiag(diag::err_unknown_typename_suggest)
1608 << identifiers[i]);
1609 lookupKind = LookupOrdinaryName;
1610 typeDecls[i] = typeDecl;
1611 ++numTypeDeclsResolved;
1612 continue;
1613 }
1614
1615 // Did we find an Objective-C class?
1616 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1617 diagnoseTypo(corrected,
1618 PDiag(diag::err_unknown_type_or_class_name_suggest)
1619 << identifiers[i] << true);
1620 lookupKind = LookupOrdinaryName;
1621 typeDecls[i] = objcClass;
1622 ++numTypeDeclsResolved;
1623 continue;
1624 }
1625 }
1626
1627 // We couldn't find anything.
1628 Diag(identifierLocs[i],
1629 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1630 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1631 : diag::err_unknown_typename))
1632 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001633 protocols.clear();
1634 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001635 return;
1636 }
1637
1638 // If all of the names were (corrected to) protocols, these were
1639 // protocol qualifiers.
1640 if (numProtocolsResolved == identifiers.size())
1641 return resolvedAsProtocols();
1642
1643 // Otherwise, all of the names were (corrected to) types.
1644 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1645 return resolvedAsTypeDecls();
1646}
1647
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001648/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001649/// a class method in its extension.
1650///
Mike Stump11289f42009-09-09 15:08:12 +00001651void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001652 ObjCInterfaceDecl *ID) {
1653 if (!ID)
1654 return; // Possibly due to previous error
1655
1656 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001657 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001658 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001659
1660 if (MethodMap.empty())
1661 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001662 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001663 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001664 if (PrevMethod &&
1665 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1666 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001667 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1668 << Method->getDeclName();
1669 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1670 }
1671 }
1672}
1673
James Dennett634962f2012-06-14 21:40:34 +00001674/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001675Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001676Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001677 ArrayRef<IdentifierLocPair> IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001678 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001679 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001680 for (const IdentifierLocPair &IdentPair : IdentList) {
1681 IdentifierInfo *Ident = IdentPair.first;
1682 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Douglas Gregor32c17572012-01-01 20:30:41 +00001683 ForRedeclaration);
1684 ObjCProtocolDecl *PDecl
1685 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001686 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001687 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001688
1689 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001690 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001691
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001692 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001693 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001694
1695 if (PrevDecl)
1696 mergeDeclAttributes(PDecl, PrevDecl);
1697
Douglas Gregorf6102672012-01-01 21:23:57 +00001698 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001699 }
Mike Stump11289f42009-09-09 15:08:12 +00001700
Rafael Espindolaab417692013-07-09 12:05:01 +00001701 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001702}
1703
John McCall48871652010-08-21 09:40:31 +00001704Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001705ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1706 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001707 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001708 IdentifierInfo *CategoryName,
1709 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001710 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001711 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001712 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001713 SourceLocation EndProtoLoc) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001714 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001715 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001716
1717 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001718
1719 if (!IDecl
1720 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001721 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001722 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001723 // Create an invalid ObjCCategoryDecl to serve as context for
1724 // the enclosing method declarations. We mark the decl invalid
1725 // to make it clear that this isn't a valid AST.
1726 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001727 ClassLoc, CategoryLoc, CategoryName,
1728 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001729 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001730 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001731
1732 if (!IDecl)
1733 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001734 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001735 }
1736
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001737 if (!CategoryName && IDecl->getImplementation()) {
1738 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1739 Diag(IDecl->getImplementation()->getLocation(),
1740 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001741 }
1742
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001743 if (CategoryName) {
1744 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001745 if (ObjCCategoryDecl *Previous
1746 = IDecl->FindCategoryDeclaration(CategoryName)) {
1747 // Class extensions can be declared multiple times, categories cannot.
1748 Diag(CategoryLoc, diag::warn_dup_category_def)
1749 << ClassName << CategoryName;
1750 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001751 }
1752 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001753
Douglas Gregor85f3f952015-07-07 03:57:15 +00001754 // If we have a type parameter list, check it.
1755 if (typeParamList) {
1756 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1757 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1758 CategoryName
1759 ? TypeParamListContext::Category
1760 : TypeParamListContext::Extension))
1761 typeParamList = nullptr;
1762 } else {
1763 Diag(typeParamList->getLAngleLoc(),
1764 diag::err_objc_parameterized_category_nonclass)
1765 << (CategoryName != nullptr)
1766 << ClassName
1767 << typeParamList->getSourceRange();
1768
1769 typeParamList = nullptr;
1770 }
1771 }
1772
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001773 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001774 ClassLoc, CategoryLoc, CategoryName, IDecl,
1775 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001776 // FIXME: PushOnScopeChains?
1777 CurContext->addDecl(CDecl);
1778
Chris Lattnerda463fe2007-12-12 07:09:47 +00001779 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001780 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1781 NumProtoRefs, ProtoLocs);
1782 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001783 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001784 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001785 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001786 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001787 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001788 }
Mike Stump11289f42009-09-09 15:08:12 +00001789
Anders Carlssona6b508a2008-11-04 16:57:32 +00001790 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001791 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001792}
1793
1794/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001795/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001796/// object.
John McCall48871652010-08-21 09:40:31 +00001797Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001798 SourceLocation AtCatImplLoc,
1799 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1800 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001801 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001802 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001803 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001804 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1805 if (!CatIDecl) {
1806 // Category @implementation with no corresponding @interface.
1807 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001808 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1809 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001810 CatName, IDecl,
1811 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001812 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001813 }
1814 }
1815
Mike Stump11289f42009-09-09 15:08:12 +00001816 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001817 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001818 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001819 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001820 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001821 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001822 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001823 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1824 diag::err_undef_interface)) {
1825 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001826 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001827
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001828 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001829 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001830
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +00001831 // If the interface is deprecated/unavailable, warn/error about it.
1832 if (IDecl)
1833 DiagnoseUseOfDecl(IDecl, ClassLoc);
1834
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001835 /// Check that CatName, category name, is not used in another implementation.
1836 if (CatIDecl) {
1837 if (CatIDecl->getImplementation()) {
1838 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1839 << CatName;
1840 Diag(CatIDecl->getImplementation()->getLocation(),
1841 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001842 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001843 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001844 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001845 // Warn on implementating category of deprecated class under
1846 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001847 DiagnoseObjCImplementedDeprecations(*this,
1848 dyn_cast<NamedDecl>(IDecl),
1849 CDecl->getLocation(), 2);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001850 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001851 }
Mike Stump11289f42009-09-09 15:08:12 +00001852
Anders Carlssona6b508a2008-11-04 16:57:32 +00001853 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001854 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001855}
1856
John McCall48871652010-08-21 09:40:31 +00001857Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001858 SourceLocation AtClassImplLoc,
1859 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001860 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001861 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001862 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001863 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001864 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001865 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1866 ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001867 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001868 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001869 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001870 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001871 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1872 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001873 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001874 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001875 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001876 TypoCorrection Corrected = CorrectTypo(
1877 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1878 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001879 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1880 // Suggest the (potentially) correct interface name. Don't provide a
1881 // code-modification hint or use the typo name for recovery, because
1882 // this is just a warning. The program may actually be correct.
1883 diagnoseTypo(Corrected,
1884 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1885 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001886 } else {
1887 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1888 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001889 }
Mike Stump11289f42009-09-09 15:08:12 +00001890
Chris Lattnerda463fe2007-12-12 07:09:47 +00001891 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001892 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001893 if (SuperClassname) {
1894 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001895 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1896 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001897 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001898 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1899 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001900 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001901 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001902 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001903 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001904 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001905 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001906 Diag(SuperClassLoc, diag::err_undef_superclass)
1907 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001908 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001909 // This implementation and its interface do not have the same
1910 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001911 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001912 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001913 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001914 }
1915 }
1916 }
Mike Stump11289f42009-09-09 15:08:12 +00001917
Chris Lattnerda463fe2007-12-12 07:09:47 +00001918 if (!IDecl) {
1919 // Legacy case of @implementation with no corresponding @interface.
1920 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001921
Mike Stump87c57ac2009-05-16 07:39:55 +00001922 // FIXME: Do we support attributes on the @implementation? If so we should
1923 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001924 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001925 ClassName, /*typeParamList=*/nullptr,
1926 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001927 true);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001928 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00001929 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001930 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1931 Context.getObjCInterfaceType(SDecl),
1932 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00001933 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1934 } else {
1935 IDecl->setEndOfDefinitionLoc(ClassLoc);
1936 }
1937
Douglas Gregorac345a32009-04-24 00:16:12 +00001938 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00001939 } else {
1940 // Mark the interface as being completed, even if it was just as
1941 // @class ....;
1942 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001943 if (!IDecl->hasDefinition())
1944 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001945 }
Mike Stump11289f42009-09-09 15:08:12 +00001946
1947 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001948 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00001949 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001950
Anders Carlssona6b508a2008-11-04 16:57:32 +00001951 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001952 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001953
Chris Lattnerda463fe2007-12-12 07:09:47 +00001954 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00001955 if (IDecl->getImplementation()) {
1956 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001957 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001958 Diag(IDecl->getImplementation()->getLocation(),
1959 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001960 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00001961 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001962 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00001963 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001964 // Warn on implementating deprecated class under
1965 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001966 DiagnoseObjCImplementedDeprecations(*this,
1967 dyn_cast<NamedDecl>(IDecl),
1968 IMPDecl->getLocation(), 1);
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001969 }
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001970 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001971}
1972
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001973Sema::DeclGroupPtrTy
1974Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1975 SmallVector<Decl *, 64> DeclsInGroup;
1976 DeclsInGroup.reserve(Decls.size() + 1);
1977
1978 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1979 Decl *Dcl = Decls[i];
1980 if (!Dcl)
1981 continue;
1982 if (Dcl->getDeclContext()->isFileContext())
1983 Dcl->setTopLevelDeclInObjCContainer();
1984 DeclsInGroup.push_back(Dcl);
1985 }
1986
1987 DeclsInGroup.push_back(ObjCImpDecl);
1988
Rafael Espindolaab417692013-07-09 12:05:01 +00001989 return BuildDeclaratorGroup(DeclsInGroup, false);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001990}
1991
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001992void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1993 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001994 SourceLocation RBrace) {
1995 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001996 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001997 if (!IDecl)
1998 return;
James Dennett634962f2012-06-14 21:40:34 +00001999 /// Check case of non-existing \@interface decl.
2000 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002001 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002002 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002003 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002004 // Add ivar's to class's DeclContext.
2005 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002006 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002007 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002008 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002009 }
2010
Chris Lattnerda463fe2007-12-12 07:09:47 +00002011 return;
2012 }
2013 // If implementation has empty ivar list, just return.
2014 if (numIvars == 0)
2015 return;
Mike Stump11289f42009-09-09 15:08:12 +00002016
Chris Lattnerda463fe2007-12-12 07:09:47 +00002017 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002018 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002019 if (ImpDecl->getSuperClass())
2020 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2021 for (unsigned i = 0; i < numIvars; i++) {
2022 ObjCIvarDecl* ImplIvar = ivars[i];
2023 if (const ObjCIvarDecl *ClsIvar =
2024 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2025 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2026 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2027 continue;
2028 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002029 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002030 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002031 if (const ObjCIvarDecl *ClsExtIvar =
2032 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2033 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2034 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2035 continue;
2036 }
2037 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002038 // Instance ivar to Implementation's DeclContext.
2039 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002040 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002041 ImpDecl->addDecl(ImplIvar);
2042 }
2043 return;
2044 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002045 // Check interface's Ivar list against those in the implementation.
2046 // names and types must match.
2047 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002048 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002049 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002050 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2051 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002052 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002053 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002054 assert (ImplIvar && "missing implementation ivar");
2055 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002056
Steve Naroff157599f2009-03-03 14:49:36 +00002057 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002058 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002059 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002060 << ImplIvar->getIdentifier()
2061 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002062 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002063 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2064 ImplIvar->getBitWidthValue(Context) !=
2065 ClsIvar->getBitWidthValue(Context)) {
2066 Diag(ImplIvar->getBitWidth()->getLocStart(),
2067 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2068 Diag(ClsIvar->getBitWidth()->getLocStart(),
2069 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002070 }
Steve Naroff157599f2009-03-03 14:49:36 +00002071 // Make sure the names are identical.
2072 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002073 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002074 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002075 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002076 }
2077 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002078 }
Mike Stump11289f42009-09-09 15:08:12 +00002079
Chris Lattner0f29d982007-12-12 18:11:49 +00002080 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002081 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002082 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002083 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002084}
2085
Ted Kremenekf87decd2013-12-13 05:58:44 +00002086static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2087 ObjCMethodDecl *method,
2088 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002089 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002090 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002091 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002092 switch (method->getAvailability()) {
2093 case AR_Available:
2094 case AR_Deprecated:
2095 break;
2096
2097 // Don't warn about unavailable or not-yet-introduced methods.
2098 case AR_NotYetIntroduced:
2099 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002100 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002101 }
2102
Ted Kremenek65d63572013-03-27 00:02:21 +00002103 // FIXME: For now ignore 'IncompleteImpl'.
2104 // Previously we grouped all unimplemented methods under a single
2105 // warning, but some users strongly voiced that they would prefer
2106 // separate warnings. We will give that approach a try, as that
2107 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002108 {
2109 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2110 B << method;
2111 if (NeededFor)
2112 B << NeededFor;
2113 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002114
2115 // Issue a note to the original declaration.
2116 SourceLocation MethodLoc = method->getLocStart();
2117 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002118 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002119}
2120
David Chisnallb62d15c2010-10-25 17:23:52 +00002121/// Determines if type B can be substituted for type A. Returns true if we can
2122/// guarantee that anything that the user will do to an object of type A can
2123/// also be done to an object of type B. This is trivially true if the two
2124/// types are the same, or if B is a subclass of A. It becomes more complex
2125/// in cases where protocols are involved.
2126///
2127/// Object types in Objective-C describe the minimum requirements for an
2128/// object, rather than providing a complete description of a type. For
2129/// example, if A is a subclass of B, then B* may refer to an instance of A.
2130/// The principle of substitutability means that we may use an instance of A
2131/// anywhere that we may use an instance of B - it will implement all of the
2132/// ivars of B and all of the methods of B.
2133///
2134/// This substitutability is important when type checking methods, because
2135/// the implementation may have stricter type definitions than the interface.
2136/// The interface specifies minimum requirements, but the implementation may
2137/// have more accurate ones. For example, a method may privately accept
2138/// instances of B, but only publish that it accepts instances of A. Any
2139/// object passed to it will be type checked against B, and so will implicitly
2140/// by a valid A*. Similarly, a method may return a subclass of the class that
2141/// it is declared as returning.
2142///
2143/// This is most important when considering subclassing. A method in a
2144/// subclass must accept any object as an argument that its superclass's
2145/// implementation accepts. It may, however, accept a more general type
2146/// without breaking substitutability (i.e. you can still use the subclass
2147/// anywhere that you can use the superclass, but not vice versa). The
2148/// converse requirement applies to return types: the return type for a
2149/// subclass method must be a valid object of the kind that the superclass
2150/// advertises, but it may be specified more accurately. This avoids the need
2151/// for explicit down-casting by callers.
2152///
2153/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002154static bool isObjCTypeSubstitutable(ASTContext &Context,
2155 const ObjCObjectPointerType *A,
2156 const ObjCObjectPointerType *B,
2157 bool rejectId) {
2158 // Reject a protocol-unqualified id.
2159 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002160
2161 // If B is a qualified id, then A must also be a qualified id and it must
2162 // implement all of the protocols in B. It may not be a qualified class.
2163 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2164 // stricter definition so it is not substitutable for id<A>.
2165 if (B->isObjCQualifiedIdType()) {
2166 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002167 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2168 QualType(B,0),
2169 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002170 }
2171
2172 /*
2173 // id is a special type that bypasses type checking completely. We want a
2174 // warning when it is used in one place but not another.
2175 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2176
2177
2178 // If B is a qualified id, then A must also be a qualified id (which it isn't
2179 // if we've got this far)
2180 if (B->isObjCQualifiedIdType()) return false;
2181 */
2182
2183 // Now we know that A and B are (potentially-qualified) class types. The
2184 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002185 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002186}
2187
John McCall071df462010-10-28 02:34:38 +00002188static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2189 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2190}
2191
Douglas Gregor813a0662015-06-19 18:14:38 +00002192/// Determine whether two set of Objective-C declaration qualifiers conflict.
2193static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2194 Decl::ObjCDeclQualifier y) {
2195 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2196 (y & ~Decl::OBJC_TQ_CSNullability);
2197}
2198
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002199static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002200 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002201 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002202 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002203 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002204 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002205 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002206 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2207 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002208 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002209 S.Diag(MethodImpl->getLocation(),
2210 (IsOverridingMode
2211 ? diag::warn_conflicting_overriding_ret_type_modifiers
2212 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002213 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002214 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002215 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002216 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002217 }
2218 else
2219 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002220 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002221 if (Warn && IsOverridingMode &&
2222 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2223 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2224 MethodDecl->getReturnType(),
2225 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002226 auto nullabilityMethodImpl =
2227 *MethodImpl->getReturnType()->getNullability(S.Context);
2228 auto nullabilityMethodDecl =
2229 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002230 S.Diag(MethodImpl->getLocation(),
2231 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002232 << DiagNullabilityKind(
2233 nullabilityMethodImpl,
2234 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2235 != 0))
2236 << DiagNullabilityKind(
2237 nullabilityMethodDecl,
2238 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2239 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002240 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2241 }
2242
Alp Toker314cc812014-01-25 16:55:45 +00002243 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2244 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002245 return true;
2246 if (!Warn)
2247 return false;
John McCall071df462010-10-28 02:34:38 +00002248
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002249 unsigned DiagID =
2250 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2251 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002252
2253 // Mismatches between ObjC pointers go into a different warning
2254 // category, and sometimes they're even completely whitelisted.
2255 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002256 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002257 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002258 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002259 // Allow non-matching return types as long as they don't violate
2260 // the principle of substitutability. Specifically, we permit
2261 // return types that are subclasses of the declared return type,
2262 // or that are more-qualified versions of the declared type.
2263 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002264 return false;
John McCall071df462010-10-28 02:34:38 +00002265
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002266 DiagID =
2267 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2268 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002269 }
2270 }
2271
2272 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002273 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2274 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002275 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002276 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2277 ? diag::note_previous_declaration
2278 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002279 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002280 return false;
John McCall071df462010-10-28 02:34:38 +00002281}
2282
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002283static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002284 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002285 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002286 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002287 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002288 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002289 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002290 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002291 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002292 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2293 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002294 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002295 if (IsOverridingMode)
2296 S.Diag(ImplVar->getLocation(),
2297 diag::warn_conflicting_overriding_param_modifiers)
2298 << getTypeRange(ImplVar->getTypeSourceInfo())
2299 << MethodImpl->getDeclName();
2300 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002301 diag::warn_conflicting_param_modifiers)
2302 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002303 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002304 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2305 << getTypeRange(IfaceVar->getTypeSourceInfo());
2306 }
2307 else
2308 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002309 }
2310
John McCall071df462010-10-28 02:34:38 +00002311 QualType ImplTy = ImplVar->getType();
2312 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002313 if (Warn && IsOverridingMode &&
2314 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2315 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002316 S.Diag(ImplVar->getLocation(),
2317 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002318 << DiagNullabilityKind(
2319 *ImplTy->getNullability(S.Context),
2320 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2321 != 0))
2322 << DiagNullabilityKind(
2323 *IfaceTy->getNullability(S.Context),
2324 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2325 != 0));
2326 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002327 }
John McCall071df462010-10-28 02:34:38 +00002328 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002329 return true;
2330
2331 if (!Warn)
2332 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002333 unsigned DiagID =
2334 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2335 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002336
2337 // Mismatches between ObjC pointers go into a different warning
2338 // category, and sometimes they're even completely whitelisted.
2339 if (const ObjCObjectPointerType *ImplPtrTy =
2340 ImplTy->getAs<ObjCObjectPointerType>()) {
2341 if (const ObjCObjectPointerType *IfacePtrTy =
2342 IfaceTy->getAs<ObjCObjectPointerType>()) {
2343 // Allow non-matching argument types as long as they don't
2344 // violate the principle of substitutability. Specifically, the
2345 // implementation must accept any objects that the superclass
2346 // accepts, however it may also accept others.
2347 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002348 return false;
John McCall071df462010-10-28 02:34:38 +00002349
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002350 DiagID =
2351 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2352 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002353 }
2354 }
2355
2356 S.Diag(ImplVar->getLocation(), DiagID)
2357 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002358 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2359 S.Diag(IfaceVar->getLocation(),
2360 (IsOverridingMode ? diag::note_previous_declaration
2361 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002362 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002363 return false;
John McCall071df462010-10-28 02:34:38 +00002364}
John McCall31168b02011-06-15 23:02:42 +00002365
2366/// In ARC, check whether the conventional meanings of the two methods
2367/// match. If they don't, it's a hard error.
2368static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2369 ObjCMethodDecl *decl) {
2370 ObjCMethodFamily implFamily = impl->getMethodFamily();
2371 ObjCMethodFamily declFamily = decl->getMethodFamily();
2372 if (implFamily == declFamily) return false;
2373
2374 // Since conventions are sorted by selector, the only possibility is
2375 // that the types differ enough to cause one selector or the other
2376 // to fall out of the family.
2377 assert(implFamily == OMF_None || declFamily == OMF_None);
2378
2379 // No further diagnostics required on invalid declarations.
2380 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2381
2382 const ObjCMethodDecl *unmatched = impl;
2383 ObjCMethodFamily family = declFamily;
2384 unsigned errorID = diag::err_arc_lost_method_convention;
2385 unsigned noteID = diag::note_arc_lost_method_convention;
2386 if (declFamily == OMF_None) {
2387 unmatched = decl;
2388 family = implFamily;
2389 errorID = diag::err_arc_gained_method_convention;
2390 noteID = diag::note_arc_gained_method_convention;
2391 }
2392
2393 // Indexes into a %select clause in the diagnostic.
2394 enum FamilySelector {
2395 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2396 };
2397 FamilySelector familySelector = FamilySelector();
2398
2399 switch (family) {
2400 case OMF_None: llvm_unreachable("logic error, no method convention");
2401 case OMF_retain:
2402 case OMF_release:
2403 case OMF_autorelease:
2404 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002405 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002406 case OMF_retainCount:
2407 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002408 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002409 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002410 // Mismatches for these methods don't change ownership
2411 // conventions, so we don't care.
2412 return false;
2413
2414 case OMF_init: familySelector = F_init; break;
2415 case OMF_alloc: familySelector = F_alloc; break;
2416 case OMF_copy: familySelector = F_copy; break;
2417 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2418 case OMF_new: familySelector = F_new; break;
2419 }
2420
2421 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2422 ReasonSelector reasonSelector;
2423
2424 // The only reason these methods don't fall within their families is
2425 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002426 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002427 reasonSelector = R_UnrelatedReturn;
2428 } else {
2429 reasonSelector = R_NonObjectReturn;
2430 }
2431
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002432 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2433 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002434
2435 return true;
2436}
John McCall071df462010-10-28 02:34:38 +00002437
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002438void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002439 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002440 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002441 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002442 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2443 return;
2444
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002445 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002446 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002447 true);
Mike Stump11289f42009-09-09 15:08:12 +00002448
Chris Lattner67f35b02009-04-11 19:58:42 +00002449 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002450 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2451 EF = MethodDecl->param_end();
2452 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002453 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002454 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002455 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002456
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002457 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002458 Diag(ImpMethodDecl->getLocation(),
2459 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002460 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002461 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002462}
2463
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002464void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2465 ObjCMethodDecl *Overridden,
2466 bool IsProtocolMethodDecl) {
2467
2468 CheckMethodOverrideReturn(*this, Method, Overridden,
2469 IsProtocolMethodDecl, true,
2470 true);
2471
2472 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002473 IF = Overridden->param_begin(), EM = Method->param_end(),
2474 EF = Overridden->param_end();
2475 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002476 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2477 IsProtocolMethodDecl, true, true);
2478 }
2479
2480 if (Method->isVariadic() != Overridden->isVariadic()) {
2481 Diag(Method->getLocation(),
2482 diag::warn_conflicting_overriding_variadic);
2483 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2484 }
2485}
2486
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002487/// WarnExactTypedMethods - This routine issues a warning if method
2488/// implementation declaration matches exactly that of its declaration.
2489void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2490 ObjCMethodDecl *MethodDecl,
2491 bool IsProtocolMethodDecl) {
2492 // don't issue warning when protocol method is optional because primary
2493 // class is not required to implement it and it is safe for protocol
2494 // to implement it.
2495 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2496 return;
2497 // don't issue warning when primary class's method is
2498 // depecated/unavailable.
2499 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2500 MethodDecl->hasAttr<DeprecatedAttr>())
2501 return;
2502
2503 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2504 IsProtocolMethodDecl, false, false);
2505 if (match)
2506 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002507 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2508 EF = MethodDecl->param_end();
2509 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002510 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2511 *IM, *IF,
2512 IsProtocolMethodDecl, false, false);
2513 if (!match)
2514 break;
2515 }
2516 if (match)
2517 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002518 if (match)
2519 match = !(MethodDecl->isClassMethod() &&
2520 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002521
2522 if (match) {
2523 Diag(ImpMethodDecl->getLocation(),
2524 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002525 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2526 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002527 }
2528}
2529
Mike Stump87c57ac2009-05-16 07:39:55 +00002530/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2531/// improve the efficiency of selector lookups and type checking by associating
2532/// with each protocol / interface / category the flattened instance tables. If
2533/// we used an immutable set to keep the table then it wouldn't add significant
2534/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002535
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002536typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002537typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002538
2539static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2540 ProtocolNameSet &PNS) {
2541 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2542 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002543 for (const auto *PI : PDecl->protocols())
2544 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002545}
2546
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002547/// Recursively populates a set with all conformed protocols in a class
2548/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2549/// attribute.
2550static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2551 ProtocolNameSet &PNS) {
2552 if (!Super)
2553 return;
2554
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002555 for (const auto *I : Super->all_referenced_protocols())
2556 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002557
2558 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002559}
2560
Steve Naroffa36992242008-02-08 22:06:17 +00002561/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002562/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002563static void CheckProtocolMethodDefs(Sema &S,
2564 SourceLocation ImpLoc,
2565 ObjCProtocolDecl *PDecl,
2566 bool& IncompleteImpl,
2567 const Sema::SelectorSet &InsMap,
2568 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002569 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002570 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002571 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2572 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2573 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002574 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2575
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002576 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002577 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002578
2579 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2580 // then we should check if any class in the super class hierarchy also
2581 // conforms to this protocol, either directly or via protocol inheritance.
2582 // If so, we can skip checking this protocol completely because we
2583 // know that a parent class already satisfies this protocol.
2584 //
2585 // Note: we could generalize this logic for all protocols, and merely
2586 // add the limit on looking at the super class chain for just
2587 // specially marked protocols. This may be a good optimization. This
2588 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2589 // protocols for now for controlled evaluation.
2590 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002591 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002592 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2593 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2594 }
2595 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2596 ProtocolsExplictImpl->end())
2597 return;
2598
2599 // If no super class conforms to the protocol, we should not search
2600 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002601 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002602 }
2603
Ted Kremenek285ee852013-12-13 06:26:10 +00002604 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002605 // check to see if class implements forwardInvocation method and objects
2606 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002607 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002608 // Under such conditions, which means that every method possible is
2609 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002610 // found" warnings.
2611 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002612 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2613 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002614 if (InsMap.count(fISelector))
2615 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2616 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002617 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002618 }
Mike Stump11289f42009-09-09 15:08:12 +00002619
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002620 // If this is a forward protocol declaration, get its definition.
2621 if (!PDecl->isThisDeclarationADefinition() &&
2622 PDecl->getDefinition())
2623 PDecl = PDecl->getDefinition();
2624
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002625 // If a method lookup fails locally we still need to look and see if
2626 // the method was implemented by a base class or an inherited
2627 // protocol. This lookup is slow, but occurs rarely in correct code
2628 // and otherwise would terminate in a warning.
2629
Chris Lattnerda463fe2007-12-12 07:09:47 +00002630 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002631 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002632 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002633 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002634 !method->isPropertyAccessor() &&
2635 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002636 (!Super || !Super->lookupMethod(method->getSelector(),
2637 true /* instance */,
2638 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002639 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002640 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002641 // If a method is not implemented in the category implementation but
2642 // has been declared in its primary class, superclass,
2643 // or in one of their protocols, no need to issue the warning.
2644 // This is because method will be implemented in the primary class
2645 // or one of its super class implementation.
2646
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002647 // Ugly, but necessary. Method declared in protcol might have
2648 // have been synthesized due to a property declared in the class which
2649 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002650 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002651 IDecl->lookupMethod(method->getSelector(),
2652 true /* instance */,
2653 true /* shallowCategoryLookup */,
2654 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002655 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002656 continue;
2657 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002658 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002659 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002660 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002661 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002662 }
2663 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002664 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002665 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002666 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2667 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002668 (!Super || !Super->lookupMethod(method->getSelector(),
2669 false /* class method */,
2670 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002671 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002672 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002673 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002674 if (C && IDecl->lookupMethod(method->getSelector(),
2675 false /* class */,
2676 true /* shallowCategoryLookup */,
2677 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002678 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002679
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002680 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002681 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002682 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002683 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002684 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002685 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002686 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002687 for (auto *PI : PDecl->protocols())
2688 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002689 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002690}
2691
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002692/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002693/// or protocol against those declared in their implementations.
2694///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002695void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2696 const SelectorSet &ClsMap,
2697 SelectorSet &InsMapSeen,
2698 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002699 ObjCImplDecl* IMPDecl,
2700 ObjCContainerDecl* CDecl,
2701 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002702 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002703 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002704 // Check and see if instance methods in class interface have been
2705 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002706 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002707 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002708 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002709 if (!I->isPropertyAccessor() &&
2710 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002711 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002712 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002713 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002714 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002715 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002716 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002717 IMPDecl->getInstanceMethod(I->getSelector());
2718 assert(CDecl->getInstanceMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002719 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002720 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002721 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002722 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002723 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002724 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002725 else if (!I->isPropertyAccessor())
2726 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002727 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002728 }
2729 }
Mike Stump11289f42009-09-09 15:08:12 +00002730
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002731 // Check and see if class methods in class interface have been
2732 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002733 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002734 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002735 continue;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002736 if (!ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002737 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002738 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002739 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002740 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002741 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002742 IMPDecl->getClassMethod(I->getSelector());
2743 assert(CDecl->getClassMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002744 "Expected to find the method through lookup as well");
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002745 if (!WarnCategoryMethodImpl)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002746 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002747 isa<ObjCProtocolDecl>(CDecl));
2748 else
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002749 WarnExactTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002750 isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002751 }
2752 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002753
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002754 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2755 // Also, check for methods declared in protocols inherited by
2756 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002757 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002758 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002759 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002760 WarnCategoryMethodImpl);
2761 }
2762
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002763 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002764 // when checking that methods in implementation match their declaration,
2765 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2766 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002767 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002768 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002769 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002770 IMPDecl, Cat, IncompleteImpl,
2771 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002772 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002773 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002774 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002775 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002776 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002777 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002778 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002779 }
2780
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002781 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002782 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002783 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002784 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002785 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002786
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002787 // FIXME. For now, we are not checking for extact match of methods
2788 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002789 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002790 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002791 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002792 I->getSuperClass(), IncompleteImpl, false);
2793 }
2794}
2795
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002796/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2797/// category matches with those implemented in its primary class and
2798/// warns each time an exact match is found.
2799void Sema::CheckCategoryVsClassMethodMatches(
2800 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002801 // Get category's primary class.
2802 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2803 if (!CatDecl)
2804 return;
2805 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2806 if (!IDecl)
2807 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002808 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2809 SelectorSet InsMap, ClsMap;
2810
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002811 for (const auto *I : CatIMPDecl->instance_methods()) {
2812 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002813 // When checking for methods implemented in the category, skip over
2814 // those declared in category class's super class. This is because
2815 // the super class must implement the method.
2816 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2817 continue;
2818 InsMap.insert(Sel);
2819 }
2820
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002821 for (const auto *I : CatIMPDecl->class_methods()) {
2822 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002823 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2824 continue;
2825 ClsMap.insert(Sel);
2826 }
2827 if (InsMap.empty() && ClsMap.empty())
2828 return;
2829
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002830 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002831 bool IncompleteImpl = false;
2832 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2833 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002834 IncompleteImpl, false,
2835 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002836}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002837
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002838void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002839 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002840 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002841 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002842 // Check and see if instance methods in class interface have been
2843 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002844 for (const auto *I : IMPDecl->instance_methods())
2845 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002846
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002847 // Add the selectors for getters/setters of @dynamic properties.
2848 for (const auto *PImpl : IMPDecl->property_impls()) {
2849 // We only care about @dynamic implementations.
2850 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2851 continue;
2852
2853 const auto *P = PImpl->getPropertyDecl();
2854 if (!P) continue;
2855
2856 InsMap.insert(P->getGetterName());
2857 if (!P->getSetterName().isNull())
2858 InsMap.insert(P->getSetterName());
2859 }
2860
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002861 // Check and see if properties declared in the interface have either 1)
2862 // an implementation or 2) there is a @synthesize/@dynamic implementation
2863 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002864 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2865 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2866 LangOpts.ObjCRuntime.isNonFragile() &&
2867 !IDecl->isObjCRequiresPropertyDefs();
2868 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2869 }
2870
Douglas Gregor849ebc22015-06-19 18:14:46 +00002871 // Diagnose null-resettable synthesized setters.
2872 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2873
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002874 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002875 for (const auto *I : IMPDecl->class_methods())
2876 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002877
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002878 // Check for type conflict of methods declared in a class/protocol and
2879 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002880 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002881 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2882 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002883 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002884
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002885 // check all methods implemented in category against those declared
2886 // in its primary class.
2887 if (ObjCCategoryImplDecl *CatDecl =
2888 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2889 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002890
Chris Lattnerda463fe2007-12-12 07:09:47 +00002891 // Check the protocol list for unimplemented methods in the @implementation
2892 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002893 // Check and see if class methods in class interface have been
2894 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002895
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002896 LazyProtocolNameSet ExplicitImplProtocols;
2897
Chris Lattner9ef10f42009-03-01 00:56:52 +00002898 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002899 for (auto *PI : I->all_referenced_protocols())
2900 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2901 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002902 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002903 // For extended class, unimplemented methods in its protocols will
2904 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002905 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002906 for (auto *P : C->protocols())
2907 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002908 IncompleteImpl, InsMap, ClsMap, CDecl,
2909 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002910 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00002911 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002912 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002913 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002914 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002915}
2916
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002917Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00002918Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00002919 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00002920 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002921 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00002922 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002923 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002924 for (unsigned i = 0; i != NumElts; ++i) {
2925 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002926 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002927 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Douglas Gregorb8eaf292010-04-15 23:40:53 +00002928 LookupOrdinaryName, ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002929 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00002930 // GCC apparently allows the following idiom:
2931 //
2932 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2933 // @class XCElementToggler;
2934 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002935 // Here we have chosen to ignore the forward class declaration
2936 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00002937 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00002938 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002939 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00002940 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00002941 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00002942 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002943 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00002944 // as this will force the intended behavior which is to lookup the
2945 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002946 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00002947 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2948 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002949 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2950 continue;
2951 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00002952 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002953 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00002954
2955 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002956 ObjCInterfaceDecl *PrevIDecl
2957 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00002958
2959 IdentifierInfo *ClassName = IdentList[i];
2960 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2961 // A previous decl with a different name is because of
2962 // @compatibility_alias, for example:
2963 // \code
2964 // @class NewImage;
2965 // @compatibility_alias OldImage NewImage;
2966 // \endcode
2967 // A lookup for 'OldImage' will return the 'NewImage' decl.
2968 //
2969 // In such a case use the real declaration name, instead of the alias one,
2970 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2971 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2972 // has been aliased.
2973 ClassName = PrevIDecl->getIdentifier();
2974 }
2975
Douglas Gregor85f3f952015-07-07 03:57:15 +00002976 // If this forward declaration has type parameters, compare them with the
2977 // type parameters of the previous declaration.
2978 ObjCTypeParamList *TypeParams = TypeParamLists[i];
2979 if (PrevIDecl && TypeParams) {
2980 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
2981 // Check for consistency with the previous declaration.
2982 if (checkTypeParamListConsistency(
2983 *this, PrevTypeParams, TypeParams,
2984 TypeParamListContext::ForwardDeclaration)) {
2985 TypeParams = nullptr;
2986 }
2987 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
2988 // The @interface does not have type parameters. Complain.
2989 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
2990 << ClassName
2991 << TypeParams->getSourceRange();
2992 Diag(Def->getLocation(), diag::note_defined_here)
2993 << ClassName;
2994
2995 TypeParams = nullptr;
2996 }
2997 }
2998
Douglas Gregordc9166c2011-12-15 20:29:51 +00002999 ObjCInterfaceDecl *IDecl
3000 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003001 ClassName, TypeParams, PrevIDecl,
3002 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003003 IDecl->setAtEndRange(IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003004
Douglas Gregordc9166c2011-12-15 20:29:51 +00003005 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003006 CheckObjCDeclScope(IDecl);
3007 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003008 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003009
3010 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003011}
3012
John McCall54507ab2011-06-16 01:15:19 +00003013static bool tryMatchRecordTypes(ASTContext &Context,
3014 Sema::MethodMatchStrategy strategy,
3015 const Type *left, const Type *right);
3016
John McCall31168b02011-06-15 23:02:42 +00003017static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3018 QualType leftQT, QualType rightQT) {
3019 const Type *left =
3020 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3021 const Type *right =
3022 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3023
3024 if (left == right) return true;
3025
3026 // If we're doing a strict match, the types have to match exactly.
3027 if (strategy == Sema::MMS_strict) return false;
3028
3029 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3030
3031 // Otherwise, use this absurdly complicated algorithm to try to
3032 // validate the basic, low-level compatibility of the two types.
3033
3034 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003035 TypeInfo LeftTI = Context.getTypeInfo(left);
3036 TypeInfo RightTI = Context.getTypeInfo(right);
3037 if (LeftTI.Width != RightTI.Width)
3038 return false;
3039
3040 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003041 return false;
3042
3043 // Consider all the kinds of non-dependent canonical types:
3044 // - functions and arrays aren't possible as return and parameter types
3045
3046 // - vector types of equal size can be arbitrarily mixed
3047 if (isa<VectorType>(left)) return isa<VectorType>(right);
3048 if (isa<VectorType>(right)) return false;
3049
3050 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003051 // - structs, unions, and Objective-C objects must match more-or-less
3052 // exactly
John McCall31168b02011-06-15 23:02:42 +00003053 // - everything else should be a scalar
3054 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003055 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003056
John McCall9320b872011-09-09 05:25:32 +00003057 // Make scalars agree in kind, except count bools as chars, and group
3058 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003059 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3060 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3061 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3062 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003063 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3064 leftSK = Type::STK_ObjCObjectPointer;
3065 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3066 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003067
3068 // Note that data member pointers and function member pointers don't
3069 // intermix because of the size differences.
3070
3071 return (leftSK == rightSK);
3072}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003073
John McCall54507ab2011-06-16 01:15:19 +00003074static bool tryMatchRecordTypes(ASTContext &Context,
3075 Sema::MethodMatchStrategy strategy,
3076 const Type *lt, const Type *rt) {
3077 assert(lt && rt && lt != rt);
3078
3079 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3080 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3081 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3082
3083 // Require union-hood to match.
3084 if (left->isUnion() != right->isUnion()) return false;
3085
3086 // Require an exact match if either is non-POD.
3087 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3088 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3089 return false;
3090
3091 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003092 TypeInfo LeftTI = Context.getTypeInfo(lt);
3093 TypeInfo RightTI = Context.getTypeInfo(rt);
3094 if (LeftTI.Width != RightTI.Width)
3095 return false;
3096
3097 if (LeftTI.Align != RightTI.Align)
3098 return false;
John McCall54507ab2011-06-16 01:15:19 +00003099
3100 // Require fields to match.
3101 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3102 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3103 for (; li != le && ri != re; ++li, ++ri) {
3104 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3105 return false;
3106 }
3107 return (li == le && ri == re);
3108}
3109
Chris Lattnerda463fe2007-12-12 07:09:47 +00003110/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3111/// returns true, or false, accordingly.
3112/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003113bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3114 const ObjCMethodDecl *right,
3115 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003116 if (!matchTypes(Context, strategy, left->getReturnType(),
3117 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003118 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003119
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003120 // If either is hidden, it is not considered to match.
3121 if (left->isHidden() || right->isHidden())
3122 return false;
3123
David Blaikiebbafb8a2012-03-11 07:00:24 +00003124 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003125 (left->hasAttr<NSReturnsRetainedAttr>()
3126 != right->hasAttr<NSReturnsRetainedAttr>() ||
3127 left->hasAttr<NSConsumesSelfAttr>()
3128 != right->hasAttr<NSConsumesSelfAttr>()))
3129 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003130
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003131 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003132 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3133 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003134
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003135 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003136 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003137 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003138
3139 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3140 return false;
3141
David Blaikiebbafb8a2012-03-11 07:00:24 +00003142 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003143 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3144 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003145 }
3146 return true;
3147}
3148
Nico Weber2e0c8f72014-12-27 03:58:08 +00003149void Sema::addMethodToGlobalList(ObjCMethodList *List,
3150 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003151 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3152 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003153 if (ObjCCategoryDecl *CD =
3154 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003155 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003156 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003157
Douglas Gregorc454afe2012-01-25 00:19:56 +00003158 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003159 if (List->getMethod() == nullptr) {
3160 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003161 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003162 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003163 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003164
Douglas Gregorc454afe2012-01-25 00:19:56 +00003165 // We've seen a method with this name, see if we have already seen this type
3166 // signature.
3167 ObjCMethodList *Previous = List;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003168 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003169 // If we are building a module, keep all of the methods.
3170 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
3171 continue;
3172
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003173 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) {
3174 // Even if two method types do not match, we would like to say
3175 // there is more than one declaration so unavailability/deprecated
3176 // warning is not too noisy.
3177 if (!Method->isDefined())
3178 List->setHasMoreThanOneDecl(true);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003179 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003180 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003181
3182 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003183
3184 // Propagate the 'defined' bit.
3185 if (Method->isDefined())
3186 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003187 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003188 // Objective-C doesn't allow an @interface for a class after its
3189 // @implementation. So if Method is not defined and there already is
3190 // an entry for this type signature, Method has to be for a different
3191 // class than PrevObjCMethod.
3192 List->setHasMoreThanOneDecl(true);
3193 }
3194
Douglas Gregorc454afe2012-01-25 00:19:56 +00003195 // If a method is deprecated, push it in the global pool.
3196 // This is used for better diagnostics.
3197 if (Method->isDeprecated()) {
3198 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003199 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003200 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003201 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003202 // unless previous one is deprecated.
3203 if (Method->isUnavailable()) {
3204 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003205 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003206 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003207
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003208 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003209 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003210
Douglas Gregorc454afe2012-01-25 00:19:56 +00003211 // We have a new signature for an existing method - add it.
3212 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003213 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Nico Weber2e0c8f72014-12-27 03:58:08 +00003214 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003215}
3216
Sebastian Redl75d8a322010-08-02 23:18:59 +00003217/// \brief Read the contents of the method pool for a given selector from
3218/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003219void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003220 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003221 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003222}
3223
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003224void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003225 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003226 // Ignore methods of invalid containers.
3227 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003228 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003229
Douglas Gregor70f449b2012-01-25 00:59:09 +00003230 if (ExternalSource)
3231 ReadMethodPool(Method->getSelector());
3232
Sebastian Redl75d8a322010-08-02 23:18:59 +00003233 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003234 if (Pos == MethodPool.end())
3235 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3236 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003237
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003238 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003239
Sebastian Redl75d8a322010-08-02 23:18:59 +00003240 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003241 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003242}
3243
John McCall31168b02011-06-15 23:02:42 +00003244/// Determines if this is an "acceptable" loose mismatch in the global
3245/// method pool. This exists mostly as a hack to get around certain
3246/// global mismatches which we can't afford to make warnings / errors.
3247/// Really, what we want is a way to take a method out of the global
3248/// method pool.
3249static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3250 ObjCMethodDecl *other) {
3251 if (!chosen->isInstanceMethod())
3252 return false;
3253
3254 Selector sel = chosen->getSelector();
3255 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3256 return false;
3257
3258 // Don't complain about mismatches for -length if the method we
3259 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003260 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003261}
3262
Nico Weber2e0c8f72014-12-27 03:58:08 +00003263bool Sema::CollectMultipleMethodsInGlobalPool(
3264 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003265 if (ExternalSource)
3266 ReadMethodPool(Sel);
3267
3268 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3269 if (Pos == MethodPool.end())
3270 return false;
3271 // Gather the non-hidden methods.
3272 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3273 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003274 if (M->getMethod() && !M->getMethod()->isHidden())
3275 Methods.push_back(M->getMethod());
3276 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003277}
3278
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003279bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3280 SourceRange R,
3281 bool receiverIdOrClass) {
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003282 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003283 // Test for no method in the pool which should not trigger any warning by
3284 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003285 if (Pos == MethodPool.end())
3286 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003287 ObjCMethodList &MethList =
3288 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3289
3290 // Diagnose finding more than one method in global pool
3291 SmallVector<ObjCMethodDecl *, 4> Methods;
3292 Methods.push_back(BestMethod);
Jonathan Roelofs74411362015-04-28 18:04:44 +00003293 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext())
3294 if (ObjCMethodDecl *M = ML->getMethod())
3295 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>())
3296 Methods.push_back(M);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003297 if (Methods.size() > 1)
3298 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass);
3299
Nico Weber2e0c8f72014-12-27 03:58:08 +00003300 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003301}
3302
Sebastian Redl75d8a322010-08-02 23:18:59 +00003303ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003304 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003305 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003306 if (ExternalSource)
3307 ReadMethodPool(Sel);
3308
Sebastian Redl75d8a322010-08-02 23:18:59 +00003309 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003310 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003311 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003312
Douglas Gregor77f49a42013-01-16 18:47:38 +00003313 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003314 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003315 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003316 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003317 if (M->getMethod() && !M->getMethod()->isHidden())
3318 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003319 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003320 return nullptr;
3321}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003322
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003323void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3324 Selector Sel, SourceRange R,
3325 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003326 // We found multiple methods, so we may have to complain.
3327 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003328
Douglas Gregor77f49a42013-01-16 18:47:38 +00003329 // We support a warning which complains about *any* difference in
3330 // method signature.
3331 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003332 receiverIdOrClass &&
3333 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003334 if (strictSelectorMatch) {
3335 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3336 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3337 issueDiagnostic = true;
3338 break;
3339 }
3340 }
3341 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003342
Douglas Gregor77f49a42013-01-16 18:47:38 +00003343 // If we didn't see any strict differences, we won't see any loose
3344 // differences. In ARC, however, we also need to check for loose
3345 // mismatches, because most of them are errors.
3346 if (!strictSelectorMatch ||
3347 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3348 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3349 // This checks if the methods differ in type mismatch.
3350 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3351 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3352 issueDiagnostic = true;
3353 if (getLangOpts().ObjCAutoRefCount)
3354 issueError = true;
3355 break;
3356 }
3357 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003358
Douglas Gregor77f49a42013-01-16 18:47:38 +00003359 if (issueDiagnostic) {
3360 if (issueError)
3361 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3362 else if (strictSelectorMatch)
3363 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3364 else
3365 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003366
Douglas Gregor77f49a42013-01-16 18:47:38 +00003367 Diag(Methods[0]->getLocStart(),
3368 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003369 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003370 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3371 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003372 << Methods[I]->getSourceRange();
3373 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003374 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003375}
3376
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003377ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003378 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3379 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003380 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003381
3382 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003383 for (const ObjCMethodList *Method = &Methods.first; Method;
3384 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003385 if (Method->getMethod() &&
3386 (Method->getMethod()->isDefined() ||
3387 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003388 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003389
3390 for (const ObjCMethodList *Method = &Methods.second; Method;
3391 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003392 if (Method->getMethod() &&
3393 (Method->getMethod()->isDefined() ||
3394 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003395 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003396 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003397}
3398
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003399static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003400HelperSelectorsForTypoCorrection(
3401 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3402 StringRef Typo, const ObjCMethodDecl * Method) {
3403 const unsigned MaxEditDistance = 1;
3404 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003405 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003406
3407 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3408 if (MinPossibleEditDistance > 0 &&
3409 Typo.size() / MinPossibleEditDistance < 1)
3410 return;
3411 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3412 if (EditDistance > MaxEditDistance)
3413 return;
3414 if (EditDistance == BestEditDistance)
3415 BestMethod.push_back(Method);
3416 else if (EditDistance < BestEditDistance) {
3417 BestMethod.clear();
3418 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003419 }
3420}
3421
Fariborz Jahanian75481672013-06-17 17:10:54 +00003422static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3423 QualType ObjectType) {
3424 if (ObjectType.isNull())
3425 return true;
3426 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3427 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003428 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3429 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003430}
3431
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003432const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003433Sema::SelectorsForTypoCorrection(Selector Sel,
3434 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003435 unsigned NumArgs = Sel.getNumArgs();
3436 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003437 bool ObjectIsId = true, ObjectIsClass = true;
3438 if (ObjectType.isNull())
3439 ObjectIsId = ObjectIsClass = false;
3440 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003441 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003442 else if (const ObjCObjectPointerType *ObjCPtr =
3443 ObjectType->getAsObjCInterfacePointerType()) {
3444 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3445 ObjectIsId = ObjectIsClass = false;
3446 }
3447 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3448 ObjectIsClass = false;
3449 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3450 ObjectIsId = false;
3451 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003452 return nullptr;
3453
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003454 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3455 e = MethodPool.end(); b != e; b++) {
3456 // instance methods
3457 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003458 if (M->getMethod() &&
3459 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3460 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003461 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003462 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003463 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003464 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3465 ObjectType))
3466 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003467 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003468 // class methods
3469 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003470 if (M->getMethod() &&
3471 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3472 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003473 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003474 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003475 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003476 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3477 ObjectType))
3478 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003479 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003480 }
3481
3482 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3483 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3484 HelperSelectorsForTypoCorrection(SelectedMethods,
3485 Sel.getAsString(), Methods[i]);
3486 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003487 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003488}
3489
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003490/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003491/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003492/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003493/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003494/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003495void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3496 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003497 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003498 if (Ivar->isInvalidDecl())
3499 continue;
3500 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3501 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3502 if (prevIvar) {
3503 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3504 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3505 Ivar->setInvalidDecl();
3506 }
3507 }
3508 }
3509}
3510
John McCallb61e14e2015-10-27 04:54:50 +00003511/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3512static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3513 if (S.getLangOpts().ObjCWeak) return;
3514
3515 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3516 ivar; ivar = ivar->getNextIvar()) {
3517 if (ivar->isInvalidDecl()) continue;
3518 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3519 if (S.getLangOpts().ObjCWeakRuntime) {
3520 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3521 } else {
3522 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3523 }
3524 }
3525 }
3526}
3527
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003528Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3529 switch (CurContext->getDeclKind()) {
3530 case Decl::ObjCInterface:
3531 return Sema::OCK_Interface;
3532 case Decl::ObjCProtocol:
3533 return Sema::OCK_Protocol;
3534 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003535 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003536 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003537 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003538 case Decl::ObjCImplementation:
3539 return Sema::OCK_Implementation;
3540 case Decl::ObjCCategoryImpl:
3541 return Sema::OCK_CategoryImplementation;
3542
3543 default:
3544 return Sema::OCK_None;
3545 }
3546}
3547
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003548// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003549Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003550 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003551 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003552 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003553
3554 assert(AtEnd.isValid() && "Invalid location for '@end'");
3555
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003556 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3557 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian9290ede2009-11-16 18:57:01 +00003558
Mike Stump11289f42009-09-09 15:08:12 +00003559 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003560 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3561 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003562 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003563
Steve Naroff35c62ae2009-01-08 17:28:14 +00003564 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3565 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3566 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3567
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003568 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003569 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003570 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003571
3572 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003573 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003574 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003575 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003576 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003577 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003578 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003579 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003580 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003581 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003582 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003583 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003584 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003585 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003586 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003587 if (!Context.getSourceManager().isInSystemHeader(
3588 Method->getLocation()))
3589 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3590 << Method->getDeclName();
3591 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3592 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003593 InsMap[Method->getSelector()] = Method;
3594 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003595 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003596 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003597 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003598 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003599 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003600 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003601 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003602 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003603 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003604 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003605 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003606 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003607 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003608 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003609 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003610 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003611 if (!Context.getSourceManager().isInSystemHeader(
3612 Method->getLocation()))
3613 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3614 << Method->getDeclName();
3615 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3616 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003617 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003618 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003619 }
3620 }
3621 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003622 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3623 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003624 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003625 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003626 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003627 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003628
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003629 if (C->IsClassExtension()) {
3630 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3631 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003632 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003633 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003634 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003635 if (CDecl->getIdentifier())
3636 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3637 // user-defined setter/getter. It also synthesizes setter/getter methods
3638 // and adds them to the DeclContext and global method pools.
Aaron Ballmand174edf2014-03-13 19:11:50 +00003639 for (auto *I : CDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00003640 ProcessPropertyDecl(I, CDecl);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003641 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003642 }
3643 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003644 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003645 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003646 // Any property declared in a class extension might have user
3647 // declared setter or getter in current class extension or one
3648 // of the other class extensions. Mark them as synthesized as
3649 // property will be synthesized when property with same name is
3650 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003651 for (const auto *Ext : IDecl->visible_extensions()) {
Aaron Ballmand174edf2014-03-13 19:11:50 +00003652 for (const auto *Property : Ext->properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003653 // Skip over properties declared @dynamic
3654 if (const ObjCPropertyImplDecl *PIDecl
3655 = IC->FindPropertyImplDecl(Property->getIdentifier()))
3656 if (PIDecl->getPropertyImplementation()
3657 == ObjCPropertyImplDecl::Dynamic)
3658 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003659
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003660 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003661 if (ObjCMethodDecl *GetterMethod
3662 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003663 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003664 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003665 if (ObjCMethodDecl *SetterMethod
3666 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003667 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003668 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003669 }
3670 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003671 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003672 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003673 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003674 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003675 if (IDecl->hasDesignatedInitializers())
3676 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00003677 DiagnoseWeakIvars(*this, IC);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003678
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003679 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00003680 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003681 // This class has no superclass, so check that it has been marked with
3682 // __attribute((objc_root_class)).
3683 if (!HasRootClassAttr) {
3684 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00003685 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003686 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3687 << IDecl->getIdentifier();
3688 // See if NSObject is in the current scope, and if it is, suggest
3689 // adding " : NSObject " to the class declaration.
3690 NamedDecl *IF = LookupSingleName(TUScope,
3691 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3692 DeclLoc, LookupOrdinaryName);
3693 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3694 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3695 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3696 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3697 } else {
3698 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3699 }
3700 }
3701 } else if (HasRootClassAttr) {
3702 // Complain that only root classes may have this attribute.
3703 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3704 }
3705
John McCall5fb5df92012-06-20 06:18:46 +00003706 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003707 while (IDecl->getSuperClass()) {
3708 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3709 IDecl = IDecl->getSuperClass();
3710 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003711 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003712 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003713 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00003714 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00003715 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003716 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003717
Chris Lattnerda463fe2007-12-12 07:09:47 +00003718 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00003719 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00003720 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003721 if (ObjCCategoryDecl *Cat
3722 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3723 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003724 }
3725 }
3726 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003727 if (isInterfaceDeclKind) {
3728 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003729 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003730 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003731 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3732 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003733 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00003734 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00003735 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003736 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003737 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00003738 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003739
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003740 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003741 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003742 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3743 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003744 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3745 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003746
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00003747 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003748 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003749}
3750
Chris Lattnerda463fe2007-12-12 07:09:47 +00003751/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3752/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00003753static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003754CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00003755 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003756}
3757
Douglas Gregor33823722011-06-11 01:09:30 +00003758/// \brief Check whether the declared result type of the given Objective-C
3759/// method declaration is compatible with the method's class.
3760///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003761static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00003762CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3763 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00003764 QualType ResultType = Method->getReturnType();
3765
Douglas Gregor33823722011-06-11 01:09:30 +00003766 // If an Objective-C method inherits its related result type, then its
3767 // declared result type must be compatible with its own class type. The
3768 // declared result type is compatible if:
3769 if (const ObjCObjectPointerType *ResultObjectType
3770 = ResultType->getAs<ObjCObjectPointerType>()) {
3771 // - it is id or qualified id, or
3772 if (ResultObjectType->isObjCIdType() ||
3773 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003774 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003775
3776 if (CurrentClass) {
3777 if (ObjCInterfaceDecl *ResultClass
3778 = ResultObjectType->getInterfaceDecl()) {
3779 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00003780 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003781 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003782
3783 // - it is a superclass of the method's class type
3784 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003785 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003786 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00003787 } else {
3788 // Any Objective-C pointer type might be acceptable for a protocol
3789 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003790 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00003791 }
3792 }
3793
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003794 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003795}
3796
John McCalld2930c22011-07-22 02:45:48 +00003797namespace {
3798/// A helper class for searching for methods which a particular method
3799/// overrides.
3800class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003801public:
John McCalld2930c22011-07-22 02:45:48 +00003802 Sema &S;
3803 ObjCMethodDecl *Method;
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003804 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00003805 bool Recursive;
3806
3807public:
3808 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
3809 Selector selector = method->getSelector();
3810
3811 // Bypass this search if we've never seen an instance/class method
3812 // with this selector before.
3813 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
3814 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00003815 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00003816 S.ReadMethodPool(selector);
3817
3818 it = S.MethodPool.find(selector);
3819 if (it == S.MethodPool.end())
3820 return;
John McCalld2930c22011-07-22 02:45:48 +00003821 }
3822 ObjCMethodList &list =
3823 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003824 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00003825
3826 ObjCContainerDecl *container
3827 = cast<ObjCContainerDecl>(method->getDeclContext());
3828
3829 // Prevent the search from reaching this container again. This is
3830 // important with categories, which override methods from the
3831 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003832 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
3833 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003834 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
3835 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003836 } else {
3837 searchFromContainer(container);
3838 }
Douglas Gregor33823722011-06-11 01:09:30 +00003839 }
John McCalld2930c22011-07-22 02:45:48 +00003840
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003841 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00003842 iterator begin() const { return Overridden.begin(); }
3843 iterator end() const { return Overridden.end(); }
3844
3845private:
3846 void searchFromContainer(ObjCContainerDecl *container) {
3847 if (container->isInvalidDecl()) return;
3848
3849 switch (container->getDeclKind()) {
3850#define OBJCCONTAINER(type, base) \
3851 case Decl::type: \
3852 searchFrom(cast<type##Decl>(container)); \
3853 break;
3854#define ABSTRACT_DECL(expansion)
3855#define DECL(type, base) \
3856 case Decl::type:
3857#include "clang/AST/DeclNodes.inc"
3858 llvm_unreachable("not an ObjC container!");
3859 }
3860 }
3861
3862 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00003863 if (!protocol->hasDefinition())
3864 return;
3865
John McCalld2930c22011-07-22 02:45:48 +00003866 // A method in a protocol declaration overrides declarations from
3867 // referenced ("parent") protocols.
3868 search(protocol->getReferencedProtocols());
3869 }
3870
3871 void searchFrom(ObjCCategoryDecl *category) {
3872 // A method in a category declaration overrides declarations from
3873 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003874 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00003875 search(category->getReferencedProtocols());
3876 }
3877
3878 void searchFrom(ObjCCategoryImplDecl *impl) {
3879 // A method in a category definition that has a category
3880 // declaration overrides declarations from the category
3881 // declaration.
3882 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
3883 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003884 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
3885 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003886
3887 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003888 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
3889 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003890 }
3891 }
3892
3893 void searchFrom(ObjCInterfaceDecl *iface) {
3894 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00003895 if (!iface->hasDefinition())
3896 return;
3897
John McCalld2930c22011-07-22 02:45:48 +00003898 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00003899 for (auto *Cat : iface->known_categories())
3900 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00003901
3902 // - the super class, and
3903 if (ObjCInterfaceDecl *super = iface->getSuperClass())
3904 search(super);
3905
3906 // - any referenced protocols.
3907 search(iface->getReferencedProtocols());
3908 }
3909
3910 void searchFrom(ObjCImplementationDecl *impl) {
3911 // A method in a class implementation overrides declarations from
3912 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003913 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
3914 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003915 }
3916
John McCalld2930c22011-07-22 02:45:48 +00003917 void search(const ObjCProtocolList &protocols) {
3918 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
3919 i != e; ++i)
3920 search(*i);
3921 }
3922
3923 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00003924 // Check for a method in this container which matches this selector.
3925 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00003926 Method->isInstanceMethod(),
3927 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00003928
3929 // If we find one, record it and bail out.
3930 if (meth) {
3931 Overridden.insert(meth);
3932 return;
3933 }
3934
3935 // Otherwise, search for methods that a hypothetical method here
3936 // would have overridden.
3937
3938 // Note that we're now in a recursive case.
3939 Recursive = true;
3940
3941 searchFromContainer(container);
3942 }
3943};
Hans Wennborgdcfba332015-10-06 23:40:43 +00003944} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00003945
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003946void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
3947 ObjCInterfaceDecl *CurrentClass,
3948 ResultTypeCompatibilityKind RTC) {
3949 // Search for overridden methods and merge information down from them.
3950 OverrideSearch overrides(*this, ObjCMethod);
3951 // Keep track if the method overrides any method in the class's base classes,
3952 // its protocols, or its categories' protocols; we will keep that info
3953 // in the ObjCMethodDecl.
3954 // For this info, a method in an implementation is not considered as
3955 // overriding the same method in the interface or its categories.
3956 bool hasOverriddenMethodsInBaseOrProtocol = false;
3957 for (OverrideSearch::iterator
3958 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
3959 ObjCMethodDecl *overridden = *i;
3960
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003961 if (!hasOverriddenMethodsInBaseOrProtocol) {
3962 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3963 CurrentClass != overridden->getClassInterface() ||
3964 overridden->isOverriding()) {
3965 hasOverriddenMethodsInBaseOrProtocol = true;
3966
3967 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3968 // OverrideSearch will return as "overridden" the same method in the
3969 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3970 // check whether a category of a base class introduced a method with the
3971 // same selector, after the interface method declaration.
3972 // To avoid unnecessary lookups in the majority of cases, we use the
3973 // extra info bits in GlobalMethodPool to check whether there were any
3974 // category methods with this selector.
3975 GlobalMethodPool::iterator It =
3976 MethodPool.find(ObjCMethod->getSelector());
3977 if (It != MethodPool.end()) {
3978 ObjCMethodList &List =
3979 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3980 unsigned CategCount = List.getBits();
3981 if (CategCount > 0) {
3982 // If the method is in a category we'll do lookup if there were at
3983 // least 2 category methods recorded, otherwise only one will do.
3984 if (CategCount > 1 ||
3985 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3986 OverrideSearch overrides(*this, overridden);
3987 for (OverrideSearch::iterator
3988 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3989 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003990 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3991 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003992 hasOverriddenMethodsInBaseOrProtocol = true;
3993 overridden->setOverriding(true);
3994 break;
3995 }
3996 }
3997 }
3998 }
3999 }
4000 }
4001 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004002
4003 // Propagate down the 'related result type' bit from overridden methods.
4004 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4005 ObjCMethod->SetRelatedResultType();
4006
4007 // Then merge the declarations.
4008 mergeObjCMethodDecls(ObjCMethod, overridden);
4009
4010 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4011 continue; // Conflicting properties are detected elsewhere.
4012
4013 // Check for overriding methods
4014 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4015 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4016 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4017 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4018
4019 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004020 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4021 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004022 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4023 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004024 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4025 PrevE = overridden->param_end();
4026 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004027 assert(PrevI != overridden->param_end() && "Param mismatch");
4028 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4029 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4030 // If type of argument of method in this class does not match its
4031 // respective argument type in the super class method, issue warning;
4032 if (!Context.typesAreCompatible(T1, T2)) {
4033 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4034 << T1 << T2;
4035 Diag(overridden->getLocation(), diag::note_previous_declaration);
4036 break;
4037 }
4038 }
4039 }
4040 }
4041
4042 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4043}
4044
Douglas Gregor813a0662015-06-19 18:14:38 +00004045/// Merge type nullability from for a redeclaration of the same entity,
4046/// producing the updated type of the redeclared entity.
4047static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4048 QualType type,
4049 bool usesCSKeyword,
4050 SourceLocation prevLoc,
4051 QualType prevType,
4052 bool prevUsesCSKeyword) {
4053 // Determine the nullability of both types.
4054 auto nullability = type->getNullability(S.Context);
4055 auto prevNullability = prevType->getNullability(S.Context);
4056
4057 // Easy case: both have nullability.
4058 if (nullability.hasValue() == prevNullability.hasValue()) {
4059 // Neither has nullability; continue.
4060 if (!nullability)
4061 return type;
4062
4063 // The nullabilities are equivalent; do nothing.
4064 if (*nullability == *prevNullability)
4065 return type;
4066
4067 // Complain about mismatched nullability.
4068 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004069 << DiagNullabilityKind(*nullability, usesCSKeyword)
4070 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004071 return type;
4072 }
4073
4074 // If it's the redeclaration that has nullability, don't change anything.
4075 if (nullability)
4076 return type;
4077
4078 // Otherwise, provide the result with the same nullability.
4079 return S.Context.getAttributedType(
4080 AttributedType::getNullabilityAttrKind(*prevNullability),
4081 type, type);
4082}
4083
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004084/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004085/// (or a category/extension) into the corresponding method in the
4086/// @implementation (for a class or category).
4087static void mergeInterfaceMethodToImpl(Sema &S,
4088 ObjCMethodDecl *method,
4089 ObjCMethodDecl *prevMethod) {
4090 // Merge the objc_requires_super attribute.
4091 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4092 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4093 // merge the attribute into implementation.
4094 method->addAttr(
4095 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4096 method->getLocation()));
4097 }
4098
4099 // Merge nullability of the result type.
4100 QualType newReturnType
4101 = mergeTypeNullabilityForRedecl(
4102 S, method->getReturnTypeSourceRange().getBegin(),
4103 method->getReturnType(),
4104 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4105 prevMethod->getReturnTypeSourceRange().getBegin(),
4106 prevMethod->getReturnType(),
4107 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4108 method->setReturnType(newReturnType);
4109
4110 // Handle each of the parameters.
4111 unsigned numParams = method->param_size();
4112 unsigned numPrevParams = prevMethod->param_size();
4113 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4114 ParmVarDecl *param = method->param_begin()[i];
4115 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4116
4117 // Merge nullability.
4118 QualType newParamType
4119 = mergeTypeNullabilityForRedecl(
4120 S, param->getLocation(), param->getType(),
4121 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4122 prevParam->getLocation(), prevParam->getType(),
4123 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4124 param->setType(newParamType);
4125 }
4126}
4127
John McCall48871652010-08-21 09:40:31 +00004128Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004129 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004130 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004131 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004132 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004133 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004134 Selector Sel,
4135 // optional arguments. The number of types/arguments is obtained
4136 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004137 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004138 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004139 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004140 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004141 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004142 if (!CurContext->isObjCContainer()) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004143 Diag(MethodLoc, diag::error_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004144 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004145 }
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004146 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4147 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004148 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004149
Douglas Gregorbab8a962011-09-08 01:46:34 +00004150 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004151 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004152 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004153 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004154
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004155 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004156 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004157
Douglas Gregor813a0662015-06-19 18:14:38 +00004158 QualType bareResultType = resultDeclType;
4159 (void)AttributedType::stripOuterNullability(bareResultType);
4160 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004161 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004162 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004163 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004164 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004165 }
Mike Stump11289f42009-09-09 15:08:12 +00004166
Alp Toker314cc812014-01-25 16:55:45 +00004167 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4168 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4169 MethodType == tok::minus, isVariadic,
4170 /*isPropertyAccessor=*/false,
4171 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4172 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4173 : ObjCMethodDecl::Required,
4174 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004175
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004176 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004177
Chris Lattner23b0faf2009-04-11 19:42:43 +00004178 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004179 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004180 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004181
David Blaikie7d170102013-05-15 07:37:26 +00004182 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004183 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004184 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004185 } else {
John McCall856bbea2009-10-23 21:48:59 +00004186 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004187 }
Mike Stump11289f42009-09-09 15:08:12 +00004188
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004189 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4190 LookupOrdinaryName, ForRedeclaration);
4191 LookupName(R, S);
4192 if (R.isSingleResult()) {
4193 NamedDecl *PrevDecl = R.getFoundDecl();
4194 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004195 Diag(ArgInfo[i].NameLoc,
4196 (MethodDefinition ? diag::warn_method_param_redefinition
4197 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004198 << ArgInfo[i].Name;
4199 Diag(PrevDecl->getLocation(),
4200 diag::note_previous_declaration);
4201 }
4202 }
4203
Abramo Bagnaradff19302011-03-08 08:55:46 +00004204 SourceLocation StartLoc = DI
4205 ? DI->getTypeLoc().getBeginLoc()
4206 : ArgInfo[i].NameLoc;
4207
John McCalld44f4d72011-04-23 02:46:06 +00004208 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4209 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004210 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004211
John McCall82490832011-05-02 00:30:12 +00004212 Param->setObjCMethodScopeInfo(i);
4213
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004214 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004215 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004216
Chris Lattner9713a1c2009-04-11 19:34:56 +00004217 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004218 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Mike Stump11289f42009-09-09 15:08:12 +00004219
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004220 if (Param->hasAttr<BlocksAttr>()) {
4221 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4222 Param->setInvalidDecl();
4223 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004224 S->AddDecl(Param);
4225 IdResolver.AddDecl(Param);
4226
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004227 Params.push_back(Param);
4228 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004229
Fariborz Jahanian60462092010-04-08 00:30:06 +00004230 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004231 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004232 QualType ArgType = Param->getType();
4233 if (ArgType.isNull())
4234 ArgType = Context.getObjCIdType();
4235 else
4236 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004237 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004238
Fariborz Jahanian60462092010-04-08 00:30:06 +00004239 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004240 Params.push_back(Param);
4241 }
4242
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004243 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004244 ObjCMethod->setObjCDeclQualifier(
4245 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004246
4247 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004248 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Mike Stump11289f42009-09-09 15:08:12 +00004249
Douglas Gregor87e92752010-12-21 17:34:17 +00004250 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004251 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004252 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004253 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004254 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4255 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004256 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004257 PrevMethod = ImpDecl->getClassMethod(Sel);
4258 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004259 }
Douglas Gregor33823722011-06-11 01:09:30 +00004260
Douglas Gregor813a0662015-06-19 18:14:38 +00004261 // Merge information from the @interface declaration into the
4262 // @implementation.
4263 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4264 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4265 ObjCMethod->isInstanceMethod())) {
4266 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4267
4268 // Warn about defining -dealloc in a category.
4269 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4270 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4271 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4272 << ObjCMethod->getDeclName();
4273 }
4274 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004275 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004276 } else {
4277 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004278 }
John McCalld2930c22011-07-22 02:45:48 +00004279
Chris Lattnerda463fe2007-12-12 07:09:47 +00004280 if (PrevMethod) {
4281 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004282 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004283 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004284 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004285 ObjCMethod->setInvalidDecl();
4286 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004287 }
John McCall28a6aea2009-11-04 02:18:39 +00004288
Douglas Gregor33823722011-06-11 01:09:30 +00004289 // If this Objective-C method does not have a related result type, but we
4290 // are allowed to infer related result types, try to do so based on the
4291 // method family.
4292 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4293 if (!CurrentClass) {
4294 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4295 CurrentClass = Cat->getClassInterface();
4296 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4297 CurrentClass = Impl->getClassInterface();
4298 else if (ObjCCategoryImplDecl *CatImpl
4299 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4300 CurrentClass = CatImpl->getClassInterface();
4301 }
John McCalld2930c22011-07-22 02:45:48 +00004302
Douglas Gregorbab8a962011-09-08 01:46:34 +00004303 ResultTypeCompatibilityKind RTC
4304 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004305
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004306 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004307
John McCall31168b02011-06-15 23:02:42 +00004308 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004309 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004310 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004311
Douglas Gregorbab8a962011-09-08 01:46:34 +00004312 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004313 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004314 !ObjCMethod->hasRelatedResultType() &&
4315 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004316 bool InferRelatedResultType = false;
4317 switch (ObjCMethod->getMethodFamily()) {
4318 case OMF_None:
4319 case OMF_copy:
4320 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004321 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004322 case OMF_mutableCopy:
4323 case OMF_release:
4324 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004325 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004326 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004327 break;
4328
4329 case OMF_alloc:
4330 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004331 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004332 break;
4333
4334 case OMF_init:
4335 case OMF_autorelease:
4336 case OMF_retain:
4337 case OMF_self:
4338 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4339 break;
4340 }
4341
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004342 if (InferRelatedResultType &&
4343 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004344 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004345 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004346
4347 ActOnDocumentableDecl(ObjCMethod);
4348
John McCall48871652010-08-21 09:40:31 +00004349 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004350}
4351
Chris Lattner438e5012008-12-17 07:13:27 +00004352bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004353 // Following is also an error. But it is caused by a missing @end
4354 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004355 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004356 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004357
4358 // If we switched context to translation unit while we are still lexically in
4359 // an objc container, it means the parser missed emitting an error.
4360 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4361 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004362
Anders Carlssona6b508a2008-11-04 16:57:32 +00004363 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4364 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004365
Anders Carlssona6b508a2008-11-04 16:57:32 +00004366 return true;
4367}
Chris Lattner438e5012008-12-17 07:13:27 +00004368
James Dennett634962f2012-06-14 21:40:34 +00004369/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004370/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004371void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004372 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004373 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004374 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004375 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004376 if (!Class) {
4377 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4378 return;
4379 }
John McCall5fb5df92012-06-20 06:18:46 +00004380 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004381 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4382 return;
4383 }
Mike Stump11289f42009-09-09 15:08:12 +00004384
Chris Lattner438e5012008-12-17 07:13:27 +00004385 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004386 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004387 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004388 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004389 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004390 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCall48871652010-08-21 09:40:31 +00004391 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004392 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4393 /*FIXME: StartL=*/ID->getLocation(),
4394 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004395 ID->getIdentifier(), ID->getType(),
4396 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004397 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004398 }
Mike Stump11289f42009-09-09 15:08:12 +00004399
Chris Lattner438e5012008-12-17 07:13:27 +00004400 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004401 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004402 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004403 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004404 if (getLangOpts().CPlusPlus)
Chris Lattner438e5012008-12-17 07:13:27 +00004405 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCall48871652010-08-21 09:40:31 +00004406 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004407 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004408 }
4409}
4410
Douglas Gregorf3564192010-04-26 17:32:49 +00004411/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004412VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4413 SourceLocation StartLoc,
4414 SourceLocation IdLoc,
4415 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004416 bool Invalid) {
4417 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4418 // duration shall not be qualified by an address-space qualifier."
4419 // Since all parameters have automatic store duration, they can not have
4420 // an address space.
4421 if (T.getAddressSpace() != 0) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004422 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004423 Invalid = true;
4424 }
4425
4426 // An @catch parameter must be an unqualified object pointer type;
4427 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4428 if (Invalid) {
4429 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004430 } else if (T->isDependentType()) {
4431 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004432 } else if (!T->isObjCObjectPointerType()) {
4433 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004434 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004435 } else if (T->isObjCQualifiedIdType()) {
4436 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004437 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004438 }
4439
Abramo Bagnaradff19302011-03-08 08:55:46 +00004440 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004441 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004442 New->setExceptionVariable(true);
4443
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004444 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004445 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004446 Invalid = true;
4447
Douglas Gregorf3564192010-04-26 17:32:49 +00004448 if (Invalid)
4449 New->setInvalidDecl();
4450 return New;
4451}
4452
John McCall48871652010-08-21 09:40:31 +00004453Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004454 const DeclSpec &DS = D.getDeclSpec();
4455
4456 // We allow the "register" storage class on exception variables because
4457 // GCC did, but we drop it completely. Any other storage class is an error.
4458 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4459 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4460 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004461 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004462 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004463 << DeclSpec::getSpecifierName(SCS);
4464 }
4465 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4466 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4467 diag::err_invalid_thread)
4468 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004469 D.getMutableDeclSpec().ClearStorageClassSpecs();
4470
Richard Smithb1402ae2013-03-18 22:52:47 +00004471 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004472
4473 // Check that there are no default arguments inside the type of this
4474 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004475 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004476 CheckExtraCXXDefaultArguments(D);
4477
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004478 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004479 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004480
Abramo Bagnaradff19302011-03-08 08:55:46 +00004481 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4482 D.getSourceRange().getBegin(),
4483 D.getIdentifierLoc(),
4484 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004485 D.isInvalidType());
4486
4487 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4488 if (D.getCXXScopeSpec().isSet()) {
4489 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4490 << D.getCXXScopeSpec().getRange();
4491 New->setInvalidDecl();
4492 }
4493
4494 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004495 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004496 if (D.getIdentifier())
4497 IdResolver.AddDecl(New);
4498
4499 ProcessDeclAttributes(S, New, D);
4500
4501 if (New->hasAttr<BlocksAttr>())
4502 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004503 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004504}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004505
4506/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004507/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004508void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004509 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004510 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4511 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004512 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004513 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004514 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004515 }
4516}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004517
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004518void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004519 // Load referenced selectors from the external source.
4520 if (ExternalSource) {
4521 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4522 ExternalSource->ReadReferencedSelectors(Sels);
4523 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4524 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4525 }
4526
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004527 // Warning will be issued only when selector table is
4528 // generated (which means there is at lease one implementation
4529 // in the TU). This is to match gcc's behavior.
4530 if (ReferencedSelectors.empty() ||
4531 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004532 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004533 for (auto &SelectorAndLocation : ReferencedSelectors) {
4534 Selector Sel = SelectorAndLocation.first;
4535 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004536 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004537 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004538 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004539}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004540
4541ObjCIvarDecl *
4542Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4543 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004544 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004545 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004546 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4547 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004548 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004549 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4550 /*shallowCategoryLookup=*/false,
4551 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004552 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004553 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004554 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004555 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4556 // property backing ivar must belong to property's class
4557 // or be a private ivar in class's implementation.
4558 // FIXME. fix the const-ness issue.
4559 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4560 IV->getIdentifier());
4561 return IV;
4562 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004563 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004564}
4565
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004566namespace {
4567 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4568 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004569 class UnusedBackingIvarChecker :
4570 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004571 public:
4572 Sema &S;
4573 const ObjCMethodDecl *Method;
4574 const ObjCIvarDecl *IvarD;
4575 bool AccessedIvar;
4576 bool InvokedSelfMethod;
4577
4578 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4579 const ObjCIvarDecl *IvarD)
4580 : S(S), Method(Method), IvarD(IvarD),
4581 AccessedIvar(false), InvokedSelfMethod(false) {
4582 assert(IvarD);
4583 }
4584
4585 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4586 if (E->getDecl() == IvarD) {
4587 AccessedIvar = true;
4588 return false;
4589 }
4590 return true;
4591 }
4592
4593 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4594 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4595 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4596 InvokedSelfMethod = true;
4597 }
4598 return true;
4599 }
4600 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00004601} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004602
4603void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4604 const ObjCImplementationDecl *ImplD) {
4605 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004606 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004607
Aaron Ballmanf26acce2014-03-13 19:50:17 +00004608 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004609 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4610 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004611 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004612 continue;
4613
4614 const ObjCPropertyDecl *PDecl;
4615 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4616 if (!IV)
4617 continue;
4618
4619 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4620 Checker.TraverseStmt(CurMethod->getBody());
4621 if (Checker.AccessedIvar)
4622 continue;
4623
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004624 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004625 // implementation makes a self call. This is to prevent false positive in
4626 // cases where the ivar is accessed by another method that the accessor
4627 // delegates to.
4628 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00004629 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004630 Diag(PDecl->getLocation(), diag::note_property_declare);
4631 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004632 }
4633}