blob: 7b9b9c148c13ded04c8871abe6a97c526d1a922c [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)) {
Aaron Ballman36a53502014-01-16 13:03:14 +0000103 method->addAttr(UnavailableAttr::CreateImplicit(Context,
104 "init method returns a type unrelated to its receiver type",
105 loc));
John McCall31168b02011-06-15 23:02:42 +0000106 return true;
107 }
108
109 // Otherwise, it's an error.
110 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
111 method->setInvalidDecl();
112 return true;
113}
114
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000115void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000116 const ObjCMethodDecl *Overridden) {
Douglas Gregor33823722011-06-11 01:09:30 +0000117 if (Overridden->hasRelatedResultType() &&
118 !NewMethod->hasRelatedResultType()) {
119 // This can only happen when the method follows a naming convention that
120 // implies a related result type, and the original (overridden) method has
121 // a suitable return type, but the new (overriding) method does not have
122 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000123 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000124 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +0000125
126 // Figure out which class this method is part of, if any.
127 ObjCInterfaceDecl *CurrentClass
128 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
129 if (!CurrentClass) {
130 DeclContext *DC = NewMethod->getDeclContext();
131 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
132 CurrentClass = Cat->getClassInterface();
133 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
134 CurrentClass = Impl->getClassInterface();
135 else if (ObjCCategoryImplDecl *CatImpl
136 = dyn_cast<ObjCCategoryImplDecl>(DC))
137 CurrentClass = CatImpl->getClassInterface();
138 }
139
140 if (CurrentClass) {
141 Diag(NewMethod->getLocation(),
142 diag::warn_related_result_type_compatibility_class)
143 << Context.getObjCInterfaceType(CurrentClass)
144 << ResultType
145 << ResultTypeRange;
146 } else {
147 Diag(NewMethod->getLocation(),
148 diag::warn_related_result_type_compatibility_protocol)
149 << ResultType
150 << ResultTypeRange;
151 }
152
Douglas Gregorbab8a962011-09-08 01:46:34 +0000153 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
154 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000155 diag::note_related_result_type_family)
156 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000157 << Family;
158 else
159 Diag(Overridden->getLocation(),
160 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000161 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000162 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000163 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
164 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
165 Diag(NewMethod->getLocation(),
166 diag::err_nsreturns_retained_attribute_mismatch) << 1;
167 Diag(Overridden->getLocation(), diag::note_previous_decl)
168 << "method";
169 }
170 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
171 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
172 Diag(NewMethod->getLocation(),
173 diag::err_nsreturns_retained_attribute_mismatch) << 0;
174 Diag(Overridden->getLocation(), diag::note_previous_decl)
175 << "method";
176 }
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000177 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
178 oe = Overridden->param_end();
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000179 for (ObjCMethodDecl::param_iterator
180 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +0000181 ni != ne && oi != oe; ++ni, ++oi) {
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +0000182 const ParmVarDecl *oldDecl = (*oi);
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000183 ParmVarDecl *newDecl = (*ni);
184 if (newDecl->hasAttr<NSConsumedAttr>() !=
185 oldDecl->hasAttr<NSConsumedAttr>()) {
186 Diag(newDecl->getLocation(),
187 diag::err_nsconsumed_attribute_mismatch);
188 Diag(oldDecl->getLocation(), diag::note_previous_decl)
189 << "parameter";
190 }
191 }
192 }
Douglas Gregor33823722011-06-11 01:09:30 +0000193}
194
John McCall31168b02011-06-15 23:02:42 +0000195/// \brief Check a method declaration for compatibility with the Objective-C
196/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000197bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000198 ObjCMethodFamily family = method->getMethodFamily();
199 switch (family) {
200 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000201 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000202 case OMF_retain:
203 case OMF_release:
204 case OMF_autorelease:
205 case OMF_retainCount:
206 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000207 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000208 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000209 return false;
210
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000211 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000212 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000213 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000214 if (ResultTypeRange.isInvalid())
Alp Toker314cc812014-01-25 16:55:45 +0000215 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
216 << method->getReturnType()
217 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000218 else
Alp Toker314cc812014-01-25 16:55:45 +0000219 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
220 << method->getReturnType()
221 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000222 return true;
223 }
224 return false;
225
John McCall31168b02011-06-15 23:02:42 +0000226 case OMF_init:
227 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000228 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000229 return true;
230
Aaron Ballman36a53502014-01-16 13:03:14 +0000231 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000232
233 // Don't add a second copy of this attribute, but otherwise don't
234 // let it be suppressed.
235 if (method->hasAttr<NSReturnsRetainedAttr>())
236 return false;
237 break;
238
239 case OMF_alloc:
240 case OMF_copy:
241 case OMF_mutableCopy:
242 case OMF_new:
243 if (method->hasAttr<NSReturnsRetainedAttr>() ||
244 method->hasAttr<NSReturnsNotRetainedAttr>() ||
245 method->hasAttr<NSReturnsAutoreleasedAttr>())
246 return false;
247 break;
248 }
249
Aaron Ballman36a53502014-01-16 13:03:14 +0000250 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000251 return false;
252}
253
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000254static void DiagnoseObjCImplementedDeprecations(Sema &S,
255 NamedDecl *ND,
256 SourceLocation ImplLoc,
257 int select) {
Douglas Gregor20b2ebd2011-03-23 00:50:03 +0000258 if (ND && ND->isDeprecated()) {
Fariborz Jahanian6fd94352011-02-16 00:30:31 +0000259 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000260 if (select == 0)
Ted Kremenek59b10db2012-02-27 22:55:11 +0000261 S.Diag(ND->getLocation(), diag::note_method_declared_at)
262 << ND->getDeclName();
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000263 else
264 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
265 }
266}
267
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000268/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
269/// pool.
270void Sema::AddAnyMethodToGlobalPool(Decl *D) {
271 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
272
273 // If we don't have a valid method decl, simply return.
274 if (!MDecl)
275 return;
276 if (MDecl->isInstanceMethod())
277 AddInstanceMethodToGlobalPool(MDecl, true);
278 else
279 AddFactoryMethodToGlobalPool(MDecl, true);
280}
281
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000282/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
283/// has explicit ownership attribute; false otherwise.
284static bool
285HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
286 QualType T = Param->getType();
287
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000288 if (const PointerType *PT = T->getAs<PointerType>()) {
289 T = PT->getPointeeType();
290 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
291 T = RT->getPointeeType();
292 } else {
293 return true;
294 }
295
296 // If we have a lifetime qualifier, but it's local, we must have
297 // inferred it. So, it is implicit.
298 return !T.getLocalQualifiers().hasObjCLifetime();
299}
300
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000301/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
302/// and user declared, in the method definition's AST.
303void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000304 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000305 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000306
Steve Naroff542cd5d2008-07-25 17:57:26 +0000307 // If we don't have a valid method decl, simply return.
308 if (!MDecl)
309 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000310
Chris Lattnerda463fe2007-12-12 07:09:47 +0000311 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000312 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000313 PushFunctionScope();
314
Chris Lattnerda463fe2007-12-12 07:09:47 +0000315 // Create Decl objects for each parameter, entrring them in the scope for
316 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000317
318 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000319 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000320
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000321 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
322 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000323
Reid Kleckner5a115802013-06-24 14:38:26 +0000324 // The ObjC parser requires parameter names so there's no need to check.
325 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
326 /*CheckParameterNames=*/false);
327
Chris Lattner58258242008-04-10 02:22:51 +0000328 // Introduce all of the other parameters into this scope.
Aaron Ballman43b68be2014-03-07 17:50:17 +0000329 for (auto *Param : MDecl->params()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000330 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000331 getLangOpts().ObjCAutoRefCount &&
332 !HasExplicitOwnershipAttr(*this, Param))
333 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
334 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000335
Aaron Ballman43b68be2014-03-07 17:50:17 +0000336 if (Param->getIdentifier())
337 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000338 }
John McCall31168b02011-06-15 23:02:42 +0000339
340 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000341 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000342 switch (MDecl->getMethodFamily()) {
343 case OMF_retain:
344 case OMF_retainCount:
345 case OMF_release:
346 case OMF_autorelease:
347 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000348 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000349 break;
350
351 case OMF_None:
352 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000353 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000354 case OMF_alloc:
355 case OMF_init:
356 case OMF_mutableCopy:
357 case OMF_copy:
358 case OMF_new:
359 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000360 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000361 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000362 break;
363 }
364 }
365
Nico Weber715abaf2011-08-22 17:25:57 +0000366 // Warn on deprecated methods under -Wdeprecated-implementations,
367 // and prepare for warning on missing super calls.
368 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000369 ObjCMethodDecl *IMD =
370 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
371
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000372 if (IMD) {
373 ObjCImplDecl *ImplDeclOfMethodDef =
374 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
375 ObjCContainerDecl *ContDeclOfMethodDecl =
376 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000377 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000378 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
379 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000380 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
381 if (CD->IsClassExtension()) {
382 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
383 ImplDeclOfMethodDecl = OID->getImplementation();
384 } else
385 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000386 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000387 // No need to issue deprecated warning if deprecated mehod in class/category
388 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000389 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000390 DiagnoseObjCImplementedDeprecations(*this,
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000391 dyn_cast<NamedDecl>(IMD),
392 MDecl->getLocation(), 0);
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000393 }
Nico Weber715abaf2011-08-22 17:25:57 +0000394
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000395 if (MDecl->getMethodFamily() == OMF_init) {
396 if (MDecl->isDesignatedInitializerForTheInterface()) {
397 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000398 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000399 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000400 } else if (IC->hasDesignatedInitializers()) {
401 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000402 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000403 }
404 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000405
Nico Weber1fb82662011-08-28 22:35:17 +0000406 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000407 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
408 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
409 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000410 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000411 ObjCMethodFamily Family = MDecl->getMethodFamily();
412 if (Family == OMF_dealloc) {
413 if (!(getLangOpts().ObjCAutoRefCount ||
414 getLangOpts().getGC() == LangOptions::GCOnly))
415 getCurFunction()->ObjCShouldCallSuper = true;
416
417 } else if (Family == OMF_finalize) {
418 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
419 getCurFunction()->ObjCShouldCallSuper = true;
420
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000421 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000422 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000423 SuperClass->lookupMethod(MDecl->getSelector(),
424 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000425 getCurFunction()->ObjCShouldCallSuper =
426 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000427 }
Nico Weber1fb82662011-08-28 22:35:17 +0000428 }
Nico Weber715abaf2011-08-22 17:25:57 +0000429 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000430}
431
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000432namespace {
433
434// Callback to only accept typo corrections that are Objective-C classes.
435// If an ObjCInterfaceDecl* is given to the constructor, then the validation
436// function will reject corrections to that class.
437class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
438 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000439 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000440 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
441 : CurrentIDecl(IDecl) {}
442
Craig Toppere14c0f82014-03-12 04:55:44 +0000443 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000444 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
445 return ID && !declaresSameEntity(ID, CurrentIDecl);
446 }
447
448 private:
449 ObjCInterfaceDecl *CurrentIDecl;
450};
451
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000452}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000453
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000454static void diagnoseUseOfProtocols(Sema &TheSema,
455 ObjCContainerDecl *CD,
456 ObjCProtocolDecl *const *ProtoRefs,
457 unsigned NumProtoRefs,
458 const SourceLocation *ProtoLocs) {
459 assert(ProtoRefs);
460 // Diagnose availability in the context of the ObjC container.
461 Sema::ContextRAII SavedContext(TheSema, CD);
462 for (unsigned i = 0; i < NumProtoRefs; ++i) {
463 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]);
464 }
465}
466
Douglas Gregore9d95f12015-07-07 03:57:35 +0000467void Sema::
468ActOnSuperClassOfClassInterface(Scope *S,
469 SourceLocation AtInterfaceLoc,
470 ObjCInterfaceDecl *IDecl,
471 IdentifierInfo *ClassName,
472 SourceLocation ClassLoc,
473 IdentifierInfo *SuperName,
474 SourceLocation SuperLoc,
475 ArrayRef<ParsedType> SuperTypeArgs,
476 SourceRange SuperTypeArgsRange) {
477 // Check if a different kind of symbol declared in this scope.
478 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
479 LookupOrdinaryName);
480
481 if (!PrevDecl) {
482 // Try to correct for a typo in the superclass name without correcting
483 // to the class we're defining.
484 if (TypoCorrection Corrected = CorrectTypo(
485 DeclarationNameInfo(SuperName, SuperLoc),
486 LookupOrdinaryName, TUScope,
487 NULL, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
488 CTK_ErrorRecovery)) {
489 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
490 << SuperName << ClassName);
491 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
492 }
493 }
494
495 if (declaresSameEntity(PrevDecl, IDecl)) {
496 Diag(SuperLoc, diag::err_recursive_superclass)
497 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
498 IDecl->setEndOfDefinitionLoc(ClassLoc);
499 } else {
500 ObjCInterfaceDecl *SuperClassDecl =
501 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
502 QualType SuperClassType;
503
504 // Diagnose classes that inherit from deprecated classes.
505 if (SuperClassDecl) {
506 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
507 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
508 }
509
510 if (PrevDecl && SuperClassDecl == 0) {
511 // The previous declaration was not a class decl. Check if we have a
512 // typedef. If we do, get the underlying class type.
513 if (const TypedefNameDecl *TDecl =
514 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
515 QualType T = TDecl->getUnderlyingType();
516 if (T->isObjCObjectType()) {
517 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
518 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
519 SuperClassType = Context.getTypeDeclType(TDecl);
520
521 // This handles the following case:
522 // @interface NewI @end
523 // typedef NewI DeprI __attribute__((deprecated("blah")))
524 // @interface SI : DeprI /* warn here */ @end
525 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
526 }
527 }
528 }
529
530 // This handles the following case:
531 //
532 // typedef int SuperClass;
533 // @interface MyClass : SuperClass {} @end
534 //
535 if (!SuperClassDecl) {
536 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
537 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
538 }
539 }
540
541 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
542 if (!SuperClassDecl)
543 Diag(SuperLoc, diag::err_undef_superclass)
544 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
545 else if (RequireCompleteType(SuperLoc,
546 SuperClassType,
547 diag::err_forward_superclass,
548 SuperClassDecl->getDeclName(),
549 ClassName,
550 SourceRange(AtInterfaceLoc, ClassLoc))) {
551 SuperClassDecl = 0;
552 SuperClassType = QualType();
553 }
554 }
555
556 if (SuperClassType.isNull()) {
557 assert(!SuperClassDecl && "Failed to set SuperClassType?");
558 return;
559 }
560
561 // Handle type arguments on the superclass.
562 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000563 if (!SuperTypeArgs.empty()) {
564 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
565 S,
566 SuperLoc,
567 CreateParsedType(SuperClassType,
568 nullptr),
569 SuperTypeArgsRange.getBegin(),
570 SuperTypeArgs,
571 SuperTypeArgsRange.getEnd(),
572 SourceLocation(),
573 { },
574 { },
575 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000576 if (!fullSuperClassType.isUsable())
577 return;
578
579 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
580 &SuperClassTInfo);
581 }
582
583 if (!SuperClassTInfo) {
584 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
585 SuperLoc);
586 }
587
588 IDecl->setSuperClass(SuperClassTInfo);
589 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
590 }
591}
592
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000593DeclResult Sema::actOnObjCTypeParam(Scope *S,
594 ObjCTypeParamVariance variance,
595 SourceLocation varianceLoc,
596 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000597 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000598 SourceLocation paramLoc,
599 SourceLocation colonLoc,
600 ParsedType parsedTypeBound) {
601 // If there was an explicitly-provided type bound, check it.
602 TypeSourceInfo *typeBoundInfo = nullptr;
603 if (parsedTypeBound) {
604 // The type bound can be any Objective-C pointer type.
605 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
606 if (typeBound->isObjCObjectPointerType()) {
607 // okay
608 } else if (typeBound->isObjCObjectType()) {
609 // The user forgot the * on an Objective-C pointer type, e.g.,
610 // "T : NSView".
611 SourceLocation starLoc = PP.getLocForEndOfToken(
612 typeBoundInfo->getTypeLoc().getEndLoc());
613 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
614 diag::err_objc_type_param_bound_missing_pointer)
615 << typeBound << paramName
616 << FixItHint::CreateInsertion(starLoc, " *");
617
618 // Create a new type location builder so we can update the type
619 // location information we have.
620 TypeLocBuilder builder;
621 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
622
623 // Create the Objective-C pointer type.
624 typeBound = Context.getObjCObjectPointerType(typeBound);
625 ObjCObjectPointerTypeLoc newT
626 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
627 newT.setStarLoc(starLoc);
628
629 // Form the new type source information.
630 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
631 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000632 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000633 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
634 diag::err_objc_type_param_bound_nonobject)
635 << typeBound << paramName;
636
637 // Forget the bound; we'll default to id later.
638 typeBoundInfo = nullptr;
639 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000640
John McCall69975252015-09-23 22:14:21 +0000641 // Type bounds cannot have qualifiers (even indirectly) or explicit
642 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000643 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000644 QualType typeBound = typeBoundInfo->getType();
645 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
646 if (qual || typeBound.hasQualifiers()) {
647 bool diagnosed = false;
648 SourceRange rangeToRemove;
649 if (qual) {
650 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
651 rangeToRemove = attr.getLocalSourceRange();
652 if (attr.getTypePtr()->getImmediateNullability()) {
653 Diag(attr.getLocStart(),
654 diag::err_objc_type_param_bound_explicit_nullability)
655 << paramName << typeBound
656 << FixItHint::CreateRemoval(rangeToRemove);
657 diagnosed = true;
658 }
659 }
660 }
661
662 if (!diagnosed) {
663 Diag(qual ? qual.getLocStart()
664 : typeBoundInfo->getTypeLoc().getLocStart(),
665 diag::err_objc_type_param_bound_qualified)
666 << paramName << typeBound << typeBound.getQualifiers().getAsString()
667 << FixItHint::CreateRemoval(rangeToRemove);
668 }
669
670 // If the type bound has qualifiers other than CVR, we need to strip
671 // them or we'll probably assert later when trying to apply new
672 // qualifiers.
673 Qualifiers quals = typeBound.getQualifiers();
674 quals.removeCVRQualifiers();
675 if (!quals.empty()) {
676 typeBoundInfo =
677 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
678 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000679 }
680 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000681 }
682
683 // If there was no explicit type bound (or we removed it due to an error),
684 // use 'id' instead.
685 if (!typeBoundInfo) {
686 colonLoc = SourceLocation();
687 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
688 }
689
690 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000691 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
692 index, paramLoc, paramName, colonLoc,
693 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000694}
695
696ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
697 SourceLocation lAngleLoc,
698 ArrayRef<Decl *> typeParamsIn,
699 SourceLocation rAngleLoc) {
700 // We know that the array only contains Objective-C type parameters.
701 ArrayRef<ObjCTypeParamDecl *>
702 typeParams(
703 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
704 typeParamsIn.size());
705
706 // Diagnose redeclarations of type parameters.
707 // We do this now because Objective-C type parameters aren't pushed into
708 // scope until later (after the instance variable block), but we want the
709 // diagnostics to occur right after we parse the type parameter list.
710 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
711 for (auto typeParam : typeParams) {
712 auto known = knownParams.find(typeParam->getIdentifier());
713 if (known != knownParams.end()) {
714 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
715 << typeParam->getIdentifier()
716 << SourceRange(known->second->getLocation());
717
718 typeParam->setInvalidDecl();
719 } else {
720 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
721
722 // Push the type parameter into scope.
723 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
724 }
725 }
726
727 // Create the parameter list.
728 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
729}
730
731void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
732 for (auto typeParam : *typeParamList) {
733 if (!typeParam->isInvalidDecl()) {
734 S->RemoveDecl(typeParam);
735 IdResolver.RemoveDecl(typeParam);
736 }
737 }
738}
739
740namespace {
741 /// The context in which an Objective-C type parameter list occurs, for use
742 /// in diagnostics.
743 enum class TypeParamListContext {
744 ForwardDeclaration,
745 Definition,
746 Category,
747 Extension
748 };
749}
750
751/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000752/// between a category/extension and an \@interface or between an \@class and an
753/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000754static bool checkTypeParamListConsistency(Sema &S,
755 ObjCTypeParamList *prevTypeParams,
756 ObjCTypeParamList *newTypeParams,
757 TypeParamListContext newContext) {
758 // If the sizes don't match, complain about that.
759 if (prevTypeParams->size() != newTypeParams->size()) {
760 SourceLocation diagLoc;
761 if (newTypeParams->size() > prevTypeParams->size()) {
762 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
763 } else {
764 diagLoc = S.PP.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
765 }
766
767 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
768 << static_cast<unsigned>(newContext)
769 << (newTypeParams->size() > prevTypeParams->size())
770 << prevTypeParams->size()
771 << newTypeParams->size();
772
773 return true;
774 }
775
776 // Match up the type parameters.
777 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
778 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
779 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
780
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000781 // Check for consistency of the variance.
782 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
783 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
784 newContext != TypeParamListContext::Definition) {
785 // When the new type parameter is invariant and is not part
786 // of the definition, just propagate the variance.
787 newTypeParam->setVariance(prevTypeParam->getVariance());
788 } else if (prevTypeParam->getVariance()
789 == ObjCTypeParamVariance::Invariant &&
790 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
791 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
792 ->getDefinition() == prevTypeParam->getDeclContext())) {
793 // When the old parameter is invariant and was not part of the
794 // definition, just ignore the difference because it doesn't
795 // matter.
796 } else {
797 {
798 // Diagnose the conflict and update the second declaration.
799 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
800 if (diagLoc.isInvalid())
801 diagLoc = newTypeParam->getLocStart();
802
803 auto diag = S.Diag(diagLoc,
804 diag::err_objc_type_param_variance_conflict)
805 << static_cast<unsigned>(newTypeParam->getVariance())
806 << newTypeParam->getDeclName()
807 << static_cast<unsigned>(prevTypeParam->getVariance())
808 << prevTypeParam->getDeclName();
809 switch (prevTypeParam->getVariance()) {
810 case ObjCTypeParamVariance::Invariant:
811 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
812 break;
813
814 case ObjCTypeParamVariance::Covariant:
815 case ObjCTypeParamVariance::Contravariant: {
816 StringRef newVarianceStr
817 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
818 ? "__covariant"
819 : "__contravariant";
820 if (newTypeParam->getVariance()
821 == ObjCTypeParamVariance::Invariant) {
822 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
823 (newVarianceStr + " ").str());
824 } else {
825 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
826 newVarianceStr);
827 }
828 }
829 }
830 }
831
832 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
833 << prevTypeParam->getDeclName();
834
835 // Override the variance.
836 newTypeParam->setVariance(prevTypeParam->getVariance());
837 }
838 }
839
Douglas Gregor85f3f952015-07-07 03:57:15 +0000840 // If the bound types match, there's nothing to do.
841 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
842 newTypeParam->getUnderlyingType()))
843 continue;
844
845 // If the new type parameter's bound was explicit, complain about it being
846 // different from the original.
847 if (newTypeParam->hasExplicitBound()) {
848 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
849 ->getTypeLoc().getSourceRange();
850 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
851 << newTypeParam->getUnderlyingType()
852 << newTypeParam->getDeclName()
853 << prevTypeParam->hasExplicitBound()
854 << prevTypeParam->getUnderlyingType()
855 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
856 << prevTypeParam->getDeclName()
857 << FixItHint::CreateReplacement(
858 newBoundRange,
859 prevTypeParam->getUnderlyingType().getAsString(
860 S.Context.getPrintingPolicy()));
861
862 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
863 << prevTypeParam->getDeclName();
864
865 // Override the new type parameter's bound type with the previous type,
866 // so that it's consistent.
867 newTypeParam->setTypeSourceInfo(
868 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
869 continue;
870 }
871
872 // The new type parameter got the implicit bound of 'id'. That's okay for
873 // categories and extensions (overwrite it later), but not for forward
874 // declarations and @interfaces, because those must be standalone.
875 if (newContext == TypeParamListContext::ForwardDeclaration ||
876 newContext == TypeParamListContext::Definition) {
877 // Diagnose this problem for forward declarations and definitions.
878 SourceLocation insertionLoc
879 = S.PP.getLocForEndOfToken(newTypeParam->getLocation());
880 std::string newCode
881 = " : " + prevTypeParam->getUnderlyingType().getAsString(
882 S.Context.getPrintingPolicy());
883 S.Diag(newTypeParam->getLocation(),
884 diag::err_objc_type_param_bound_missing)
885 << prevTypeParam->getUnderlyingType()
886 << newTypeParam->getDeclName()
887 << (newContext == TypeParamListContext::ForwardDeclaration)
888 << FixItHint::CreateInsertion(insertionLoc, newCode);
889
890 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
891 << prevTypeParam->getDeclName();
892 }
893
894 // Update the new type parameter's bound to match the previous one.
895 newTypeParam->setTypeSourceInfo(
896 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
897 }
898
899 return false;
900}
901
John McCall48871652010-08-21 09:40:31 +0000902Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000903ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000904 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000905 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000906 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000907 ArrayRef<ParsedType> SuperTypeArgs,
908 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000909 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000910 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000911 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000912 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000913
Chris Lattnerda463fe2007-12-12 07:09:47 +0000914 // Check for another declaration kind with the same name.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000915 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000916 LookupOrdinaryName, ForRedeclaration);
Douglas Gregor5101c242008-12-05 18:15:24 +0000917
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000918 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000919 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000920 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000921 }
Mike Stump11289f42009-09-09 15:08:12 +0000922
Douglas Gregordc9166c2011-12-15 20:29:51 +0000923 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000924 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000925
926 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
927 // A previous decl with a different name is because of
928 // @compatibility_alias, for example:
929 // \code
930 // @class NewImage;
931 // @compatibility_alias OldImage NewImage;
932 // \endcode
933 // A lookup for 'OldImage' will return the 'NewImage' decl.
934 //
935 // In such a case use the real declaration name, instead of the alias one,
936 // otherwise we will break IdentifierResolver and redecls-chain invariants.
937 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
938 // has been aliased.
939 ClassName = PrevIDecl->getIdentifier();
940 }
941
Douglas Gregor85f3f952015-07-07 03:57:15 +0000942 // If there was a forward declaration with type parameters, check
943 // for consistency.
944 if (PrevIDecl) {
945 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
946 if (typeParamList) {
947 // Both have type parameter lists; check for consistency.
948 if (checkTypeParamListConsistency(*this, prevTypeParamList,
949 typeParamList,
950 TypeParamListContext::Definition)) {
951 typeParamList = nullptr;
952 }
953 } else {
954 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
955 << ClassName;
956 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
957 << ClassName;
958
959 // Clone the type parameter list.
960 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
961 for (auto typeParam : *prevTypeParamList) {
962 clonedTypeParams.push_back(
963 ObjCTypeParamDecl::Create(
964 Context,
965 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000966 typeParam->getVariance(),
967 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000968 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +0000969 SourceLocation(),
970 typeParam->getIdentifier(),
971 SourceLocation(),
972 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
973 }
974
975 typeParamList = ObjCTypeParamList::create(Context,
976 SourceLocation(),
977 clonedTypeParams,
978 SourceLocation());
979 }
980 }
981 }
982
Douglas Gregordc9166c2011-12-15 20:29:51 +0000983 ObjCInterfaceDecl *IDecl
984 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000985 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000986 if (PrevIDecl) {
987 // Class already seen. Was it a definition?
988 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
989 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
990 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +0000991 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000992 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +0000993 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000994 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000995
996 if (AttrList)
997 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
998 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Douglas Gregordc9166c2011-12-15 20:29:51 +00001000 // Start the definition of this class. If we're in a redefinition case, there
1001 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001002 if (!IDecl->hasDefinition())
1003 IDecl->startDefinition();
1004
Chris Lattnerda463fe2007-12-12 07:09:47 +00001005 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001006 // Diagnose availability in the context of the @interface.
1007 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001008
Douglas Gregore9d95f12015-07-07 03:57:35 +00001009 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1010 ClassName, ClassLoc,
1011 SuperName, SuperLoc, SuperTypeArgs,
1012 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001013 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001014 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001015 }
Mike Stump11289f42009-09-09 15:08:12 +00001016
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001017 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001018 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001019 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1020 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001021 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001022 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001023 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001024 }
Mike Stump11289f42009-09-09 15:08:12 +00001025
Anders Carlssona6b508a2008-11-04 16:57:32 +00001026 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001027 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001028}
1029
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001030/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1031/// typedef'ed use for a qualified super class and adds them to the list
1032/// of the protocols.
1033void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1034 IdentifierInfo *SuperName,
1035 SourceLocation SuperLoc) {
1036 if (!SuperName)
1037 return;
1038 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1039 LookupOrdinaryName);
1040 if (!IDecl)
1041 return;
1042
1043 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1044 QualType T = TDecl->getUnderlyingType();
1045 if (T->isObjCObjectType())
1046 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
Benjamin Kramerf9890422015-02-17 16:48:30 +00001047 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001048 }
1049}
1050
Richard Smithac4e36d2012-08-08 23:32:13 +00001051/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001052/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001053Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1054 IdentifierInfo *AliasName,
1055 SourceLocation AliasLocation,
1056 IdentifierInfo *ClassName,
1057 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001058 // Look for previous declaration of alias name
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001059 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001060 LookupOrdinaryName, ForRedeclaration);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001061 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001062 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001063 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001064 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001065 }
1066 // Check for class declaration
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001067 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001068 LookupOrdinaryName, ForRedeclaration);
Richard Smithdda56e42011-04-15 14:24:37 +00001069 if (const TypedefNameDecl *TDecl =
1070 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001071 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001072 if (T->isObjCObjectType()) {
1073 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001074 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001075 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001076 LookupOrdinaryName, ForRedeclaration);
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001077 }
1078 }
1079 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001080 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001081 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001082 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001083 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001084 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001085 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001086 }
Mike Stump11289f42009-09-09 15:08:12 +00001087
Chris Lattner219b3e92008-03-16 21:17:37 +00001088 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001089 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001090 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001091
Anders Carlssona6b508a2008-11-04 16:57:32 +00001092 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001093 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001094
John McCall48871652010-08-21 09:40:31 +00001095 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001096}
1097
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001098bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001099 IdentifierInfo *PName,
1100 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001101 const ObjCList<ObjCProtocolDecl> &PList) {
1102
1103 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001104 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1105 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001106 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1107 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001108 if (PDecl->getIdentifier() == PName) {
1109 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1110 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001111 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001112 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001113
1114 if (!PDecl->hasDefinition())
1115 continue;
1116
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001117 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1118 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1119 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001120 }
1121 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001122 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001123}
1124
John McCall48871652010-08-21 09:40:31 +00001125Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001126Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1127 IdentifierInfo *ProtocolName,
1128 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001129 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001130 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001131 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001132 SourceLocation EndProtoLoc,
1133 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001134 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001135 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001136 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001137 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1138 ForRedeclaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001139 ObjCProtocolDecl *PDecl = nullptr;
1140 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001141 // If we already have a definition, complain.
1142 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1143 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001144
Douglas Gregor32c17572012-01-01 20:30:41 +00001145 // Create a new protocol that is completely distinct from previous
1146 // declarations, and do not make this protocol available for name lookup.
1147 // That way, we'll end up completely ignoring the duplicate.
1148 // FIXME: Can we turn this into an error?
1149 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1150 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001151 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001152 PDecl->startDefinition();
1153 } else {
1154 if (PrevDecl) {
1155 // Check for circular dependencies among protocol declarations. This can
1156 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001157 ObjCList<ObjCProtocolDecl> PList;
1158 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1159 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001160 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001161 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001162
1163 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001164 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001165 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001166 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001167
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001168 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001169 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001170 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001171
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001172 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001173 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001174
1175 // Merge attributes from previous declarations.
1176 if (PrevDecl)
1177 mergeDeclAttributes(PDecl, PrevDecl);
1178
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001179 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001180 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001181 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1182 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001183 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001184 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001185 }
Mike Stump11289f42009-09-09 15:08:12 +00001186
1187 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001188 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001189}
1190
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001191static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1192 ObjCProtocolDecl *&UndefinedProtocol) {
1193 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1194 UndefinedProtocol = PDecl;
1195 return true;
1196 }
1197
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001198 for (auto *PI : PDecl->protocols())
1199 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1200 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001201 return true;
1202 }
1203 return false;
1204}
1205
Chris Lattnerda463fe2007-12-12 07:09:47 +00001206/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001207/// issues an error if they are not declared. It returns list of
1208/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001209void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001210Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001211 const IdentifierLocPair *ProtocolId,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001212 unsigned NumProtocols,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001213 SmallVectorImpl<Decl *> &Protocols) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001214 for (unsigned i = 0; i != NumProtocols; ++i) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001215 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
1216 ProtocolId[i].second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001217 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001218 TypoCorrection Corrected = CorrectTypo(
1219 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001220 LookupObjCProtocolName, TUScope, nullptr,
1221 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001222 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001223 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1224 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1225 << ProtocolId[i].first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001226 }
1227
1228 if (!PDecl) {
Chris Lattner3b054132008-11-19 05:08:23 +00001229 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001230 << ProtocolId[i].first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001231 continue;
1232 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001233 // If this is a forward protocol declaration, get its definition.
1234 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1235 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001236
1237 // For an objc container, delay protocol reference checking until after we
1238 // can set the objc decl as the availability context, otherwise check now.
1239 if (!ForObjCContainer) {
1240 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
1241 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001242
1243 // If this is a forward declaration and we are supposed to warn in this
1244 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001245 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001246 ObjCProtocolDecl *UndefinedProtocol;
1247
Douglas Gregoreed49792013-01-17 00:38:46 +00001248 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001249 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Chris Lattner3b054132008-11-19 05:08:23 +00001250 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001251 << ProtocolId[i].first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001252 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1253 << UndefinedProtocol;
1254 }
John McCall48871652010-08-21 09:40:31 +00001255 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001256 }
1257}
1258
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001259namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001260// Callback to only accept typo corrections that are either
1261// Objective-C protocols or valid Objective-C type arguments.
1262class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1263 ASTContext &Context;
1264 Sema::LookupNameKind LookupKind;
1265 public:
1266 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1267 Sema::LookupNameKind lookupKind)
1268 : Context(context), LookupKind(lookupKind) { }
1269
1270 bool ValidateCandidate(const TypoCorrection &candidate) override {
1271 // If we're allowed to find protocols and we have a protocol, accept it.
1272 if (LookupKind != Sema::LookupOrdinaryName) {
1273 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1274 return true;
1275 }
1276
1277 // If we're allowed to find type names and we have one, accept it.
1278 if (LookupKind != Sema::LookupObjCProtocolName) {
1279 // If we have a type declaration, we might accept this result.
1280 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1281 // If we found a tag declaration outside of C++, skip it. This
1282 // can happy because we look for any name when there is no
1283 // bias to protocol or type names.
1284 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1285 return false;
1286
1287 // Make sure the type is something we would accept as a type
1288 // argument.
1289 auto type = Context.getTypeDeclType(typeDecl);
1290 if (type->isObjCObjectPointerType() ||
1291 type->isBlockPointerType() ||
1292 type->isDependentType() ||
1293 type->isObjCObjectType())
1294 return true;
1295
1296 return false;
1297 }
1298
1299 // If we have an Objective-C class type, accept it; there will
1300 // be another fix to add the '*'.
1301 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1302 return true;
1303
1304 return false;
1305 }
1306
1307 return false;
1308 }
1309};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001310} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001311
1312void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1313 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001314 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001315 SourceLocation lAngleLoc,
1316 ArrayRef<IdentifierInfo *> identifiers,
1317 ArrayRef<SourceLocation> identifierLocs,
1318 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001319 SourceLocation &typeArgsLAngleLoc,
1320 SmallVectorImpl<ParsedType> &typeArgs,
1321 SourceLocation &typeArgsRAngleLoc,
1322 SourceLocation &protocolLAngleLoc,
1323 SmallVectorImpl<Decl *> &protocols,
1324 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001325 bool warnOnIncompleteProtocols) {
1326 // Local function that updates the declaration specifiers with
1327 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001328 unsigned numProtocolsResolved = 0;
1329 auto resolvedAsProtocols = [&] {
1330 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1331
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001332 // Determine whether the base type is a parameterized class, in
1333 // which case we want to warn about typos such as
1334 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1335 ObjCInterfaceDecl *baseClass = nullptr;
1336 QualType base = GetTypeFromParser(baseType, nullptr);
1337 bool allAreTypeNames = false;
1338 SourceLocation firstClassNameLoc;
1339 if (!base.isNull()) {
1340 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1341 baseClass = objcObjectType->getInterface();
1342 if (baseClass) {
1343 if (auto typeParams = baseClass->getTypeParamList()) {
1344 if (typeParams->size() == numProtocolsResolved) {
1345 // Note that we should be looking for type names, too.
1346 allAreTypeNames = true;
1347 }
1348 }
1349 }
1350 }
1351 }
1352
Douglas Gregore9d95f12015-07-07 03:57:35 +00001353 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001354 ObjCProtocolDecl *&proto
1355 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001356 // For an objc container, delay protocol reference checking until after we
1357 // can set the objc decl as the availability context, otherwise check now.
1358 if (!warnOnIncompleteProtocols) {
1359 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1360 }
1361
1362 // If this is a forward protocol declaration, get its definition.
1363 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1364 proto = proto->getDefinition();
1365
1366 // If this is a forward declaration and we are supposed to warn in this
1367 // case, do it.
1368 // FIXME: Recover nicely in the hidden case.
1369 ObjCProtocolDecl *forwardDecl = nullptr;
1370 if (warnOnIncompleteProtocols &&
1371 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1372 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1373 << proto->getDeclName();
1374 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1375 << forwardDecl;
1376 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001377
1378 // If everything this far has been a type name (and we care
1379 // about such things), check whether this name refers to a type
1380 // as well.
1381 if (allAreTypeNames) {
1382 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1383 LookupOrdinaryName)) {
1384 if (isa<ObjCInterfaceDecl>(decl)) {
1385 if (firstClassNameLoc.isInvalid())
1386 firstClassNameLoc = identifierLocs[i];
1387 } else if (!isa<TypeDecl>(decl)) {
1388 // Not a type.
1389 allAreTypeNames = false;
1390 }
1391 } else {
1392 allAreTypeNames = false;
1393 }
1394 }
1395 }
1396
1397 // All of the protocols listed also have type names, and at least
1398 // one is an Objective-C class name. Check whether all of the
1399 // protocol conformances are declared by the base class itself, in
1400 // which case we warn.
1401 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1402 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1403 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1404 bool allProtocolsDeclared = true;
1405 for (auto proto : protocols) {
1406 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1407 allProtocolsDeclared = false;
1408 break;
1409 }
1410 }
1411
1412 if (allProtocolsDeclared) {
1413 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1414 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1415 << FixItHint::CreateInsertion(
1416 PP.getLocForEndOfToken(firstClassNameLoc), " *");
1417 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001418 }
1419
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001420 protocolLAngleLoc = lAngleLoc;
1421 protocolRAngleLoc = rAngleLoc;
1422 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001423 };
1424
1425 // Attempt to resolve all of the identifiers as protocols.
1426 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1427 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1428 protocols.push_back(proto);
1429 if (proto)
1430 ++numProtocolsResolved;
1431 }
1432
1433 // If all of the names were protocols, these were protocol qualifiers.
1434 if (numProtocolsResolved == identifiers.size())
1435 return resolvedAsProtocols();
1436
1437 // Attempt to resolve all of the identifiers as type names or
1438 // Objective-C class names. The latter is technically ill-formed,
1439 // but is probably something like \c NSArray<NSView *> missing the
1440 // \c*.
1441 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1442 SmallVector<TypeOrClassDecl, 4> typeDecls;
1443 unsigned numTypeDeclsResolved = 0;
1444 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1445 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1446 LookupOrdinaryName);
1447 if (!decl) {
1448 typeDecls.push_back(TypeOrClassDecl());
1449 continue;
1450 }
1451
1452 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1453 typeDecls.push_back(typeDecl);
1454 ++numTypeDeclsResolved;
1455 continue;
1456 }
1457
1458 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1459 typeDecls.push_back(objcClass);
1460 ++numTypeDeclsResolved;
1461 continue;
1462 }
1463
1464 typeDecls.push_back(TypeOrClassDecl());
1465 }
1466
1467 AttributeFactory attrFactory;
1468
1469 // Local function that forms a reference to the given type or
1470 // Objective-C class declaration.
1471 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1472 -> TypeResult {
1473 // Form declaration specifiers. They simply refer to the type.
1474 DeclSpec DS(attrFactory);
1475 const char* prevSpec; // unused
1476 unsigned diagID; // unused
1477 QualType type;
1478 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1479 type = Context.getTypeDeclType(actualTypeDecl);
1480 else
1481 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1482 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1483 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1484 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1485 parsedType, Context.getPrintingPolicy());
1486 // Use the identifier location for the type source range.
1487 DS.SetRangeStart(loc);
1488 DS.SetRangeEnd(loc);
1489
1490 // Form the declarator.
1491 Declarator D(DS, Declarator::TypeNameContext);
1492
1493 // If we have a typedef of an Objective-C class type that is missing a '*',
1494 // add the '*'.
1495 if (type->getAs<ObjCInterfaceType>()) {
1496 SourceLocation starLoc = PP.getLocForEndOfToken(loc);
1497 ParsedAttributes parsedAttrs(attrFactory);
1498 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1499 SourceLocation(),
1500 SourceLocation(),
1501 SourceLocation(),
1502 SourceLocation()),
1503 parsedAttrs,
1504 starLoc);
1505
1506 // Diagnose the missing '*'.
1507 Diag(loc, diag::err_objc_type_arg_missing_star)
1508 << type
1509 << FixItHint::CreateInsertion(starLoc, " *");
1510 }
1511
1512 // Convert this to a type.
1513 return ActOnTypeName(S, D);
1514 };
1515
1516 // Local function that updates the declaration specifiers with
1517 // type argument information.
1518 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001519 // We did not resolve these as protocols.
1520 protocols.clear();
1521
Douglas Gregore9d95f12015-07-07 03:57:35 +00001522 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1523 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001524 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1525 // Map type reference to a type.
1526 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001527 if (!type.isUsable()) {
1528 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001529 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001530 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001531
1532 typeArgs.push_back(type.get());
1533 }
1534
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001535 typeArgsLAngleLoc = lAngleLoc;
1536 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001537 };
1538
1539 // If all of the identifiers can be resolved as type names or
1540 // Objective-C class names, we have type arguments.
1541 if (numTypeDeclsResolved == identifiers.size())
1542 return resolvedAsTypeDecls();
1543
1544 // Error recovery: some names weren't found, or we have a mix of
1545 // type and protocol names. Go resolve all of the unresolved names
1546 // and complain if we can't find a consistent answer.
1547 LookupNameKind lookupKind = LookupAnyName;
1548 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1549 // If we already have a protocol or type. Check whether it is the
1550 // right thing.
1551 if (protocols[i] || typeDecls[i]) {
1552 // If we haven't figured out whether we want types or protocols
1553 // yet, try to figure it out from this name.
1554 if (lookupKind == LookupAnyName) {
1555 // If this name refers to both a protocol and a type (e.g., \c
1556 // NSObject), don't conclude anything yet.
1557 if (protocols[i] && typeDecls[i])
1558 continue;
1559
1560 // Otherwise, let this name decide whether we'll be correcting
1561 // toward types or protocols.
1562 lookupKind = protocols[i] ? LookupObjCProtocolName
1563 : LookupOrdinaryName;
1564 continue;
1565 }
1566
1567 // If we want protocols and we have a protocol, there's nothing
1568 // more to do.
1569 if (lookupKind == LookupObjCProtocolName && protocols[i])
1570 continue;
1571
1572 // If we want types and we have a type declaration, there's
1573 // nothing more to do.
1574 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1575 continue;
1576
1577 // We have a conflict: some names refer to protocols and others
1578 // refer to types.
1579 Diag(identifierLocs[i], diag::err_objc_type_args_and_protocols)
1580 << (protocols[i] != nullptr)
1581 << identifiers[i]
1582 << identifiers[0]
1583 << SourceRange(identifierLocs[0]);
1584
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001585 protocols.clear();
1586 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001587 return;
1588 }
1589
1590 // Perform typo correction on the name.
1591 TypoCorrection corrected = CorrectTypo(
1592 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1593 nullptr,
1594 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1595 lookupKind),
1596 CTK_ErrorRecovery);
1597 if (corrected) {
1598 // Did we find a protocol?
1599 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1600 diagnoseTypo(corrected,
1601 PDiag(diag::err_undeclared_protocol_suggest)
1602 << identifiers[i]);
1603 lookupKind = LookupObjCProtocolName;
1604 protocols[i] = proto;
1605 ++numProtocolsResolved;
1606 continue;
1607 }
1608
1609 // Did we find a type?
1610 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1611 diagnoseTypo(corrected,
1612 PDiag(diag::err_unknown_typename_suggest)
1613 << identifiers[i]);
1614 lookupKind = LookupOrdinaryName;
1615 typeDecls[i] = typeDecl;
1616 ++numTypeDeclsResolved;
1617 continue;
1618 }
1619
1620 // Did we find an Objective-C class?
1621 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1622 diagnoseTypo(corrected,
1623 PDiag(diag::err_unknown_type_or_class_name_suggest)
1624 << identifiers[i] << true);
1625 lookupKind = LookupOrdinaryName;
1626 typeDecls[i] = objcClass;
1627 ++numTypeDeclsResolved;
1628 continue;
1629 }
1630 }
1631
1632 // We couldn't find anything.
1633 Diag(identifierLocs[i],
1634 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1635 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1636 : diag::err_unknown_typename))
1637 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001638 protocols.clear();
1639 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001640 return;
1641 }
1642
1643 // If all of the names were (corrected to) protocols, these were
1644 // protocol qualifiers.
1645 if (numProtocolsResolved == identifiers.size())
1646 return resolvedAsProtocols();
1647
1648 // Otherwise, all of the names were (corrected to) types.
1649 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1650 return resolvedAsTypeDecls();
1651}
1652
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001653/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001654/// a class method in its extension.
1655///
Mike Stump11289f42009-09-09 15:08:12 +00001656void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001657 ObjCInterfaceDecl *ID) {
1658 if (!ID)
1659 return; // Possibly due to previous error
1660
1661 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001662 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001663 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001664
1665 if (MethodMap.empty())
1666 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001667 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001668 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001669 if (PrevMethod &&
1670 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1671 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001672 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1673 << Method->getDeclName();
1674 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1675 }
1676 }
1677}
1678
James Dennett634962f2012-06-14 21:40:34 +00001679/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001680Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001681Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001682 const IdentifierLocPair *IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001683 unsigned NumElts,
1684 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001685 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001686 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattnerd7352d62008-07-21 22:17:28 +00001687 IdentifierInfo *Ident = IdentList[i].first;
Douglas Gregor32c17572012-01-01 20:30:41 +00001688 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
1689 ForRedeclaration);
1690 ObjCProtocolDecl *PDecl
1691 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1692 IdentList[i].second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001693 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001694
1695 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001696 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001697
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001698 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001699 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001700
1701 if (PrevDecl)
1702 mergeDeclAttributes(PDecl, PrevDecl);
1703
Douglas Gregorf6102672012-01-01 21:23:57 +00001704 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Rafael Espindolaab417692013-07-09 12:05:01 +00001707 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001708}
1709
John McCall48871652010-08-21 09:40:31 +00001710Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001711ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1712 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001713 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001714 IdentifierInfo *CategoryName,
1715 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001716 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001717 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001718 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001719 SourceLocation EndProtoLoc) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001720 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001721 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001722
1723 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001724
1725 if (!IDecl
1726 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001727 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001728 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001729 // Create an invalid ObjCCategoryDecl to serve as context for
1730 // the enclosing method declarations. We mark the decl invalid
1731 // to make it clear that this isn't a valid AST.
1732 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001733 ClassLoc, CategoryLoc, CategoryName,
1734 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001735 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001736 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001737
1738 if (!IDecl)
1739 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001740 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001741 }
1742
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001743 if (!CategoryName && IDecl->getImplementation()) {
1744 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1745 Diag(IDecl->getImplementation()->getLocation(),
1746 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001747 }
1748
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001749 if (CategoryName) {
1750 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001751 if (ObjCCategoryDecl *Previous
1752 = IDecl->FindCategoryDeclaration(CategoryName)) {
1753 // Class extensions can be declared multiple times, categories cannot.
1754 Diag(CategoryLoc, diag::warn_dup_category_def)
1755 << ClassName << CategoryName;
1756 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001757 }
1758 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001759
Douglas Gregor85f3f952015-07-07 03:57:15 +00001760 // If we have a type parameter list, check it.
1761 if (typeParamList) {
1762 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1763 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1764 CategoryName
1765 ? TypeParamListContext::Category
1766 : TypeParamListContext::Extension))
1767 typeParamList = nullptr;
1768 } else {
1769 Diag(typeParamList->getLAngleLoc(),
1770 diag::err_objc_parameterized_category_nonclass)
1771 << (CategoryName != nullptr)
1772 << ClassName
1773 << typeParamList->getSourceRange();
1774
1775 typeParamList = nullptr;
1776 }
1777 }
1778
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001779 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001780 ClassLoc, CategoryLoc, CategoryName, IDecl,
1781 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001782 // FIXME: PushOnScopeChains?
1783 CurContext->addDecl(CDecl);
1784
Chris Lattnerda463fe2007-12-12 07:09:47 +00001785 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001786 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1787 NumProtoRefs, ProtoLocs);
1788 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001789 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001790 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001791 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001792 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001793 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001794 }
Mike Stump11289f42009-09-09 15:08:12 +00001795
Anders Carlssona6b508a2008-11-04 16:57:32 +00001796 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001797 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001798}
1799
1800/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001801/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001802/// object.
John McCall48871652010-08-21 09:40:31 +00001803Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001804 SourceLocation AtCatImplLoc,
1805 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1806 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001807 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001808 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001809 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001810 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1811 if (!CatIDecl) {
1812 // Category @implementation with no corresponding @interface.
1813 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001814 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1815 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001816 CatName, IDecl,
1817 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001818 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001819 }
1820 }
1821
Mike Stump11289f42009-09-09 15:08:12 +00001822 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001823 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001824 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001825 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001826 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001827 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001828 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001829 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1830 diag::err_undef_interface)) {
1831 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001832 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001833
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001834 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001835 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001836
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +00001837 // If the interface is deprecated/unavailable, warn/error about it.
1838 if (IDecl)
1839 DiagnoseUseOfDecl(IDecl, ClassLoc);
1840
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001841 /// Check that CatName, category name, is not used in another implementation.
1842 if (CatIDecl) {
1843 if (CatIDecl->getImplementation()) {
1844 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1845 << CatName;
1846 Diag(CatIDecl->getImplementation()->getLocation(),
1847 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001848 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001849 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001850 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001851 // Warn on implementating category of deprecated class under
1852 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001853 DiagnoseObjCImplementedDeprecations(*this,
1854 dyn_cast<NamedDecl>(IDecl),
1855 CDecl->getLocation(), 2);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001856 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001857 }
Mike Stump11289f42009-09-09 15:08:12 +00001858
Anders Carlssona6b508a2008-11-04 16:57:32 +00001859 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001860 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001861}
1862
John McCall48871652010-08-21 09:40:31 +00001863Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001864 SourceLocation AtClassImplLoc,
1865 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001866 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001867 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001868 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001869 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001870 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001871 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1872 ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001873 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001874 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001875 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001876 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001877 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1878 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001879 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001880 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001881 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001882 TypoCorrection Corrected = CorrectTypo(
1883 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1884 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001885 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1886 // Suggest the (potentially) correct interface name. Don't provide a
1887 // code-modification hint or use the typo name for recovery, because
1888 // this is just a warning. The program may actually be correct.
1889 diagnoseTypo(Corrected,
1890 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1891 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001892 } else {
1893 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1894 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001895 }
Mike Stump11289f42009-09-09 15:08:12 +00001896
Chris Lattnerda463fe2007-12-12 07:09:47 +00001897 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001898 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001899 if (SuperClassname) {
1900 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001901 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1902 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001903 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001904 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1905 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001906 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001907 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001908 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001909 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001910 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001911 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001912 Diag(SuperClassLoc, diag::err_undef_superclass)
1913 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001914 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001915 // This implementation and its interface do not have the same
1916 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001917 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001918 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001919 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001920 }
1921 }
1922 }
Mike Stump11289f42009-09-09 15:08:12 +00001923
Chris Lattnerda463fe2007-12-12 07:09:47 +00001924 if (!IDecl) {
1925 // Legacy case of @implementation with no corresponding @interface.
1926 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001927
Mike Stump87c57ac2009-05-16 07:39:55 +00001928 // FIXME: Do we support attributes on the @implementation? If so we should
1929 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001930 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001931 ClassName, /*typeParamList=*/nullptr,
1932 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001933 true);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001934 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00001935 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001936 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1937 Context.getObjCInterfaceType(SDecl),
1938 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00001939 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1940 } else {
1941 IDecl->setEndOfDefinitionLoc(ClassLoc);
1942 }
1943
Douglas Gregorac345a32009-04-24 00:16:12 +00001944 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00001945 } else {
1946 // Mark the interface as being completed, even if it was just as
1947 // @class ....;
1948 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001949 if (!IDecl->hasDefinition())
1950 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001951 }
Mike Stump11289f42009-09-09 15:08:12 +00001952
1953 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001954 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00001955 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001956
Anders Carlssona6b508a2008-11-04 16:57:32 +00001957 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001958 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001959
Chris Lattnerda463fe2007-12-12 07:09:47 +00001960 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00001961 if (IDecl->getImplementation()) {
1962 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001963 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001964 Diag(IDecl->getImplementation()->getLocation(),
1965 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001966 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00001967 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001968 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00001969 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001970 // Warn on implementating deprecated class under
1971 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001972 DiagnoseObjCImplementedDeprecations(*this,
1973 dyn_cast<NamedDecl>(IDecl),
1974 IMPDecl->getLocation(), 1);
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001975 }
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001976 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001977}
1978
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001979Sema::DeclGroupPtrTy
1980Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1981 SmallVector<Decl *, 64> DeclsInGroup;
1982 DeclsInGroup.reserve(Decls.size() + 1);
1983
1984 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1985 Decl *Dcl = Decls[i];
1986 if (!Dcl)
1987 continue;
1988 if (Dcl->getDeclContext()->isFileContext())
1989 Dcl->setTopLevelDeclInObjCContainer();
1990 DeclsInGroup.push_back(Dcl);
1991 }
1992
1993 DeclsInGroup.push_back(ObjCImpDecl);
1994
Rafael Espindolaab417692013-07-09 12:05:01 +00001995 return BuildDeclaratorGroup(DeclsInGroup, false);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001996}
1997
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001998void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1999 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002000 SourceLocation RBrace) {
2001 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002002 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002003 if (!IDecl)
2004 return;
James Dennett634962f2012-06-14 21:40:34 +00002005 /// Check case of non-existing \@interface decl.
2006 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002007 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002008 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002009 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002010 // Add ivar's to class's DeclContext.
2011 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002012 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002013 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002014 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002015 }
2016
Chris Lattnerda463fe2007-12-12 07:09:47 +00002017 return;
2018 }
2019 // If implementation has empty ivar list, just return.
2020 if (numIvars == 0)
2021 return;
Mike Stump11289f42009-09-09 15:08:12 +00002022
Chris Lattnerda463fe2007-12-12 07:09:47 +00002023 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002024 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002025 if (ImpDecl->getSuperClass())
2026 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2027 for (unsigned i = 0; i < numIvars; i++) {
2028 ObjCIvarDecl* ImplIvar = ivars[i];
2029 if (const ObjCIvarDecl *ClsIvar =
2030 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2031 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2032 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2033 continue;
2034 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002035 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002036 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002037 if (const ObjCIvarDecl *ClsExtIvar =
2038 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2039 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2040 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2041 continue;
2042 }
2043 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002044 // Instance ivar to Implementation's DeclContext.
2045 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002046 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002047 ImpDecl->addDecl(ImplIvar);
2048 }
2049 return;
2050 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002051 // Check interface's Ivar list against those in the implementation.
2052 // names and types must match.
2053 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002054 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002055 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002056 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2057 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002058 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002059 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002060 assert (ImplIvar && "missing implementation ivar");
2061 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002062
Steve Naroff157599f2009-03-03 14:49:36 +00002063 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002064 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002065 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002066 << ImplIvar->getIdentifier()
2067 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002068 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002069 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2070 ImplIvar->getBitWidthValue(Context) !=
2071 ClsIvar->getBitWidthValue(Context)) {
2072 Diag(ImplIvar->getBitWidth()->getLocStart(),
2073 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2074 Diag(ClsIvar->getBitWidth()->getLocStart(),
2075 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002076 }
Steve Naroff157599f2009-03-03 14:49:36 +00002077 // Make sure the names are identical.
2078 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002079 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002080 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002081 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002082 }
2083 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002084 }
Mike Stump11289f42009-09-09 15:08:12 +00002085
Chris Lattner0f29d982007-12-12 18:11:49 +00002086 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002087 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002088 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002089 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002090}
2091
Ted Kremenekf87decd2013-12-13 05:58:44 +00002092static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2093 ObjCMethodDecl *method,
2094 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002095 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002096 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002097 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002098 switch (method->getAvailability()) {
2099 case AR_Available:
2100 case AR_Deprecated:
2101 break;
2102
2103 // Don't warn about unavailable or not-yet-introduced methods.
2104 case AR_NotYetIntroduced:
2105 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002106 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002107 }
2108
Ted Kremenek65d63572013-03-27 00:02:21 +00002109 // FIXME: For now ignore 'IncompleteImpl'.
2110 // Previously we grouped all unimplemented methods under a single
2111 // warning, but some users strongly voiced that they would prefer
2112 // separate warnings. We will give that approach a try, as that
2113 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002114 {
2115 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2116 B << method;
2117 if (NeededFor)
2118 B << NeededFor;
2119 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002120
2121 // Issue a note to the original declaration.
2122 SourceLocation MethodLoc = method->getLocStart();
2123 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002124 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002125}
2126
David Chisnallb62d15c2010-10-25 17:23:52 +00002127/// Determines if type B can be substituted for type A. Returns true if we can
2128/// guarantee that anything that the user will do to an object of type A can
2129/// also be done to an object of type B. This is trivially true if the two
2130/// types are the same, or if B is a subclass of A. It becomes more complex
2131/// in cases where protocols are involved.
2132///
2133/// Object types in Objective-C describe the minimum requirements for an
2134/// object, rather than providing a complete description of a type. For
2135/// example, if A is a subclass of B, then B* may refer to an instance of A.
2136/// The principle of substitutability means that we may use an instance of A
2137/// anywhere that we may use an instance of B - it will implement all of the
2138/// ivars of B and all of the methods of B.
2139///
2140/// This substitutability is important when type checking methods, because
2141/// the implementation may have stricter type definitions than the interface.
2142/// The interface specifies minimum requirements, but the implementation may
2143/// have more accurate ones. For example, a method may privately accept
2144/// instances of B, but only publish that it accepts instances of A. Any
2145/// object passed to it will be type checked against B, and so will implicitly
2146/// by a valid A*. Similarly, a method may return a subclass of the class that
2147/// it is declared as returning.
2148///
2149/// This is most important when considering subclassing. A method in a
2150/// subclass must accept any object as an argument that its superclass's
2151/// implementation accepts. It may, however, accept a more general type
2152/// without breaking substitutability (i.e. you can still use the subclass
2153/// anywhere that you can use the superclass, but not vice versa). The
2154/// converse requirement applies to return types: the return type for a
2155/// subclass method must be a valid object of the kind that the superclass
2156/// advertises, but it may be specified more accurately. This avoids the need
2157/// for explicit down-casting by callers.
2158///
2159/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002160static bool isObjCTypeSubstitutable(ASTContext &Context,
2161 const ObjCObjectPointerType *A,
2162 const ObjCObjectPointerType *B,
2163 bool rejectId) {
2164 // Reject a protocol-unqualified id.
2165 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002166
2167 // If B is a qualified id, then A must also be a qualified id and it must
2168 // implement all of the protocols in B. It may not be a qualified class.
2169 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2170 // stricter definition so it is not substitutable for id<A>.
2171 if (B->isObjCQualifiedIdType()) {
2172 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002173 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2174 QualType(B,0),
2175 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002176 }
2177
2178 /*
2179 // id is a special type that bypasses type checking completely. We want a
2180 // warning when it is used in one place but not another.
2181 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2182
2183
2184 // If B is a qualified id, then A must also be a qualified id (which it isn't
2185 // if we've got this far)
2186 if (B->isObjCQualifiedIdType()) return false;
2187 */
2188
2189 // Now we know that A and B are (potentially-qualified) class types. The
2190 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002191 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002192}
2193
John McCall071df462010-10-28 02:34:38 +00002194static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2195 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2196}
2197
Douglas Gregor813a0662015-06-19 18:14:38 +00002198/// Determine whether two set of Objective-C declaration qualifiers conflict.
2199static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2200 Decl::ObjCDeclQualifier y) {
2201 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2202 (y & ~Decl::OBJC_TQ_CSNullability);
2203}
2204
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002205static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002206 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002207 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002208 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002209 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002210 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002211 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002212 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2213 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002214 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002215 S.Diag(MethodImpl->getLocation(),
2216 (IsOverridingMode
2217 ? diag::warn_conflicting_overriding_ret_type_modifiers
2218 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002219 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002220 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002221 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002222 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002223 }
2224 else
2225 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002226 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002227 if (Warn && IsOverridingMode &&
2228 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2229 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2230 MethodDecl->getReturnType(),
2231 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002232 auto nullabilityMethodImpl =
2233 *MethodImpl->getReturnType()->getNullability(S.Context);
2234 auto nullabilityMethodDecl =
2235 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002236 S.Diag(MethodImpl->getLocation(),
2237 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002238 << DiagNullabilityKind(
2239 nullabilityMethodImpl,
2240 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2241 != 0))
2242 << DiagNullabilityKind(
2243 nullabilityMethodDecl,
2244 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2245 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002246 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2247 }
2248
Alp Toker314cc812014-01-25 16:55:45 +00002249 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2250 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002251 return true;
2252 if (!Warn)
2253 return false;
John McCall071df462010-10-28 02:34:38 +00002254
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002255 unsigned DiagID =
2256 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2257 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002258
2259 // Mismatches between ObjC pointers go into a different warning
2260 // category, and sometimes they're even completely whitelisted.
2261 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002262 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002263 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002264 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002265 // Allow non-matching return types as long as they don't violate
2266 // the principle of substitutability. Specifically, we permit
2267 // return types that are subclasses of the declared return type,
2268 // or that are more-qualified versions of the declared type.
2269 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002270 return false;
John McCall071df462010-10-28 02:34:38 +00002271
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002272 DiagID =
2273 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2274 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002275 }
2276 }
2277
2278 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002279 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2280 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002281 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002282 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2283 ? diag::note_previous_declaration
2284 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002285 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002286 return false;
John McCall071df462010-10-28 02:34:38 +00002287}
2288
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002289static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002290 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002291 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002292 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002293 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002294 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002295 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002296 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002297 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002298 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2299 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002300 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002301 if (IsOverridingMode)
2302 S.Diag(ImplVar->getLocation(),
2303 diag::warn_conflicting_overriding_param_modifiers)
2304 << getTypeRange(ImplVar->getTypeSourceInfo())
2305 << MethodImpl->getDeclName();
2306 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002307 diag::warn_conflicting_param_modifiers)
2308 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002309 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002310 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2311 << getTypeRange(IfaceVar->getTypeSourceInfo());
2312 }
2313 else
2314 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002315 }
2316
John McCall071df462010-10-28 02:34:38 +00002317 QualType ImplTy = ImplVar->getType();
2318 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002319 if (Warn && IsOverridingMode &&
2320 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2321 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002322 S.Diag(ImplVar->getLocation(),
2323 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002324 << DiagNullabilityKind(
2325 *ImplTy->getNullability(S.Context),
2326 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2327 != 0))
2328 << DiagNullabilityKind(
2329 *IfaceTy->getNullability(S.Context),
2330 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2331 != 0));
2332 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002333 }
John McCall071df462010-10-28 02:34:38 +00002334 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002335 return true;
2336
2337 if (!Warn)
2338 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002339 unsigned DiagID =
2340 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2341 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002342
2343 // Mismatches between ObjC pointers go into a different warning
2344 // category, and sometimes they're even completely whitelisted.
2345 if (const ObjCObjectPointerType *ImplPtrTy =
2346 ImplTy->getAs<ObjCObjectPointerType>()) {
2347 if (const ObjCObjectPointerType *IfacePtrTy =
2348 IfaceTy->getAs<ObjCObjectPointerType>()) {
2349 // Allow non-matching argument types as long as they don't
2350 // violate the principle of substitutability. Specifically, the
2351 // implementation must accept any objects that the superclass
2352 // accepts, however it may also accept others.
2353 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002354 return false;
John McCall071df462010-10-28 02:34:38 +00002355
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002356 DiagID =
2357 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2358 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002359 }
2360 }
2361
2362 S.Diag(ImplVar->getLocation(), DiagID)
2363 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002364 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2365 S.Diag(IfaceVar->getLocation(),
2366 (IsOverridingMode ? diag::note_previous_declaration
2367 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002368 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002369 return false;
John McCall071df462010-10-28 02:34:38 +00002370}
John McCall31168b02011-06-15 23:02:42 +00002371
2372/// In ARC, check whether the conventional meanings of the two methods
2373/// match. If they don't, it's a hard error.
2374static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2375 ObjCMethodDecl *decl) {
2376 ObjCMethodFamily implFamily = impl->getMethodFamily();
2377 ObjCMethodFamily declFamily = decl->getMethodFamily();
2378 if (implFamily == declFamily) return false;
2379
2380 // Since conventions are sorted by selector, the only possibility is
2381 // that the types differ enough to cause one selector or the other
2382 // to fall out of the family.
2383 assert(implFamily == OMF_None || declFamily == OMF_None);
2384
2385 // No further diagnostics required on invalid declarations.
2386 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2387
2388 const ObjCMethodDecl *unmatched = impl;
2389 ObjCMethodFamily family = declFamily;
2390 unsigned errorID = diag::err_arc_lost_method_convention;
2391 unsigned noteID = diag::note_arc_lost_method_convention;
2392 if (declFamily == OMF_None) {
2393 unmatched = decl;
2394 family = implFamily;
2395 errorID = diag::err_arc_gained_method_convention;
2396 noteID = diag::note_arc_gained_method_convention;
2397 }
2398
2399 // Indexes into a %select clause in the diagnostic.
2400 enum FamilySelector {
2401 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2402 };
2403 FamilySelector familySelector = FamilySelector();
2404
2405 switch (family) {
2406 case OMF_None: llvm_unreachable("logic error, no method convention");
2407 case OMF_retain:
2408 case OMF_release:
2409 case OMF_autorelease:
2410 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002411 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002412 case OMF_retainCount:
2413 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002414 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002415 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002416 // Mismatches for these methods don't change ownership
2417 // conventions, so we don't care.
2418 return false;
2419
2420 case OMF_init: familySelector = F_init; break;
2421 case OMF_alloc: familySelector = F_alloc; break;
2422 case OMF_copy: familySelector = F_copy; break;
2423 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2424 case OMF_new: familySelector = F_new; break;
2425 }
2426
2427 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2428 ReasonSelector reasonSelector;
2429
2430 // The only reason these methods don't fall within their families is
2431 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002432 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002433 reasonSelector = R_UnrelatedReturn;
2434 } else {
2435 reasonSelector = R_NonObjectReturn;
2436 }
2437
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002438 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2439 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002440
2441 return true;
2442}
John McCall071df462010-10-28 02:34:38 +00002443
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002444void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002445 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002446 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002447 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002448 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2449 return;
2450
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002451 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002452 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002453 true);
Mike Stump11289f42009-09-09 15:08:12 +00002454
Chris Lattner67f35b02009-04-11 19:58:42 +00002455 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002456 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2457 EF = MethodDecl->param_end();
2458 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002459 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002460 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002461 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002462
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002463 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002464 Diag(ImpMethodDecl->getLocation(),
2465 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002466 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002467 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002468}
2469
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002470void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2471 ObjCMethodDecl *Overridden,
2472 bool IsProtocolMethodDecl) {
2473
2474 CheckMethodOverrideReturn(*this, Method, Overridden,
2475 IsProtocolMethodDecl, true,
2476 true);
2477
2478 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002479 IF = Overridden->param_begin(), EM = Method->param_end(),
2480 EF = Overridden->param_end();
2481 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002482 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2483 IsProtocolMethodDecl, true, true);
2484 }
2485
2486 if (Method->isVariadic() != Overridden->isVariadic()) {
2487 Diag(Method->getLocation(),
2488 diag::warn_conflicting_overriding_variadic);
2489 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2490 }
2491}
2492
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002493/// WarnExactTypedMethods - This routine issues a warning if method
2494/// implementation declaration matches exactly that of its declaration.
2495void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2496 ObjCMethodDecl *MethodDecl,
2497 bool IsProtocolMethodDecl) {
2498 // don't issue warning when protocol method is optional because primary
2499 // class is not required to implement it and it is safe for protocol
2500 // to implement it.
2501 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2502 return;
2503 // don't issue warning when primary class's method is
2504 // depecated/unavailable.
2505 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2506 MethodDecl->hasAttr<DeprecatedAttr>())
2507 return;
2508
2509 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2510 IsProtocolMethodDecl, false, false);
2511 if (match)
2512 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002513 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2514 EF = MethodDecl->param_end();
2515 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002516 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2517 *IM, *IF,
2518 IsProtocolMethodDecl, false, false);
2519 if (!match)
2520 break;
2521 }
2522 if (match)
2523 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002524 if (match)
2525 match = !(MethodDecl->isClassMethod() &&
2526 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002527
2528 if (match) {
2529 Diag(ImpMethodDecl->getLocation(),
2530 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002531 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2532 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002533 }
2534}
2535
Mike Stump87c57ac2009-05-16 07:39:55 +00002536/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2537/// improve the efficiency of selector lookups and type checking by associating
2538/// with each protocol / interface / category the flattened instance tables. If
2539/// we used an immutable set to keep the table then it wouldn't add significant
2540/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002541
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002542typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002543typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002544
2545static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2546 ProtocolNameSet &PNS) {
2547 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2548 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002549 for (const auto *PI : PDecl->protocols())
2550 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002551}
2552
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002553/// Recursively populates a set with all conformed protocols in a class
2554/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2555/// attribute.
2556static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2557 ProtocolNameSet &PNS) {
2558 if (!Super)
2559 return;
2560
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002561 for (const auto *I : Super->all_referenced_protocols())
2562 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002563
2564 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002565}
2566
Steve Naroffa36992242008-02-08 22:06:17 +00002567/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002568/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002569static void CheckProtocolMethodDefs(Sema &S,
2570 SourceLocation ImpLoc,
2571 ObjCProtocolDecl *PDecl,
2572 bool& IncompleteImpl,
2573 const Sema::SelectorSet &InsMap,
2574 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002575 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002576 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002577 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2578 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2579 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002580 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2581
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002582 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002583 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002584
2585 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2586 // then we should check if any class in the super class hierarchy also
2587 // conforms to this protocol, either directly or via protocol inheritance.
2588 // If so, we can skip checking this protocol completely because we
2589 // know that a parent class already satisfies this protocol.
2590 //
2591 // Note: we could generalize this logic for all protocols, and merely
2592 // add the limit on looking at the super class chain for just
2593 // specially marked protocols. This may be a good optimization. This
2594 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2595 // protocols for now for controlled evaluation.
2596 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002597 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002598 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2599 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2600 }
2601 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2602 ProtocolsExplictImpl->end())
2603 return;
2604
2605 // If no super class conforms to the protocol, we should not search
2606 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002607 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002608 }
2609
Ted Kremenek285ee852013-12-13 06:26:10 +00002610 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002611 // check to see if class implements forwardInvocation method and objects
2612 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002613 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002614 // Under such conditions, which means that every method possible is
2615 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002616 // found" warnings.
2617 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002618 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2619 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002620 if (InsMap.count(fISelector))
2621 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2622 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002623 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002624 }
Mike Stump11289f42009-09-09 15:08:12 +00002625
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002626 // If this is a forward protocol declaration, get its definition.
2627 if (!PDecl->isThisDeclarationADefinition() &&
2628 PDecl->getDefinition())
2629 PDecl = PDecl->getDefinition();
2630
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002631 // If a method lookup fails locally we still need to look and see if
2632 // the method was implemented by a base class or an inherited
2633 // protocol. This lookup is slow, but occurs rarely in correct code
2634 // and otherwise would terminate in a warning.
2635
Chris Lattnerda463fe2007-12-12 07:09:47 +00002636 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002637 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002638 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002639 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002640 !method->isPropertyAccessor() &&
2641 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002642 (!Super || !Super->lookupMethod(method->getSelector(),
2643 true /* instance */,
2644 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002645 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002646 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002647 // If a method is not implemented in the category implementation but
2648 // has been declared in its primary class, superclass,
2649 // or in one of their protocols, no need to issue the warning.
2650 // This is because method will be implemented in the primary class
2651 // or one of its super class implementation.
2652
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002653 // Ugly, but necessary. Method declared in protcol might have
2654 // have been synthesized due to a property declared in the class which
2655 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002656 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002657 IDecl->lookupMethod(method->getSelector(),
2658 true /* instance */,
2659 true /* shallowCategoryLookup */,
2660 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002661 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002662 continue;
2663 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002664 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002665 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002666 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002667 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002668 }
2669 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002670 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002671 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002672 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2673 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002674 (!Super || !Super->lookupMethod(method->getSelector(),
2675 false /* class method */,
2676 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002677 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002678 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002679 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002680 if (C && IDecl->lookupMethod(method->getSelector(),
2681 false /* class */,
2682 true /* shallowCategoryLookup */,
2683 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002684 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002685
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002686 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002687 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002688 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002689 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002690 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002691 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002692 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002693 for (auto *PI : PDecl->protocols())
2694 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002695 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002696}
2697
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002698/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002699/// or protocol against those declared in their implementations.
2700///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002701void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2702 const SelectorSet &ClsMap,
2703 SelectorSet &InsMapSeen,
2704 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002705 ObjCImplDecl* IMPDecl,
2706 ObjCContainerDecl* CDecl,
2707 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002708 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002709 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002710 // Check and see if instance methods in class interface have been
2711 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002712 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002713 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002714 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002715 if (!I->isPropertyAccessor() &&
2716 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002717 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002718 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002719 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002720 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002721 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002722 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002723 IMPDecl->getInstanceMethod(I->getSelector());
2724 assert(CDecl->getInstanceMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002725 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002726 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002727 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002728 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002729 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002730 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002731 else if (!I->isPropertyAccessor())
2732 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002733 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002734 }
2735 }
Mike Stump11289f42009-09-09 15:08:12 +00002736
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002737 // Check and see if class methods in class interface have been
2738 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002739 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002740 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002741 continue;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002742 if (!ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002743 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002744 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002745 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002746 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002747 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002748 IMPDecl->getClassMethod(I->getSelector());
2749 assert(CDecl->getClassMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002750 "Expected to find the method through lookup as well");
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002751 if (!WarnCategoryMethodImpl)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002752 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002753 isa<ObjCProtocolDecl>(CDecl));
2754 else
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002755 WarnExactTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002756 isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002757 }
2758 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002759
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002760 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2761 // Also, check for methods declared in protocols inherited by
2762 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002763 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002764 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002765 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002766 WarnCategoryMethodImpl);
2767 }
2768
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002769 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002770 // when checking that methods in implementation match their declaration,
2771 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2772 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002773 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002774 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002775 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002776 IMPDecl, Cat, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002777 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002778 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002779 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002780 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002781 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002782 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002783 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002784 }
2785
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002786 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002787 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002788 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002789 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002790 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002791
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002792 // FIXME. For now, we are not checking for extact match of methods
2793 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002794 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002795 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002796 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002797 I->getSuperClass(), IncompleteImpl, false);
2798 }
2799}
2800
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002801/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2802/// category matches with those implemented in its primary class and
2803/// warns each time an exact match is found.
2804void Sema::CheckCategoryVsClassMethodMatches(
2805 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002806 // Get category's primary class.
2807 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2808 if (!CatDecl)
2809 return;
2810 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2811 if (!IDecl)
2812 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002813 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2814 SelectorSet InsMap, ClsMap;
2815
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002816 for (const auto *I : CatIMPDecl->instance_methods()) {
2817 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002818 // When checking for methods implemented in the category, skip over
2819 // those declared in category class's super class. This is because
2820 // the super class must implement the method.
2821 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2822 continue;
2823 InsMap.insert(Sel);
2824 }
2825
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002826 for (const auto *I : CatIMPDecl->class_methods()) {
2827 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002828 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2829 continue;
2830 ClsMap.insert(Sel);
2831 }
2832 if (InsMap.empty() && ClsMap.empty())
2833 return;
2834
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002835 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002836 bool IncompleteImpl = false;
2837 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2838 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002839 IncompleteImpl, false,
2840 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002841}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002842
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002843void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002844 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002845 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002846 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002847 // Check and see if instance methods in class interface have been
2848 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002849 for (const auto *I : IMPDecl->instance_methods())
2850 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002851
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002852 // Check and see if properties declared in the interface have either 1)
2853 // an implementation or 2) there is a @synthesize/@dynamic implementation
2854 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002855 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2856 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2857 LangOpts.ObjCRuntime.isNonFragile() &&
2858 !IDecl->isObjCRequiresPropertyDefs();
2859 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2860 }
2861
Douglas Gregor849ebc22015-06-19 18:14:46 +00002862 // Diagnose null-resettable synthesized setters.
2863 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2864
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002865 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002866 for (const auto *I : IMPDecl->class_methods())
2867 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002868
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002869 // Check for type conflict of methods declared in a class/protocol and
2870 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002871 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002872 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2873 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002874 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002875
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002876 // check all methods implemented in category against those declared
2877 // in its primary class.
2878 if (ObjCCategoryImplDecl *CatDecl =
2879 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2880 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002881
Chris Lattnerda463fe2007-12-12 07:09:47 +00002882 // Check the protocol list for unimplemented methods in the @implementation
2883 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002884 // Check and see if class methods in class interface have been
2885 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002886
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002887 LazyProtocolNameSet ExplicitImplProtocols;
2888
Chris Lattner9ef10f42009-03-01 00:56:52 +00002889 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002890 for (auto *PI : I->all_referenced_protocols())
2891 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2892 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002893 // Check class extensions (unnamed categories)
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002894 for (auto *Ext : I->visible_extensions())
2895 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002896 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002897 // For extended class, unimplemented methods in its protocols will
2898 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002899 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002900 for (auto *P : C->protocols())
2901 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002902 IncompleteImpl, InsMap, ClsMap, CDecl,
2903 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002904 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00002905 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002906 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002907 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002908 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002909}
2910
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002911Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00002912Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00002913 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00002914 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002915 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00002916 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002917 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002918 for (unsigned i = 0; i != NumElts; ++i) {
2919 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002920 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002921 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Douglas Gregorb8eaf292010-04-15 23:40:53 +00002922 LookupOrdinaryName, ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002923 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00002924 // GCC apparently allows the following idiom:
2925 //
2926 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2927 // @class XCElementToggler;
2928 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002929 // Here we have chosen to ignore the forward class declaration
2930 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00002931 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00002932 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002933 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00002934 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00002935 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00002936 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002937 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00002938 // as this will force the intended behavior which is to lookup the
2939 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002940 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00002941 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2942 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002943 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2944 continue;
2945 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00002946 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002947 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00002948
2949 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002950 ObjCInterfaceDecl *PrevIDecl
2951 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00002952
2953 IdentifierInfo *ClassName = IdentList[i];
2954 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2955 // A previous decl with a different name is because of
2956 // @compatibility_alias, for example:
2957 // \code
2958 // @class NewImage;
2959 // @compatibility_alias OldImage NewImage;
2960 // \endcode
2961 // A lookup for 'OldImage' will return the 'NewImage' decl.
2962 //
2963 // In such a case use the real declaration name, instead of the alias one,
2964 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2965 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2966 // has been aliased.
2967 ClassName = PrevIDecl->getIdentifier();
2968 }
2969
Douglas Gregor85f3f952015-07-07 03:57:15 +00002970 // If this forward declaration has type parameters, compare them with the
2971 // type parameters of the previous declaration.
2972 ObjCTypeParamList *TypeParams = TypeParamLists[i];
2973 if (PrevIDecl && TypeParams) {
2974 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
2975 // Check for consistency with the previous declaration.
2976 if (checkTypeParamListConsistency(
2977 *this, PrevTypeParams, TypeParams,
2978 TypeParamListContext::ForwardDeclaration)) {
2979 TypeParams = nullptr;
2980 }
2981 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
2982 // The @interface does not have type parameters. Complain.
2983 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
2984 << ClassName
2985 << TypeParams->getSourceRange();
2986 Diag(Def->getLocation(), diag::note_defined_here)
2987 << ClassName;
2988
2989 TypeParams = nullptr;
2990 }
2991 }
2992
Douglas Gregordc9166c2011-12-15 20:29:51 +00002993 ObjCInterfaceDecl *IDecl
2994 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002995 ClassName, TypeParams, PrevIDecl,
2996 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00002997 IDecl->setAtEndRange(IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00002998
Douglas Gregordc9166c2011-12-15 20:29:51 +00002999 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003000 CheckObjCDeclScope(IDecl);
3001 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003002 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003003
3004 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003005}
3006
John McCall54507ab2011-06-16 01:15:19 +00003007static bool tryMatchRecordTypes(ASTContext &Context,
3008 Sema::MethodMatchStrategy strategy,
3009 const Type *left, const Type *right);
3010
John McCall31168b02011-06-15 23:02:42 +00003011static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3012 QualType leftQT, QualType rightQT) {
3013 const Type *left =
3014 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3015 const Type *right =
3016 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3017
3018 if (left == right) return true;
3019
3020 // If we're doing a strict match, the types have to match exactly.
3021 if (strategy == Sema::MMS_strict) return false;
3022
3023 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3024
3025 // Otherwise, use this absurdly complicated algorithm to try to
3026 // validate the basic, low-level compatibility of the two types.
3027
3028 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003029 TypeInfo LeftTI = Context.getTypeInfo(left);
3030 TypeInfo RightTI = Context.getTypeInfo(right);
3031 if (LeftTI.Width != RightTI.Width)
3032 return false;
3033
3034 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003035 return false;
3036
3037 // Consider all the kinds of non-dependent canonical types:
3038 // - functions and arrays aren't possible as return and parameter types
3039
3040 // - vector types of equal size can be arbitrarily mixed
3041 if (isa<VectorType>(left)) return isa<VectorType>(right);
3042 if (isa<VectorType>(right)) return false;
3043
3044 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003045 // - structs, unions, and Objective-C objects must match more-or-less
3046 // exactly
John McCall31168b02011-06-15 23:02:42 +00003047 // - everything else should be a scalar
3048 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003049 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003050
John McCall9320b872011-09-09 05:25:32 +00003051 // Make scalars agree in kind, except count bools as chars, and group
3052 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003053 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3054 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3055 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3056 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003057 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3058 leftSK = Type::STK_ObjCObjectPointer;
3059 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3060 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003061
3062 // Note that data member pointers and function member pointers don't
3063 // intermix because of the size differences.
3064
3065 return (leftSK == rightSK);
3066}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003067
John McCall54507ab2011-06-16 01:15:19 +00003068static bool tryMatchRecordTypes(ASTContext &Context,
3069 Sema::MethodMatchStrategy strategy,
3070 const Type *lt, const Type *rt) {
3071 assert(lt && rt && lt != rt);
3072
3073 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3074 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3075 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3076
3077 // Require union-hood to match.
3078 if (left->isUnion() != right->isUnion()) return false;
3079
3080 // Require an exact match if either is non-POD.
3081 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3082 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3083 return false;
3084
3085 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003086 TypeInfo LeftTI = Context.getTypeInfo(lt);
3087 TypeInfo RightTI = Context.getTypeInfo(rt);
3088 if (LeftTI.Width != RightTI.Width)
3089 return false;
3090
3091 if (LeftTI.Align != RightTI.Align)
3092 return false;
John McCall54507ab2011-06-16 01:15:19 +00003093
3094 // Require fields to match.
3095 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3096 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3097 for (; li != le && ri != re; ++li, ++ri) {
3098 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3099 return false;
3100 }
3101 return (li == le && ri == re);
3102}
3103
Chris Lattnerda463fe2007-12-12 07:09:47 +00003104/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3105/// returns true, or false, accordingly.
3106/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003107bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3108 const ObjCMethodDecl *right,
3109 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003110 if (!matchTypes(Context, strategy, left->getReturnType(),
3111 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003112 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003113
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003114 // If either is hidden, it is not considered to match.
3115 if (left->isHidden() || right->isHidden())
3116 return false;
3117
David Blaikiebbafb8a2012-03-11 07:00:24 +00003118 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003119 (left->hasAttr<NSReturnsRetainedAttr>()
3120 != right->hasAttr<NSReturnsRetainedAttr>() ||
3121 left->hasAttr<NSConsumesSelfAttr>()
3122 != right->hasAttr<NSConsumesSelfAttr>()))
3123 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003124
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003125 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003126 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3127 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003128
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003129 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003130 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003131 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003132
3133 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3134 return false;
3135
David Blaikiebbafb8a2012-03-11 07:00:24 +00003136 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003137 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3138 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003139 }
3140 return true;
3141}
3142
Nico Weber2e0c8f72014-12-27 03:58:08 +00003143void Sema::addMethodToGlobalList(ObjCMethodList *List,
3144 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003145 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3146 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003147 if (ObjCCategoryDecl *CD =
3148 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003149 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003150 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003151
Douglas Gregorc454afe2012-01-25 00:19:56 +00003152 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003153 if (List->getMethod() == nullptr) {
3154 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003155 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003156 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003157 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003158
Douglas Gregorc454afe2012-01-25 00:19:56 +00003159 // We've seen a method with this name, see if we have already seen this type
3160 // signature.
3161 ObjCMethodList *Previous = List;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003162 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003163 // If we are building a module, keep all of the methods.
3164 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
3165 continue;
3166
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003167 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) {
3168 // Even if two method types do not match, we would like to say
3169 // there is more than one declaration so unavailability/deprecated
3170 // warning is not too noisy.
3171 if (!Method->isDefined())
3172 List->setHasMoreThanOneDecl(true);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003173 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003174 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003175
3176 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003177
3178 // Propagate the 'defined' bit.
3179 if (Method->isDefined())
3180 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003181 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003182 // Objective-C doesn't allow an @interface for a class after its
3183 // @implementation. So if Method is not defined and there already is
3184 // an entry for this type signature, Method has to be for a different
3185 // class than PrevObjCMethod.
3186 List->setHasMoreThanOneDecl(true);
3187 }
3188
Douglas Gregorc454afe2012-01-25 00:19:56 +00003189 // If a method is deprecated, push it in the global pool.
3190 // This is used for better diagnostics.
3191 if (Method->isDeprecated()) {
3192 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003193 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003194 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003195 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003196 // unless previous one is deprecated.
3197 if (Method->isUnavailable()) {
3198 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
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
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003202 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003203 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003204
Douglas Gregorc454afe2012-01-25 00:19:56 +00003205 // We have a new signature for an existing method - add it.
3206 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003207 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Nico Weber2e0c8f72014-12-27 03:58:08 +00003208 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003209}
3210
Sebastian Redl75d8a322010-08-02 23:18:59 +00003211/// \brief Read the contents of the method pool for a given selector from
3212/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003213void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003214 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003215 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003216}
3217
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003218void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003219 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003220 // Ignore methods of invalid containers.
3221 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003222 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003223
Douglas Gregor70f449b2012-01-25 00:59:09 +00003224 if (ExternalSource)
3225 ReadMethodPool(Method->getSelector());
3226
Sebastian Redl75d8a322010-08-02 23:18:59 +00003227 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003228 if (Pos == MethodPool.end())
3229 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3230 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003231
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003232 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003233
Sebastian Redl75d8a322010-08-02 23:18:59 +00003234 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003235 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003236}
3237
John McCall31168b02011-06-15 23:02:42 +00003238/// Determines if this is an "acceptable" loose mismatch in the global
3239/// method pool. This exists mostly as a hack to get around certain
3240/// global mismatches which we can't afford to make warnings / errors.
3241/// Really, what we want is a way to take a method out of the global
3242/// method pool.
3243static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3244 ObjCMethodDecl *other) {
3245 if (!chosen->isInstanceMethod())
3246 return false;
3247
3248 Selector sel = chosen->getSelector();
3249 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3250 return false;
3251
3252 // Don't complain about mismatches for -length if the method we
3253 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003254 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003255}
3256
Nico Weber2e0c8f72014-12-27 03:58:08 +00003257bool Sema::CollectMultipleMethodsInGlobalPool(
3258 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003259 if (ExternalSource)
3260 ReadMethodPool(Sel);
3261
3262 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3263 if (Pos == MethodPool.end())
3264 return false;
3265 // Gather the non-hidden methods.
3266 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3267 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003268 if (M->getMethod() && !M->getMethod()->isHidden())
3269 Methods.push_back(M->getMethod());
3270 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003271}
3272
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003273bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3274 SourceRange R,
3275 bool receiverIdOrClass) {
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003276 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003277 // Test for no method in the pool which should not trigger any warning by
3278 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003279 if (Pos == MethodPool.end())
3280 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003281 ObjCMethodList &MethList =
3282 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3283
3284 // Diagnose finding more than one method in global pool
3285 SmallVector<ObjCMethodDecl *, 4> Methods;
3286 Methods.push_back(BestMethod);
Jonathan Roelofs74411362015-04-28 18:04:44 +00003287 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext())
3288 if (ObjCMethodDecl *M = ML->getMethod())
3289 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>())
3290 Methods.push_back(M);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003291 if (Methods.size() > 1)
3292 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass);
3293
Nico Weber2e0c8f72014-12-27 03:58:08 +00003294 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003295}
3296
Sebastian Redl75d8a322010-08-02 23:18:59 +00003297ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003298 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003299 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003300 if (ExternalSource)
3301 ReadMethodPool(Sel);
3302
Sebastian Redl75d8a322010-08-02 23:18:59 +00003303 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003304 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003305 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003306
Douglas Gregor77f49a42013-01-16 18:47:38 +00003307 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003308 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003309 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003310 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003311 if (M->getMethod() && !M->getMethod()->isHidden())
3312 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003313 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003314 return nullptr;
3315}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003316
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003317void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3318 Selector Sel, SourceRange R,
3319 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003320 // We found multiple methods, so we may have to complain.
3321 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003322
Douglas Gregor77f49a42013-01-16 18:47:38 +00003323 // We support a warning which complains about *any* difference in
3324 // method signature.
3325 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003326 receiverIdOrClass &&
3327 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003328 if (strictSelectorMatch) {
3329 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3330 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3331 issueDiagnostic = true;
3332 break;
3333 }
3334 }
3335 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003336
Douglas Gregor77f49a42013-01-16 18:47:38 +00003337 // If we didn't see any strict differences, we won't see any loose
3338 // differences. In ARC, however, we also need to check for loose
3339 // mismatches, because most of them are errors.
3340 if (!strictSelectorMatch ||
3341 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3342 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3343 // This checks if the methods differ in type mismatch.
3344 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3345 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3346 issueDiagnostic = true;
3347 if (getLangOpts().ObjCAutoRefCount)
3348 issueError = true;
3349 break;
3350 }
3351 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003352
Douglas Gregor77f49a42013-01-16 18:47:38 +00003353 if (issueDiagnostic) {
3354 if (issueError)
3355 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3356 else if (strictSelectorMatch)
3357 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3358 else
3359 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003360
Douglas Gregor77f49a42013-01-16 18:47:38 +00003361 Diag(Methods[0]->getLocStart(),
3362 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003363 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003364 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3365 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003366 << Methods[I]->getSourceRange();
3367 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003368 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003369}
3370
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003371ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003372 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3373 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003374 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003375
3376 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003377 for (const ObjCMethodList *Method = &Methods.first; Method;
3378 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003379 if (Method->getMethod() &&
3380 (Method->getMethod()->isDefined() ||
3381 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003382 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003383
3384 for (const ObjCMethodList *Method = &Methods.second; Method;
3385 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003386 if (Method->getMethod() &&
3387 (Method->getMethod()->isDefined() ||
3388 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003389 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003390 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003391}
3392
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003393static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003394HelperSelectorsForTypoCorrection(
3395 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3396 StringRef Typo, const ObjCMethodDecl * Method) {
3397 const unsigned MaxEditDistance = 1;
3398 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003399 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003400
3401 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3402 if (MinPossibleEditDistance > 0 &&
3403 Typo.size() / MinPossibleEditDistance < 1)
3404 return;
3405 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3406 if (EditDistance > MaxEditDistance)
3407 return;
3408 if (EditDistance == BestEditDistance)
3409 BestMethod.push_back(Method);
3410 else if (EditDistance < BestEditDistance) {
3411 BestMethod.clear();
3412 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003413 }
3414}
3415
Fariborz Jahanian75481672013-06-17 17:10:54 +00003416static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3417 QualType ObjectType) {
3418 if (ObjectType.isNull())
3419 return true;
3420 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3421 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003422 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3423 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003424}
3425
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003426const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003427Sema::SelectorsForTypoCorrection(Selector Sel,
3428 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003429 unsigned NumArgs = Sel.getNumArgs();
3430 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003431 bool ObjectIsId = true, ObjectIsClass = true;
3432 if (ObjectType.isNull())
3433 ObjectIsId = ObjectIsClass = false;
3434 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003435 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003436 else if (const ObjCObjectPointerType *ObjCPtr =
3437 ObjectType->getAsObjCInterfacePointerType()) {
3438 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3439 ObjectIsId = ObjectIsClass = false;
3440 }
3441 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3442 ObjectIsClass = false;
3443 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3444 ObjectIsId = false;
3445 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003446 return nullptr;
3447
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003448 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3449 e = MethodPool.end(); b != e; b++) {
3450 // instance methods
3451 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003452 if (M->getMethod() &&
3453 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3454 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003455 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003456 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003457 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003458 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3459 ObjectType))
3460 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003461 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003462 // class methods
3463 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003464 if (M->getMethod() &&
3465 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3466 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003467 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003468 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003469 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003470 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3471 ObjectType))
3472 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003473 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003474 }
3475
3476 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3477 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3478 HelperSelectorsForTypoCorrection(SelectedMethods,
3479 Sel.getAsString(), Methods[i]);
3480 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003481 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003482}
3483
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003484/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003485/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003486/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003487/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003488/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003489void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3490 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003491 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003492 if (Ivar->isInvalidDecl())
3493 continue;
3494 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3495 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3496 if (prevIvar) {
3497 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3498 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3499 Ivar->setInvalidDecl();
3500 }
3501 }
3502 }
3503}
3504
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003505Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3506 switch (CurContext->getDeclKind()) {
3507 case Decl::ObjCInterface:
3508 return Sema::OCK_Interface;
3509 case Decl::ObjCProtocol:
3510 return Sema::OCK_Protocol;
3511 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003512 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003513 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003514 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003515 case Decl::ObjCImplementation:
3516 return Sema::OCK_Implementation;
3517 case Decl::ObjCCategoryImpl:
3518 return Sema::OCK_CategoryImplementation;
3519
3520 default:
3521 return Sema::OCK_None;
3522 }
3523}
3524
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003525// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003526Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003527 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003528 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003529 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003530
3531 assert(AtEnd.isValid() && "Invalid location for '@end'");
3532
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003533 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3534 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian9290ede2009-11-16 18:57:01 +00003535
Mike Stump11289f42009-09-09 15:08:12 +00003536 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003537 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3538 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003539 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003540
Steve Naroff35c62ae2009-01-08 17:28:14 +00003541 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3542 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3543 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3544
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003545 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003546 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003547 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003548
3549 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003550 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003551 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003552 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003553 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003554 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003555 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003556 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003557 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003558 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003559 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003560 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003561 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003562 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003563 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003564 if (!Context.getSourceManager().isInSystemHeader(
3565 Method->getLocation()))
3566 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3567 << Method->getDeclName();
3568 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3569 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003570 InsMap[Method->getSelector()] = Method;
3571 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003572 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003573 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003574 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003575 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003576 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003577 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003578 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003579 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003580 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003581 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003582 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003583 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003584 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003585 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003586 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003587 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003588 if (!Context.getSourceManager().isInSystemHeader(
3589 Method->getLocation()))
3590 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3591 << Method->getDeclName();
3592 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3593 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003594 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003595 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003596 }
3597 }
3598 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003599 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3600 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003601 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003602 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003603 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003604 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003605
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003606 if (C->IsClassExtension()) {
3607 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3608 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003609 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003610 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003611 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003612 if (CDecl->getIdentifier())
3613 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3614 // user-defined setter/getter. It also synthesizes setter/getter methods
3615 // and adds them to the DeclContext and global method pools.
Aaron Ballmand174edf2014-03-13 19:11:50 +00003616 for (auto *I : CDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00003617 ProcessPropertyDecl(I, CDecl);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003618 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003619 }
3620 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003621 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003622 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003623 // Any property declared in a class extension might have user
3624 // declared setter or getter in current class extension or one
3625 // of the other class extensions. Mark them as synthesized as
3626 // property will be synthesized when property with same name is
3627 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003628 for (const auto *Ext : IDecl->visible_extensions()) {
Aaron Ballmand174edf2014-03-13 19:11:50 +00003629 for (const auto *Property : Ext->properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003630 // Skip over properties declared @dynamic
3631 if (const ObjCPropertyImplDecl *PIDecl
3632 = IC->FindPropertyImplDecl(Property->getIdentifier()))
3633 if (PIDecl->getPropertyImplementation()
3634 == ObjCPropertyImplDecl::Dynamic)
3635 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003636
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003637 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003638 if (ObjCMethodDecl *GetterMethod
3639 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003640 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003641 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003642 if (ObjCMethodDecl *SetterMethod
3643 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003644 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003645 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003646 }
3647 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003648 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003649 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003650 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003651 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003652 if (IDecl->hasDesignatedInitializers())
3653 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003654
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003655 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00003656 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003657 // This class has no superclass, so check that it has been marked with
3658 // __attribute((objc_root_class)).
3659 if (!HasRootClassAttr) {
3660 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00003661 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003662 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3663 << IDecl->getIdentifier();
3664 // See if NSObject is in the current scope, and if it is, suggest
3665 // adding " : NSObject " to the class declaration.
3666 NamedDecl *IF = LookupSingleName(TUScope,
3667 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3668 DeclLoc, LookupOrdinaryName);
3669 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3670 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3671 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3672 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3673 } else {
3674 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3675 }
3676 }
3677 } else if (HasRootClassAttr) {
3678 // Complain that only root classes may have this attribute.
3679 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3680 }
3681
John McCall5fb5df92012-06-20 06:18:46 +00003682 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003683 while (IDecl->getSuperClass()) {
3684 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3685 IDecl = IDecl->getSuperClass();
3686 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003687 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003688 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003689 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00003690 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00003691 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003692 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003693
Chris Lattnerda463fe2007-12-12 07:09:47 +00003694 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00003695 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00003696 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003697 if (ObjCCategoryDecl *Cat
3698 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3699 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003700 }
3701 }
3702 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003703 if (isInterfaceDeclKind) {
3704 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003705 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003706 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003707 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3708 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003709 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00003710 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00003711 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003712 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003713 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00003714 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003715
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003716 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003717 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003718 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3719 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003720 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3721 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003722
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00003723 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003724 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003725}
3726
3727
3728/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3729/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00003730static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003731CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00003732 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003733}
3734
Douglas Gregor33823722011-06-11 01:09:30 +00003735/// \brief Check whether the declared result type of the given Objective-C
3736/// method declaration is compatible with the method's class.
3737///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003738static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00003739CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3740 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00003741 QualType ResultType = Method->getReturnType();
3742
Douglas Gregor33823722011-06-11 01:09:30 +00003743 // If an Objective-C method inherits its related result type, then its
3744 // declared result type must be compatible with its own class type. The
3745 // declared result type is compatible if:
3746 if (const ObjCObjectPointerType *ResultObjectType
3747 = ResultType->getAs<ObjCObjectPointerType>()) {
3748 // - it is id or qualified id, or
3749 if (ResultObjectType->isObjCIdType() ||
3750 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003751 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003752
3753 if (CurrentClass) {
3754 if (ObjCInterfaceDecl *ResultClass
3755 = ResultObjectType->getInterfaceDecl()) {
3756 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00003757 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003758 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003759
3760 // - it is a superclass of the method's class type
3761 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003762 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003763 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00003764 } else {
3765 // Any Objective-C pointer type might be acceptable for a protocol
3766 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003767 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00003768 }
3769 }
3770
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003771 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003772}
3773
John McCalld2930c22011-07-22 02:45:48 +00003774namespace {
3775/// A helper class for searching for methods which a particular method
3776/// overrides.
3777class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003778public:
John McCalld2930c22011-07-22 02:45:48 +00003779 Sema &S;
3780 ObjCMethodDecl *Method;
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003781 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00003782 bool Recursive;
3783
3784public:
3785 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
3786 Selector selector = method->getSelector();
3787
3788 // Bypass this search if we've never seen an instance/class method
3789 // with this selector before.
3790 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
3791 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00003792 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00003793 S.ReadMethodPool(selector);
3794
3795 it = S.MethodPool.find(selector);
3796 if (it == S.MethodPool.end())
3797 return;
John McCalld2930c22011-07-22 02:45:48 +00003798 }
3799 ObjCMethodList &list =
3800 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003801 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00003802
3803 ObjCContainerDecl *container
3804 = cast<ObjCContainerDecl>(method->getDeclContext());
3805
3806 // Prevent the search from reaching this container again. This is
3807 // important with categories, which override methods from the
3808 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003809 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
3810 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003811 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
3812 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003813 } else {
3814 searchFromContainer(container);
3815 }
Douglas Gregor33823722011-06-11 01:09:30 +00003816 }
John McCalld2930c22011-07-22 02:45:48 +00003817
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003818 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00003819 iterator begin() const { return Overridden.begin(); }
3820 iterator end() const { return Overridden.end(); }
3821
3822private:
3823 void searchFromContainer(ObjCContainerDecl *container) {
3824 if (container->isInvalidDecl()) return;
3825
3826 switch (container->getDeclKind()) {
3827#define OBJCCONTAINER(type, base) \
3828 case Decl::type: \
3829 searchFrom(cast<type##Decl>(container)); \
3830 break;
3831#define ABSTRACT_DECL(expansion)
3832#define DECL(type, base) \
3833 case Decl::type:
3834#include "clang/AST/DeclNodes.inc"
3835 llvm_unreachable("not an ObjC container!");
3836 }
3837 }
3838
3839 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00003840 if (!protocol->hasDefinition())
3841 return;
3842
John McCalld2930c22011-07-22 02:45:48 +00003843 // A method in a protocol declaration overrides declarations from
3844 // referenced ("parent") protocols.
3845 search(protocol->getReferencedProtocols());
3846 }
3847
3848 void searchFrom(ObjCCategoryDecl *category) {
3849 // A method in a category declaration overrides declarations from
3850 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003851 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00003852 search(category->getReferencedProtocols());
3853 }
3854
3855 void searchFrom(ObjCCategoryImplDecl *impl) {
3856 // A method in a category definition that has a category
3857 // declaration overrides declarations from the category
3858 // declaration.
3859 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
3860 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003861 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
3862 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003863
3864 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003865 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
3866 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003867 }
3868 }
3869
3870 void searchFrom(ObjCInterfaceDecl *iface) {
3871 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00003872 if (!iface->hasDefinition())
3873 return;
3874
John McCalld2930c22011-07-22 02:45:48 +00003875 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00003876 for (auto *Cat : iface->known_categories())
3877 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00003878
3879 // - the super class, and
3880 if (ObjCInterfaceDecl *super = iface->getSuperClass())
3881 search(super);
3882
3883 // - any referenced protocols.
3884 search(iface->getReferencedProtocols());
3885 }
3886
3887 void searchFrom(ObjCImplementationDecl *impl) {
3888 // A method in a class implementation overrides declarations from
3889 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003890 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
3891 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003892 }
3893
3894
3895 void search(const ObjCProtocolList &protocols) {
3896 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
3897 i != e; ++i)
3898 search(*i);
3899 }
3900
3901 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00003902 // Check for a method in this container which matches this selector.
3903 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00003904 Method->isInstanceMethod(),
3905 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00003906
3907 // If we find one, record it and bail out.
3908 if (meth) {
3909 Overridden.insert(meth);
3910 return;
3911 }
3912
3913 // Otherwise, search for methods that a hypothetical method here
3914 // would have overridden.
3915
3916 // Note that we're now in a recursive case.
3917 Recursive = true;
3918
3919 searchFromContainer(container);
3920 }
3921};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003922}
Douglas Gregor33823722011-06-11 01:09:30 +00003923
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003924void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
3925 ObjCInterfaceDecl *CurrentClass,
3926 ResultTypeCompatibilityKind RTC) {
3927 // Search for overridden methods and merge information down from them.
3928 OverrideSearch overrides(*this, ObjCMethod);
3929 // Keep track if the method overrides any method in the class's base classes,
3930 // its protocols, or its categories' protocols; we will keep that info
3931 // in the ObjCMethodDecl.
3932 // For this info, a method in an implementation is not considered as
3933 // overriding the same method in the interface or its categories.
3934 bool hasOverriddenMethodsInBaseOrProtocol = false;
3935 for (OverrideSearch::iterator
3936 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
3937 ObjCMethodDecl *overridden = *i;
3938
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003939 if (!hasOverriddenMethodsInBaseOrProtocol) {
3940 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3941 CurrentClass != overridden->getClassInterface() ||
3942 overridden->isOverriding()) {
3943 hasOverriddenMethodsInBaseOrProtocol = true;
3944
3945 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3946 // OverrideSearch will return as "overridden" the same method in the
3947 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3948 // check whether a category of a base class introduced a method with the
3949 // same selector, after the interface method declaration.
3950 // To avoid unnecessary lookups in the majority of cases, we use the
3951 // extra info bits in GlobalMethodPool to check whether there were any
3952 // category methods with this selector.
3953 GlobalMethodPool::iterator It =
3954 MethodPool.find(ObjCMethod->getSelector());
3955 if (It != MethodPool.end()) {
3956 ObjCMethodList &List =
3957 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3958 unsigned CategCount = List.getBits();
3959 if (CategCount > 0) {
3960 // If the method is in a category we'll do lookup if there were at
3961 // least 2 category methods recorded, otherwise only one will do.
3962 if (CategCount > 1 ||
3963 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3964 OverrideSearch overrides(*this, overridden);
3965 for (OverrideSearch::iterator
3966 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3967 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003968 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3969 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003970 hasOverriddenMethodsInBaseOrProtocol = true;
3971 overridden->setOverriding(true);
3972 break;
3973 }
3974 }
3975 }
3976 }
3977 }
3978 }
3979 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003980
3981 // Propagate down the 'related result type' bit from overridden methods.
3982 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3983 ObjCMethod->SetRelatedResultType();
3984
3985 // Then merge the declarations.
3986 mergeObjCMethodDecls(ObjCMethod, overridden);
3987
3988 if (ObjCMethod->isImplicit() && overridden->isImplicit())
3989 continue; // Conflicting properties are detected elsewhere.
3990
3991 // Check for overriding methods
3992 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3993 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3994 CheckConflictingOverridingMethod(ObjCMethod, overridden,
3995 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3996
3997 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00003998 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3999 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004000 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4001 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004002 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4003 PrevE = overridden->param_end();
4004 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004005 assert(PrevI != overridden->param_end() && "Param mismatch");
4006 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4007 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4008 // If type of argument of method in this class does not match its
4009 // respective argument type in the super class method, issue warning;
4010 if (!Context.typesAreCompatible(T1, T2)) {
4011 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4012 << T1 << T2;
4013 Diag(overridden->getLocation(), diag::note_previous_declaration);
4014 break;
4015 }
4016 }
4017 }
4018 }
4019
4020 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4021}
4022
Douglas Gregor813a0662015-06-19 18:14:38 +00004023/// Merge type nullability from for a redeclaration of the same entity,
4024/// producing the updated type of the redeclared entity.
4025static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4026 QualType type,
4027 bool usesCSKeyword,
4028 SourceLocation prevLoc,
4029 QualType prevType,
4030 bool prevUsesCSKeyword) {
4031 // Determine the nullability of both types.
4032 auto nullability = type->getNullability(S.Context);
4033 auto prevNullability = prevType->getNullability(S.Context);
4034
4035 // Easy case: both have nullability.
4036 if (nullability.hasValue() == prevNullability.hasValue()) {
4037 // Neither has nullability; continue.
4038 if (!nullability)
4039 return type;
4040
4041 // The nullabilities are equivalent; do nothing.
4042 if (*nullability == *prevNullability)
4043 return type;
4044
4045 // Complain about mismatched nullability.
4046 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004047 << DiagNullabilityKind(*nullability, usesCSKeyword)
4048 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004049 return type;
4050 }
4051
4052 // If it's the redeclaration that has nullability, don't change anything.
4053 if (nullability)
4054 return type;
4055
4056 // Otherwise, provide the result with the same nullability.
4057 return S.Context.getAttributedType(
4058 AttributedType::getNullabilityAttrKind(*prevNullability),
4059 type, type);
4060}
4061
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004062/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004063/// (or a category/extension) into the corresponding method in the
4064/// @implementation (for a class or category).
4065static void mergeInterfaceMethodToImpl(Sema &S,
4066 ObjCMethodDecl *method,
4067 ObjCMethodDecl *prevMethod) {
4068 // Merge the objc_requires_super attribute.
4069 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4070 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4071 // merge the attribute into implementation.
4072 method->addAttr(
4073 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4074 method->getLocation()));
4075 }
4076
4077 // Merge nullability of the result type.
4078 QualType newReturnType
4079 = mergeTypeNullabilityForRedecl(
4080 S, method->getReturnTypeSourceRange().getBegin(),
4081 method->getReturnType(),
4082 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4083 prevMethod->getReturnTypeSourceRange().getBegin(),
4084 prevMethod->getReturnType(),
4085 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4086 method->setReturnType(newReturnType);
4087
4088 // Handle each of the parameters.
4089 unsigned numParams = method->param_size();
4090 unsigned numPrevParams = prevMethod->param_size();
4091 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4092 ParmVarDecl *param = method->param_begin()[i];
4093 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4094
4095 // Merge nullability.
4096 QualType newParamType
4097 = mergeTypeNullabilityForRedecl(
4098 S, param->getLocation(), param->getType(),
4099 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4100 prevParam->getLocation(), prevParam->getType(),
4101 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4102 param->setType(newParamType);
4103 }
4104}
4105
John McCall48871652010-08-21 09:40:31 +00004106Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004107 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004108 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004109 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004110 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004111 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004112 Selector Sel,
4113 // optional arguments. The number of types/arguments is obtained
4114 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004115 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004116 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004117 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004118 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004119 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004120 if (!CurContext->isObjCContainer()) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004121 Diag(MethodLoc, diag::error_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004122 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004123 }
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004124 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4125 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004126 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004127
Douglas Gregorbab8a962011-09-08 01:46:34 +00004128 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004129 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004130 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004131 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004132
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004133 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004134 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004135
Douglas Gregor813a0662015-06-19 18:14:38 +00004136 QualType bareResultType = resultDeclType;
4137 (void)AttributedType::stripOuterNullability(bareResultType);
4138 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004139 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004140 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004141 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004142 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004143 }
Mike Stump11289f42009-09-09 15:08:12 +00004144
Alp Toker314cc812014-01-25 16:55:45 +00004145 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4146 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4147 MethodType == tok::minus, isVariadic,
4148 /*isPropertyAccessor=*/false,
4149 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4150 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4151 : ObjCMethodDecl::Required,
4152 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004153
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004154 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004155
Chris Lattner23b0faf2009-04-11 19:42:43 +00004156 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004157 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004158 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004159
David Blaikie7d170102013-05-15 07:37:26 +00004160 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004161 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004162 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004163 } else {
John McCall856bbea2009-10-23 21:48:59 +00004164 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004165 }
Mike Stump11289f42009-09-09 15:08:12 +00004166
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004167 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4168 LookupOrdinaryName, ForRedeclaration);
4169 LookupName(R, S);
4170 if (R.isSingleResult()) {
4171 NamedDecl *PrevDecl = R.getFoundDecl();
4172 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004173 Diag(ArgInfo[i].NameLoc,
4174 (MethodDefinition ? diag::warn_method_param_redefinition
4175 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004176 << ArgInfo[i].Name;
4177 Diag(PrevDecl->getLocation(),
4178 diag::note_previous_declaration);
4179 }
4180 }
4181
Abramo Bagnaradff19302011-03-08 08:55:46 +00004182 SourceLocation StartLoc = DI
4183 ? DI->getTypeLoc().getBeginLoc()
4184 : ArgInfo[i].NameLoc;
4185
John McCalld44f4d72011-04-23 02:46:06 +00004186 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4187 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004188 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004189
John McCall82490832011-05-02 00:30:12 +00004190 Param->setObjCMethodScopeInfo(i);
4191
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004192 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004193 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004194
Chris Lattner9713a1c2009-04-11 19:34:56 +00004195 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004196 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Mike Stump11289f42009-09-09 15:08:12 +00004197
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004198 if (Param->hasAttr<BlocksAttr>()) {
4199 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4200 Param->setInvalidDecl();
4201 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004202 S->AddDecl(Param);
4203 IdResolver.AddDecl(Param);
4204
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004205 Params.push_back(Param);
4206 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004207
Fariborz Jahanian60462092010-04-08 00:30:06 +00004208 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004209 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004210 QualType ArgType = Param->getType();
4211 if (ArgType.isNull())
4212 ArgType = Context.getObjCIdType();
4213 else
4214 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004215 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004216
Fariborz Jahanian60462092010-04-08 00:30:06 +00004217 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004218 Params.push_back(Param);
4219 }
4220
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004221 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004222 ObjCMethod->setObjCDeclQualifier(
4223 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004224
4225 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004226 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Mike Stump11289f42009-09-09 15:08:12 +00004227
Douglas Gregor87e92752010-12-21 17:34:17 +00004228 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004229 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004230 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004231 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004232 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4233 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004234 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004235 PrevMethod = ImpDecl->getClassMethod(Sel);
4236 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004237 }
Douglas Gregor33823722011-06-11 01:09:30 +00004238
Douglas Gregor813a0662015-06-19 18:14:38 +00004239 // Merge information from the @interface declaration into the
4240 // @implementation.
4241 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4242 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4243 ObjCMethod->isInstanceMethod())) {
4244 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4245
4246 // Warn about defining -dealloc in a category.
4247 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4248 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4249 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4250 << ObjCMethod->getDeclName();
4251 }
4252 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004253 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004254 } else {
4255 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004256 }
John McCalld2930c22011-07-22 02:45:48 +00004257
Chris Lattnerda463fe2007-12-12 07:09:47 +00004258 if (PrevMethod) {
4259 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004260 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004261 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004262 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004263 ObjCMethod->setInvalidDecl();
4264 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004265 }
John McCall28a6aea2009-11-04 02:18:39 +00004266
Douglas Gregor33823722011-06-11 01:09:30 +00004267 // If this Objective-C method does not have a related result type, but we
4268 // are allowed to infer related result types, try to do so based on the
4269 // method family.
4270 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4271 if (!CurrentClass) {
4272 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4273 CurrentClass = Cat->getClassInterface();
4274 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4275 CurrentClass = Impl->getClassInterface();
4276 else if (ObjCCategoryImplDecl *CatImpl
4277 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4278 CurrentClass = CatImpl->getClassInterface();
4279 }
John McCalld2930c22011-07-22 02:45:48 +00004280
Douglas Gregorbab8a962011-09-08 01:46:34 +00004281 ResultTypeCompatibilityKind RTC
4282 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004283
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004284 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004285
John McCall31168b02011-06-15 23:02:42 +00004286 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004287 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004288 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004289
Douglas Gregorbab8a962011-09-08 01:46:34 +00004290 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004291 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004292 !ObjCMethod->hasRelatedResultType() &&
4293 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004294 bool InferRelatedResultType = false;
4295 switch (ObjCMethod->getMethodFamily()) {
4296 case OMF_None:
4297 case OMF_copy:
4298 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004299 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004300 case OMF_mutableCopy:
4301 case OMF_release:
4302 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004303 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004304 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004305 break;
4306
4307 case OMF_alloc:
4308 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004309 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004310 break;
4311
4312 case OMF_init:
4313 case OMF_autorelease:
4314 case OMF_retain:
4315 case OMF_self:
4316 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4317 break;
4318 }
4319
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004320 if (InferRelatedResultType &&
4321 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004322 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004323 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004324
4325 ActOnDocumentableDecl(ObjCMethod);
4326
John McCall48871652010-08-21 09:40:31 +00004327 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004328}
4329
Chris Lattner438e5012008-12-17 07:13:27 +00004330bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004331 // Following is also an error. But it is caused by a missing @end
4332 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004333 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004334 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004335
4336 // If we switched context to translation unit while we are still lexically in
4337 // an objc container, it means the parser missed emitting an error.
4338 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4339 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004340
Anders Carlssona6b508a2008-11-04 16:57:32 +00004341 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4342 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004343
Anders Carlssona6b508a2008-11-04 16:57:32 +00004344 return true;
4345}
Chris Lattner438e5012008-12-17 07:13:27 +00004346
James Dennett634962f2012-06-14 21:40:34 +00004347/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004348/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004349void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004350 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004351 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004352 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004353 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004354 if (!Class) {
4355 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4356 return;
4357 }
John McCall5fb5df92012-06-20 06:18:46 +00004358 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004359 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4360 return;
4361 }
Mike Stump11289f42009-09-09 15:08:12 +00004362
Chris Lattner438e5012008-12-17 07:13:27 +00004363 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004364 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004365 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004366 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004367 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004368 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCall48871652010-08-21 09:40:31 +00004369 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004370 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4371 /*FIXME: StartL=*/ID->getLocation(),
4372 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004373 ID->getIdentifier(), ID->getType(),
4374 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004375 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004376 }
Mike Stump11289f42009-09-09 15:08:12 +00004377
Chris Lattner438e5012008-12-17 07:13:27 +00004378 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004379 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004380 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004381 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004382 if (getLangOpts().CPlusPlus)
Chris Lattner438e5012008-12-17 07:13:27 +00004383 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCall48871652010-08-21 09:40:31 +00004384 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004385 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004386 }
4387}
4388
Douglas Gregorf3564192010-04-26 17:32:49 +00004389/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004390VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4391 SourceLocation StartLoc,
4392 SourceLocation IdLoc,
4393 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004394 bool Invalid) {
4395 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4396 // duration shall not be qualified by an address-space qualifier."
4397 // Since all parameters have automatic store duration, they can not have
4398 // an address space.
4399 if (T.getAddressSpace() != 0) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004400 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004401 Invalid = true;
4402 }
4403
4404 // An @catch parameter must be an unqualified object pointer type;
4405 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4406 if (Invalid) {
4407 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004408 } else if (T->isDependentType()) {
4409 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004410 } else if (!T->isObjCObjectPointerType()) {
4411 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004412 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004413 } else if (T->isObjCQualifiedIdType()) {
4414 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004415 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004416 }
4417
Abramo Bagnaradff19302011-03-08 08:55:46 +00004418 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004419 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004420 New->setExceptionVariable(true);
4421
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004422 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004423 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004424 Invalid = true;
4425
Douglas Gregorf3564192010-04-26 17:32:49 +00004426 if (Invalid)
4427 New->setInvalidDecl();
4428 return New;
4429}
4430
John McCall48871652010-08-21 09:40:31 +00004431Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004432 const DeclSpec &DS = D.getDeclSpec();
4433
4434 // We allow the "register" storage class on exception variables because
4435 // GCC did, but we drop it completely. Any other storage class is an error.
4436 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4437 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4438 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004439 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004440 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004441 << DeclSpec::getSpecifierName(SCS);
4442 }
4443 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4444 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4445 diag::err_invalid_thread)
4446 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004447 D.getMutableDeclSpec().ClearStorageClassSpecs();
4448
Richard Smithb1402ae2013-03-18 22:52:47 +00004449 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004450
4451 // Check that there are no default arguments inside the type of this
4452 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004453 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004454 CheckExtraCXXDefaultArguments(D);
4455
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004456 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004457 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004458
Abramo Bagnaradff19302011-03-08 08:55:46 +00004459 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4460 D.getSourceRange().getBegin(),
4461 D.getIdentifierLoc(),
4462 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004463 D.isInvalidType());
4464
4465 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4466 if (D.getCXXScopeSpec().isSet()) {
4467 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4468 << D.getCXXScopeSpec().getRange();
4469 New->setInvalidDecl();
4470 }
4471
4472 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004473 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004474 if (D.getIdentifier())
4475 IdResolver.AddDecl(New);
4476
4477 ProcessDeclAttributes(S, New, D);
4478
4479 if (New->hasAttr<BlocksAttr>())
4480 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004481 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004482}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004483
4484/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004485/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004486void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004487 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004488 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4489 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004490 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004491 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004492 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004493 }
4494}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004495
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004496void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004497 // Load referenced selectors from the external source.
4498 if (ExternalSource) {
4499 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4500 ExternalSource->ReadReferencedSelectors(Sels);
4501 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4502 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4503 }
4504
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004505 // Warning will be issued only when selector table is
4506 // generated (which means there is at lease one implementation
4507 // in the TU). This is to match gcc's behavior.
4508 if (ReferencedSelectors.empty() ||
4509 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004510 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004511 for (auto &SelectorAndLocation : ReferencedSelectors) {
4512 Selector Sel = SelectorAndLocation.first;
4513 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004514 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004515 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004516 }
4517 return;
4518}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004519
4520ObjCIvarDecl *
4521Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4522 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004523 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004524 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004525 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4526 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004527 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004528 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4529 /*shallowCategoryLookup=*/false,
4530 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004531 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004532 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004533 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004534 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4535 // property backing ivar must belong to property's class
4536 // or be a private ivar in class's implementation.
4537 // FIXME. fix the const-ness issue.
4538 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4539 IV->getIdentifier());
4540 return IV;
4541 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004542 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004543}
4544
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004545namespace {
4546 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4547 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004548 class UnusedBackingIvarChecker :
4549 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004550 public:
4551 Sema &S;
4552 const ObjCMethodDecl *Method;
4553 const ObjCIvarDecl *IvarD;
4554 bool AccessedIvar;
4555 bool InvokedSelfMethod;
4556
4557 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4558 const ObjCIvarDecl *IvarD)
4559 : S(S), Method(Method), IvarD(IvarD),
4560 AccessedIvar(false), InvokedSelfMethod(false) {
4561 assert(IvarD);
4562 }
4563
4564 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4565 if (E->getDecl() == IvarD) {
4566 AccessedIvar = true;
4567 return false;
4568 }
4569 return true;
4570 }
4571
4572 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4573 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4574 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4575 InvokedSelfMethod = true;
4576 }
4577 return true;
4578 }
4579 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004580}
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004581
4582void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4583 const ObjCImplementationDecl *ImplD) {
4584 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004585 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004586
Aaron Ballmanf26acce2014-03-13 19:50:17 +00004587 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004588 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4589 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004590 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004591 continue;
4592
4593 const ObjCPropertyDecl *PDecl;
4594 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4595 if (!IV)
4596 continue;
4597
4598 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4599 Checker.TraverseStmt(CurMethod->getBody());
4600 if (Checker.AccessedIvar)
4601 continue;
4602
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004603 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004604 // implementation makes a self call. This is to prevent false positive in
4605 // cases where the ivar is accessed by another method that the accessor
4606 // delegates to.
4607 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00004608 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004609 Diag(PDecl->getLocation(), diag::note_property_declare);
4610 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004611 }
4612}