blob: e67955e8e1217861839c52c0d7a333d22b3070dc [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
641 // Type bounds cannot have explicit nullability.
642 if (typeBoundInfo) {
643 // Type arguments cannot explicitly specify nullability.
644 if (auto nullability = AttributedType::stripOuterNullability(typeBound)) {
645 // Look at the type location information to find the nullability
646 // specifier so we can zap it.
647 SourceLocation nullabilityLoc
648 = typeBoundInfo->getTypeLoc().findNullabilityLoc();
649 SourceLocation diagLoc
650 = nullabilityLoc.isValid()? nullabilityLoc
651 : typeBoundInfo->getTypeLoc().getLocStart();
652 Diag(diagLoc, diag::err_type_param_bound_explicit_nullability)
653 << paramName << typeBoundInfo->getType()
654 << FixItHint::CreateRemoval(nullabilityLoc);
655 }
656 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000657 }
658
659 // If there was no explicit type bound (or we removed it due to an error),
660 // use 'id' instead.
661 if (!typeBoundInfo) {
662 colonLoc = SourceLocation();
663 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
664 }
665
666 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000667 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
668 index, paramLoc, paramName, colonLoc,
669 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000670}
671
672ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
673 SourceLocation lAngleLoc,
674 ArrayRef<Decl *> typeParamsIn,
675 SourceLocation rAngleLoc) {
676 // We know that the array only contains Objective-C type parameters.
677 ArrayRef<ObjCTypeParamDecl *>
678 typeParams(
679 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
680 typeParamsIn.size());
681
682 // Diagnose redeclarations of type parameters.
683 // We do this now because Objective-C type parameters aren't pushed into
684 // scope until later (after the instance variable block), but we want the
685 // diagnostics to occur right after we parse the type parameter list.
686 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
687 for (auto typeParam : typeParams) {
688 auto known = knownParams.find(typeParam->getIdentifier());
689 if (known != knownParams.end()) {
690 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
691 << typeParam->getIdentifier()
692 << SourceRange(known->second->getLocation());
693
694 typeParam->setInvalidDecl();
695 } else {
696 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
697
698 // Push the type parameter into scope.
699 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
700 }
701 }
702
703 // Create the parameter list.
704 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
705}
706
707void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
708 for (auto typeParam : *typeParamList) {
709 if (!typeParam->isInvalidDecl()) {
710 S->RemoveDecl(typeParam);
711 IdResolver.RemoveDecl(typeParam);
712 }
713 }
714}
715
716namespace {
717 /// The context in which an Objective-C type parameter list occurs, for use
718 /// in diagnostics.
719 enum class TypeParamListContext {
720 ForwardDeclaration,
721 Definition,
722 Category,
723 Extension
724 };
725}
726
727/// Check consistency between two Objective-C type parameter lists, e.g.,
728/// between a category/extension and an @interface or between an @class and an
729/// @interface.
730static bool checkTypeParamListConsistency(Sema &S,
731 ObjCTypeParamList *prevTypeParams,
732 ObjCTypeParamList *newTypeParams,
733 TypeParamListContext newContext) {
734 // If the sizes don't match, complain about that.
735 if (prevTypeParams->size() != newTypeParams->size()) {
736 SourceLocation diagLoc;
737 if (newTypeParams->size() > prevTypeParams->size()) {
738 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
739 } else {
740 diagLoc = S.PP.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
741 }
742
743 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
744 << static_cast<unsigned>(newContext)
745 << (newTypeParams->size() > prevTypeParams->size())
746 << prevTypeParams->size()
747 << newTypeParams->size();
748
749 return true;
750 }
751
752 // Match up the type parameters.
753 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
754 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
755 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
756
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000757 // Check for consistency of the variance.
758 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
759 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
760 newContext != TypeParamListContext::Definition) {
761 // When the new type parameter is invariant and is not part
762 // of the definition, just propagate the variance.
763 newTypeParam->setVariance(prevTypeParam->getVariance());
764 } else if (prevTypeParam->getVariance()
765 == ObjCTypeParamVariance::Invariant &&
766 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
767 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
768 ->getDefinition() == prevTypeParam->getDeclContext())) {
769 // When the old parameter is invariant and was not part of the
770 // definition, just ignore the difference because it doesn't
771 // matter.
772 } else {
773 {
774 // Diagnose the conflict and update the second declaration.
775 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
776 if (diagLoc.isInvalid())
777 diagLoc = newTypeParam->getLocStart();
778
779 auto diag = S.Diag(diagLoc,
780 diag::err_objc_type_param_variance_conflict)
781 << static_cast<unsigned>(newTypeParam->getVariance())
782 << newTypeParam->getDeclName()
783 << static_cast<unsigned>(prevTypeParam->getVariance())
784 << prevTypeParam->getDeclName();
785 switch (prevTypeParam->getVariance()) {
786 case ObjCTypeParamVariance::Invariant:
787 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
788 break;
789
790 case ObjCTypeParamVariance::Covariant:
791 case ObjCTypeParamVariance::Contravariant: {
792 StringRef newVarianceStr
793 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
794 ? "__covariant"
795 : "__contravariant";
796 if (newTypeParam->getVariance()
797 == ObjCTypeParamVariance::Invariant) {
798 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
799 (newVarianceStr + " ").str());
800 } else {
801 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
802 newVarianceStr);
803 }
804 }
805 }
806 }
807
808 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
809 << prevTypeParam->getDeclName();
810
811 // Override the variance.
812 newTypeParam->setVariance(prevTypeParam->getVariance());
813 }
814 }
815
Douglas Gregor85f3f952015-07-07 03:57:15 +0000816 // If the bound types match, there's nothing to do.
817 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
818 newTypeParam->getUnderlyingType()))
819 continue;
820
821 // If the new type parameter's bound was explicit, complain about it being
822 // different from the original.
823 if (newTypeParam->hasExplicitBound()) {
824 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
825 ->getTypeLoc().getSourceRange();
826 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
827 << newTypeParam->getUnderlyingType()
828 << newTypeParam->getDeclName()
829 << prevTypeParam->hasExplicitBound()
830 << prevTypeParam->getUnderlyingType()
831 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
832 << prevTypeParam->getDeclName()
833 << FixItHint::CreateReplacement(
834 newBoundRange,
835 prevTypeParam->getUnderlyingType().getAsString(
836 S.Context.getPrintingPolicy()));
837
838 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
839 << prevTypeParam->getDeclName();
840
841 // Override the new type parameter's bound type with the previous type,
842 // so that it's consistent.
843 newTypeParam->setTypeSourceInfo(
844 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
845 continue;
846 }
847
848 // The new type parameter got the implicit bound of 'id'. That's okay for
849 // categories and extensions (overwrite it later), but not for forward
850 // declarations and @interfaces, because those must be standalone.
851 if (newContext == TypeParamListContext::ForwardDeclaration ||
852 newContext == TypeParamListContext::Definition) {
853 // Diagnose this problem for forward declarations and definitions.
854 SourceLocation insertionLoc
855 = S.PP.getLocForEndOfToken(newTypeParam->getLocation());
856 std::string newCode
857 = " : " + prevTypeParam->getUnderlyingType().getAsString(
858 S.Context.getPrintingPolicy());
859 S.Diag(newTypeParam->getLocation(),
860 diag::err_objc_type_param_bound_missing)
861 << prevTypeParam->getUnderlyingType()
862 << newTypeParam->getDeclName()
863 << (newContext == TypeParamListContext::ForwardDeclaration)
864 << FixItHint::CreateInsertion(insertionLoc, newCode);
865
866 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
867 << prevTypeParam->getDeclName();
868 }
869
870 // Update the new type parameter's bound to match the previous one.
871 newTypeParam->setTypeSourceInfo(
872 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
873 }
874
875 return false;
876}
877
John McCall48871652010-08-21 09:40:31 +0000878Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000879ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000880 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000881 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000882 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000883 ArrayRef<ParsedType> SuperTypeArgs,
884 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000885 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000886 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000887 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000888 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000889
Chris Lattnerda463fe2007-12-12 07:09:47 +0000890 // Check for another declaration kind with the same name.
Douglas Gregorb2ccf012010-04-15 22:33:43 +0000891 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
Douglas Gregorb8eaf292010-04-15 23:40:53 +0000892 LookupOrdinaryName, ForRedeclaration);
Douglas Gregor5101c242008-12-05 18:15:24 +0000893
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000894 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000895 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000896 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000897 }
Mike Stump11289f42009-09-09 15:08:12 +0000898
Douglas Gregordc9166c2011-12-15 20:29:51 +0000899 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000900 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000901
902 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
903 // A previous decl with a different name is because of
904 // @compatibility_alias, for example:
905 // \code
906 // @class NewImage;
907 // @compatibility_alias OldImage NewImage;
908 // \endcode
909 // A lookup for 'OldImage' will return the 'NewImage' decl.
910 //
911 // In such a case use the real declaration name, instead of the alias one,
912 // otherwise we will break IdentifierResolver and redecls-chain invariants.
913 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
914 // has been aliased.
915 ClassName = PrevIDecl->getIdentifier();
916 }
917
Douglas Gregor85f3f952015-07-07 03:57:15 +0000918 // If there was a forward declaration with type parameters, check
919 // for consistency.
920 if (PrevIDecl) {
921 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
922 if (typeParamList) {
923 // Both have type parameter lists; check for consistency.
924 if (checkTypeParamListConsistency(*this, prevTypeParamList,
925 typeParamList,
926 TypeParamListContext::Definition)) {
927 typeParamList = nullptr;
928 }
929 } else {
930 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
931 << ClassName;
932 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
933 << ClassName;
934
935 // Clone the type parameter list.
936 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
937 for (auto typeParam : *prevTypeParamList) {
938 clonedTypeParams.push_back(
939 ObjCTypeParamDecl::Create(
940 Context,
941 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000942 typeParam->getVariance(),
943 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +0000944 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +0000945 SourceLocation(),
946 typeParam->getIdentifier(),
947 SourceLocation(),
948 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
949 }
950
951 typeParamList = ObjCTypeParamList::create(Context,
952 SourceLocation(),
953 clonedTypeParams,
954 SourceLocation());
955 }
956 }
957 }
958
Douglas Gregordc9166c2011-12-15 20:29:51 +0000959 ObjCInterfaceDecl *IDecl
960 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000961 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000962 if (PrevIDecl) {
963 // Class already seen. Was it a definition?
964 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
965 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
966 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +0000967 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +0000968 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +0000969 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000970 }
Douglas Gregordc9166c2011-12-15 20:29:51 +0000971
972 if (AttrList)
973 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
974 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +0000975
Douglas Gregordc9166c2011-12-15 20:29:51 +0000976 // Start the definition of this class. If we're in a redefinition case, there
977 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +0000978 if (!IDecl->hasDefinition())
979 IDecl->startDefinition();
980
Chris Lattnerda463fe2007-12-12 07:09:47 +0000981 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000982 // Diagnose availability in the context of the @interface.
983 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +0000984
Douglas Gregore9d95f12015-07-07 03:57:35 +0000985 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
986 ClassName, ClassLoc,
987 SuperName, SuperLoc, SuperTypeArgs,
988 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000989 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +0000990 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000991 }
Mike Stump11289f42009-09-09 15:08:12 +0000992
Sebastian Redle7c1fe62010-08-13 00:28:03 +0000993 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +0000994 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000995 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
996 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +0000997 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000998 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +0000999 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001000 }
Mike Stump11289f42009-09-09 15:08:12 +00001001
Anders Carlssona6b508a2008-11-04 16:57:32 +00001002 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001003 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001004}
1005
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001006/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1007/// typedef'ed use for a qualified super class and adds them to the list
1008/// of the protocols.
1009void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1010 IdentifierInfo *SuperName,
1011 SourceLocation SuperLoc) {
1012 if (!SuperName)
1013 return;
1014 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1015 LookupOrdinaryName);
1016 if (!IDecl)
1017 return;
1018
1019 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1020 QualType T = TDecl->getUnderlyingType();
1021 if (T->isObjCObjectType())
1022 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
Benjamin Kramerf9890422015-02-17 16:48:30 +00001023 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001024 }
1025}
1026
Richard Smithac4e36d2012-08-08 23:32:13 +00001027/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001028/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001029Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1030 IdentifierInfo *AliasName,
1031 SourceLocation AliasLocation,
1032 IdentifierInfo *ClassName,
1033 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001034 // Look for previous declaration of alias name
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001035 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001036 LookupOrdinaryName, ForRedeclaration);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001037 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001038 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001039 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001040 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001041 }
1042 // Check for class declaration
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001043 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001044 LookupOrdinaryName, ForRedeclaration);
Richard Smithdda56e42011-04-15 14:24:37 +00001045 if (const TypedefNameDecl *TDecl =
1046 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001047 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001048 if (T->isObjCObjectType()) {
1049 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001050 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001051 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001052 LookupOrdinaryName, ForRedeclaration);
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001053 }
1054 }
1055 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001056 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001057 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001058 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001059 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001060 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001061 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001062 }
Mike Stump11289f42009-09-09 15:08:12 +00001063
Chris Lattner219b3e92008-03-16 21:17:37 +00001064 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001065 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001066 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001067
Anders Carlssona6b508a2008-11-04 16:57:32 +00001068 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001069 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001070
John McCall48871652010-08-21 09:40:31 +00001071 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001072}
1073
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001074bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001075 IdentifierInfo *PName,
1076 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001077 const ObjCList<ObjCProtocolDecl> &PList) {
1078
1079 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001080 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1081 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001082 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1083 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001084 if (PDecl->getIdentifier() == PName) {
1085 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1086 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001087 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001088 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001089
1090 if (!PDecl->hasDefinition())
1091 continue;
1092
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001093 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1094 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1095 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001096 }
1097 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001098 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001099}
1100
John McCall48871652010-08-21 09:40:31 +00001101Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001102Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1103 IdentifierInfo *ProtocolName,
1104 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001105 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001106 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001107 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001108 SourceLocation EndProtoLoc,
1109 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001110 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001111 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001112 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001113 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1114 ForRedeclaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001115 ObjCProtocolDecl *PDecl = nullptr;
1116 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001117 // If we already have a definition, complain.
1118 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1119 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001120
Douglas Gregor32c17572012-01-01 20:30:41 +00001121 // Create a new protocol that is completely distinct from previous
1122 // declarations, and do not make this protocol available for name lookup.
1123 // That way, we'll end up completely ignoring the duplicate.
1124 // FIXME: Can we turn this into an error?
1125 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1126 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001127 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001128 PDecl->startDefinition();
1129 } else {
1130 if (PrevDecl) {
1131 // Check for circular dependencies among protocol declarations. This can
1132 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001133 ObjCList<ObjCProtocolDecl> PList;
1134 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1135 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001136 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001137 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001138
1139 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001140 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001141 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001142 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001143
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001144 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001145 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001146 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001147
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001148 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001149 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001150
1151 // Merge attributes from previous declarations.
1152 if (PrevDecl)
1153 mergeDeclAttributes(PDecl, PrevDecl);
1154
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001155 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001156 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001157 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1158 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001159 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001160 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001161 }
Mike Stump11289f42009-09-09 15:08:12 +00001162
1163 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001164 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001165}
1166
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001167static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1168 ObjCProtocolDecl *&UndefinedProtocol) {
1169 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1170 UndefinedProtocol = PDecl;
1171 return true;
1172 }
1173
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001174 for (auto *PI : PDecl->protocols())
1175 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1176 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001177 return true;
1178 }
1179 return false;
1180}
1181
Chris Lattnerda463fe2007-12-12 07:09:47 +00001182/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001183/// issues an error if they are not declared. It returns list of
1184/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001185void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001186Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001187 const IdentifierLocPair *ProtocolId,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001188 unsigned NumProtocols,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001189 SmallVectorImpl<Decl *> &Protocols) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001190 for (unsigned i = 0; i != NumProtocols; ++i) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001191 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
1192 ProtocolId[i].second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001193 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001194 TypoCorrection Corrected = CorrectTypo(
1195 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001196 LookupObjCProtocolName, TUScope, nullptr,
1197 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001198 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001199 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1200 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1201 << ProtocolId[i].first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001202 }
1203
1204 if (!PDecl) {
Chris Lattner3b054132008-11-19 05:08:23 +00001205 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001206 << ProtocolId[i].first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001207 continue;
1208 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001209 // If this is a forward protocol declaration, get its definition.
1210 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1211 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001212
1213 // For an objc container, delay protocol reference checking until after we
1214 // can set the objc decl as the availability context, otherwise check now.
1215 if (!ForObjCContainer) {
1216 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
1217 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001218
1219 // If this is a forward declaration and we are supposed to warn in this
1220 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001221 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001222 ObjCProtocolDecl *UndefinedProtocol;
1223
Douglas Gregoreed49792013-01-17 00:38:46 +00001224 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001225 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Chris Lattner3b054132008-11-19 05:08:23 +00001226 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001227 << ProtocolId[i].first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001228 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1229 << UndefinedProtocol;
1230 }
John McCall48871652010-08-21 09:40:31 +00001231 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001232 }
1233}
1234
Douglas Gregore9d95f12015-07-07 03:57:35 +00001235// Callback to only accept typo corrections that are either
1236// Objective-C protocols or valid Objective-C type arguments.
1237class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1238 ASTContext &Context;
1239 Sema::LookupNameKind LookupKind;
1240 public:
1241 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1242 Sema::LookupNameKind lookupKind)
1243 : Context(context), LookupKind(lookupKind) { }
1244
1245 bool ValidateCandidate(const TypoCorrection &candidate) override {
1246 // If we're allowed to find protocols and we have a protocol, accept it.
1247 if (LookupKind != Sema::LookupOrdinaryName) {
1248 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1249 return true;
1250 }
1251
1252 // If we're allowed to find type names and we have one, accept it.
1253 if (LookupKind != Sema::LookupObjCProtocolName) {
1254 // If we have a type declaration, we might accept this result.
1255 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1256 // If we found a tag declaration outside of C++, skip it. This
1257 // can happy because we look for any name when there is no
1258 // bias to protocol or type names.
1259 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1260 return false;
1261
1262 // Make sure the type is something we would accept as a type
1263 // argument.
1264 auto type = Context.getTypeDeclType(typeDecl);
1265 if (type->isObjCObjectPointerType() ||
1266 type->isBlockPointerType() ||
1267 type->isDependentType() ||
1268 type->isObjCObjectType())
1269 return true;
1270
1271 return false;
1272 }
1273
1274 // If we have an Objective-C class type, accept it; there will
1275 // be another fix to add the '*'.
1276 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1277 return true;
1278
1279 return false;
1280 }
1281
1282 return false;
1283 }
1284};
1285
1286void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1287 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001288 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001289 SourceLocation lAngleLoc,
1290 ArrayRef<IdentifierInfo *> identifiers,
1291 ArrayRef<SourceLocation> identifierLocs,
1292 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001293 SourceLocation &typeArgsLAngleLoc,
1294 SmallVectorImpl<ParsedType> &typeArgs,
1295 SourceLocation &typeArgsRAngleLoc,
1296 SourceLocation &protocolLAngleLoc,
1297 SmallVectorImpl<Decl *> &protocols,
1298 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001299 bool warnOnIncompleteProtocols) {
1300 // Local function that updates the declaration specifiers with
1301 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001302 unsigned numProtocolsResolved = 0;
1303 auto resolvedAsProtocols = [&] {
1304 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1305
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001306 // Determine whether the base type is a parameterized class, in
1307 // which case we want to warn about typos such as
1308 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1309 ObjCInterfaceDecl *baseClass = nullptr;
1310 QualType base = GetTypeFromParser(baseType, nullptr);
1311 bool allAreTypeNames = false;
1312 SourceLocation firstClassNameLoc;
1313 if (!base.isNull()) {
1314 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1315 baseClass = objcObjectType->getInterface();
1316 if (baseClass) {
1317 if (auto typeParams = baseClass->getTypeParamList()) {
1318 if (typeParams->size() == numProtocolsResolved) {
1319 // Note that we should be looking for type names, too.
1320 allAreTypeNames = true;
1321 }
1322 }
1323 }
1324 }
1325 }
1326
Douglas Gregore9d95f12015-07-07 03:57:35 +00001327 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001328 ObjCProtocolDecl *&proto
1329 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001330 // For an objc container, delay protocol reference checking until after we
1331 // can set the objc decl as the availability context, otherwise check now.
1332 if (!warnOnIncompleteProtocols) {
1333 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1334 }
1335
1336 // If this is a forward protocol declaration, get its definition.
1337 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1338 proto = proto->getDefinition();
1339
1340 // If this is a forward declaration and we are supposed to warn in this
1341 // case, do it.
1342 // FIXME: Recover nicely in the hidden case.
1343 ObjCProtocolDecl *forwardDecl = nullptr;
1344 if (warnOnIncompleteProtocols &&
1345 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1346 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1347 << proto->getDeclName();
1348 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1349 << forwardDecl;
1350 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001351
1352 // If everything this far has been a type name (and we care
1353 // about such things), check whether this name refers to a type
1354 // as well.
1355 if (allAreTypeNames) {
1356 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1357 LookupOrdinaryName)) {
1358 if (isa<ObjCInterfaceDecl>(decl)) {
1359 if (firstClassNameLoc.isInvalid())
1360 firstClassNameLoc = identifierLocs[i];
1361 } else if (!isa<TypeDecl>(decl)) {
1362 // Not a type.
1363 allAreTypeNames = false;
1364 }
1365 } else {
1366 allAreTypeNames = false;
1367 }
1368 }
1369 }
1370
1371 // All of the protocols listed also have type names, and at least
1372 // one is an Objective-C class name. Check whether all of the
1373 // protocol conformances are declared by the base class itself, in
1374 // which case we warn.
1375 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1376 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1377 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1378 bool allProtocolsDeclared = true;
1379 for (auto proto : protocols) {
1380 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1381 allProtocolsDeclared = false;
1382 break;
1383 }
1384 }
1385
1386 if (allProtocolsDeclared) {
1387 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1388 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1389 << FixItHint::CreateInsertion(
1390 PP.getLocForEndOfToken(firstClassNameLoc), " *");
1391 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001392 }
1393
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001394 protocolLAngleLoc = lAngleLoc;
1395 protocolRAngleLoc = rAngleLoc;
1396 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001397 };
1398
1399 // Attempt to resolve all of the identifiers as protocols.
1400 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1401 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1402 protocols.push_back(proto);
1403 if (proto)
1404 ++numProtocolsResolved;
1405 }
1406
1407 // If all of the names were protocols, these were protocol qualifiers.
1408 if (numProtocolsResolved == identifiers.size())
1409 return resolvedAsProtocols();
1410
1411 // Attempt to resolve all of the identifiers as type names or
1412 // Objective-C class names. The latter is technically ill-formed,
1413 // but is probably something like \c NSArray<NSView *> missing the
1414 // \c*.
1415 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1416 SmallVector<TypeOrClassDecl, 4> typeDecls;
1417 unsigned numTypeDeclsResolved = 0;
1418 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1419 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1420 LookupOrdinaryName);
1421 if (!decl) {
1422 typeDecls.push_back(TypeOrClassDecl());
1423 continue;
1424 }
1425
1426 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1427 typeDecls.push_back(typeDecl);
1428 ++numTypeDeclsResolved;
1429 continue;
1430 }
1431
1432 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1433 typeDecls.push_back(objcClass);
1434 ++numTypeDeclsResolved;
1435 continue;
1436 }
1437
1438 typeDecls.push_back(TypeOrClassDecl());
1439 }
1440
1441 AttributeFactory attrFactory;
1442
1443 // Local function that forms a reference to the given type or
1444 // Objective-C class declaration.
1445 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1446 -> TypeResult {
1447 // Form declaration specifiers. They simply refer to the type.
1448 DeclSpec DS(attrFactory);
1449 const char* prevSpec; // unused
1450 unsigned diagID; // unused
1451 QualType type;
1452 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1453 type = Context.getTypeDeclType(actualTypeDecl);
1454 else
1455 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1456 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1457 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1458 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1459 parsedType, Context.getPrintingPolicy());
1460 // Use the identifier location for the type source range.
1461 DS.SetRangeStart(loc);
1462 DS.SetRangeEnd(loc);
1463
1464 // Form the declarator.
1465 Declarator D(DS, Declarator::TypeNameContext);
1466
1467 // If we have a typedef of an Objective-C class type that is missing a '*',
1468 // add the '*'.
1469 if (type->getAs<ObjCInterfaceType>()) {
1470 SourceLocation starLoc = PP.getLocForEndOfToken(loc);
1471 ParsedAttributes parsedAttrs(attrFactory);
1472 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1473 SourceLocation(),
1474 SourceLocation(),
1475 SourceLocation(),
1476 SourceLocation()),
1477 parsedAttrs,
1478 starLoc);
1479
1480 // Diagnose the missing '*'.
1481 Diag(loc, diag::err_objc_type_arg_missing_star)
1482 << type
1483 << FixItHint::CreateInsertion(starLoc, " *");
1484 }
1485
1486 // Convert this to a type.
1487 return ActOnTypeName(S, D);
1488 };
1489
1490 // Local function that updates the declaration specifiers with
1491 // type argument information.
1492 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001493 // We did not resolve these as protocols.
1494 protocols.clear();
1495
Douglas Gregore9d95f12015-07-07 03:57:35 +00001496 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1497 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001498 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1499 // Map type reference to a type.
1500 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001501 if (!type.isUsable()) {
1502 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001503 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001504 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001505
1506 typeArgs.push_back(type.get());
1507 }
1508
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001509 typeArgsLAngleLoc = lAngleLoc;
1510 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001511 };
1512
1513 // If all of the identifiers can be resolved as type names or
1514 // Objective-C class names, we have type arguments.
1515 if (numTypeDeclsResolved == identifiers.size())
1516 return resolvedAsTypeDecls();
1517
1518 // Error recovery: some names weren't found, or we have a mix of
1519 // type and protocol names. Go resolve all of the unresolved names
1520 // and complain if we can't find a consistent answer.
1521 LookupNameKind lookupKind = LookupAnyName;
1522 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1523 // If we already have a protocol or type. Check whether it is the
1524 // right thing.
1525 if (protocols[i] || typeDecls[i]) {
1526 // If we haven't figured out whether we want types or protocols
1527 // yet, try to figure it out from this name.
1528 if (lookupKind == LookupAnyName) {
1529 // If this name refers to both a protocol and a type (e.g., \c
1530 // NSObject), don't conclude anything yet.
1531 if (protocols[i] && typeDecls[i])
1532 continue;
1533
1534 // Otherwise, let this name decide whether we'll be correcting
1535 // toward types or protocols.
1536 lookupKind = protocols[i] ? LookupObjCProtocolName
1537 : LookupOrdinaryName;
1538 continue;
1539 }
1540
1541 // If we want protocols and we have a protocol, there's nothing
1542 // more to do.
1543 if (lookupKind == LookupObjCProtocolName && protocols[i])
1544 continue;
1545
1546 // If we want types and we have a type declaration, there's
1547 // nothing more to do.
1548 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1549 continue;
1550
1551 // We have a conflict: some names refer to protocols and others
1552 // refer to types.
1553 Diag(identifierLocs[i], diag::err_objc_type_args_and_protocols)
1554 << (protocols[i] != nullptr)
1555 << identifiers[i]
1556 << identifiers[0]
1557 << SourceRange(identifierLocs[0]);
1558
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001559 protocols.clear();
1560 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001561 return;
1562 }
1563
1564 // Perform typo correction on the name.
1565 TypoCorrection corrected = CorrectTypo(
1566 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1567 nullptr,
1568 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1569 lookupKind),
1570 CTK_ErrorRecovery);
1571 if (corrected) {
1572 // Did we find a protocol?
1573 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1574 diagnoseTypo(corrected,
1575 PDiag(diag::err_undeclared_protocol_suggest)
1576 << identifiers[i]);
1577 lookupKind = LookupObjCProtocolName;
1578 protocols[i] = proto;
1579 ++numProtocolsResolved;
1580 continue;
1581 }
1582
1583 // Did we find a type?
1584 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1585 diagnoseTypo(corrected,
1586 PDiag(diag::err_unknown_typename_suggest)
1587 << identifiers[i]);
1588 lookupKind = LookupOrdinaryName;
1589 typeDecls[i] = typeDecl;
1590 ++numTypeDeclsResolved;
1591 continue;
1592 }
1593
1594 // Did we find an Objective-C class?
1595 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1596 diagnoseTypo(corrected,
1597 PDiag(diag::err_unknown_type_or_class_name_suggest)
1598 << identifiers[i] << true);
1599 lookupKind = LookupOrdinaryName;
1600 typeDecls[i] = objcClass;
1601 ++numTypeDeclsResolved;
1602 continue;
1603 }
1604 }
1605
1606 // We couldn't find anything.
1607 Diag(identifierLocs[i],
1608 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1609 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1610 : diag::err_unknown_typename))
1611 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001612 protocols.clear();
1613 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001614 return;
1615 }
1616
1617 // If all of the names were (corrected to) protocols, these were
1618 // protocol qualifiers.
1619 if (numProtocolsResolved == identifiers.size())
1620 return resolvedAsProtocols();
1621
1622 // Otherwise, all of the names were (corrected to) types.
1623 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1624 return resolvedAsTypeDecls();
1625}
1626
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001627/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001628/// a class method in its extension.
1629///
Mike Stump11289f42009-09-09 15:08:12 +00001630void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001631 ObjCInterfaceDecl *ID) {
1632 if (!ID)
1633 return; // Possibly due to previous error
1634
1635 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001636 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001637 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001638
1639 if (MethodMap.empty())
1640 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001641 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001642 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001643 if (PrevMethod &&
1644 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1645 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001646 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1647 << Method->getDeclName();
1648 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1649 }
1650 }
1651}
1652
James Dennett634962f2012-06-14 21:40:34 +00001653/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001654Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001655Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001656 const IdentifierLocPair *IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001657 unsigned NumElts,
1658 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001659 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001660 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattnerd7352d62008-07-21 22:17:28 +00001661 IdentifierInfo *Ident = IdentList[i].first;
Douglas Gregor32c17572012-01-01 20:30:41 +00001662 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
1663 ForRedeclaration);
1664 ObjCProtocolDecl *PDecl
1665 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1666 IdentList[i].second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001667 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001668
1669 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001670 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001671
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001672 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001673 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Douglas Gregor32c17572012-01-01 20:30:41 +00001674
1675 if (PrevDecl)
1676 mergeDeclAttributes(PDecl, PrevDecl);
1677
Douglas Gregorf6102672012-01-01 21:23:57 +00001678 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001679 }
Mike Stump11289f42009-09-09 15:08:12 +00001680
Rafael Espindolaab417692013-07-09 12:05:01 +00001681 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001682}
1683
John McCall48871652010-08-21 09:40:31 +00001684Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001685ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1686 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001687 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001688 IdentifierInfo *CategoryName,
1689 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001690 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001691 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001692 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001693 SourceLocation EndProtoLoc) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001694 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001695 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001696
1697 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001698
1699 if (!IDecl
1700 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001701 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001702 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001703 // Create an invalid ObjCCategoryDecl to serve as context for
1704 // the enclosing method declarations. We mark the decl invalid
1705 // to make it clear that this isn't a valid AST.
1706 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001707 ClassLoc, CategoryLoc, CategoryName,
1708 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001709 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001710 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001711
1712 if (!IDecl)
1713 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001714 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001715 }
1716
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001717 if (!CategoryName && IDecl->getImplementation()) {
1718 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1719 Diag(IDecl->getImplementation()->getLocation(),
1720 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001721 }
1722
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001723 if (CategoryName) {
1724 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001725 if (ObjCCategoryDecl *Previous
1726 = IDecl->FindCategoryDeclaration(CategoryName)) {
1727 // Class extensions can be declared multiple times, categories cannot.
1728 Diag(CategoryLoc, diag::warn_dup_category_def)
1729 << ClassName << CategoryName;
1730 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001731 }
1732 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001733
Douglas Gregor85f3f952015-07-07 03:57:15 +00001734 // If we have a type parameter list, check it.
1735 if (typeParamList) {
1736 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1737 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1738 CategoryName
1739 ? TypeParamListContext::Category
1740 : TypeParamListContext::Extension))
1741 typeParamList = nullptr;
1742 } else {
1743 Diag(typeParamList->getLAngleLoc(),
1744 diag::err_objc_parameterized_category_nonclass)
1745 << (CategoryName != nullptr)
1746 << ClassName
1747 << typeParamList->getSourceRange();
1748
1749 typeParamList = nullptr;
1750 }
1751 }
1752
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001753 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001754 ClassLoc, CategoryLoc, CategoryName, IDecl,
1755 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001756 // FIXME: PushOnScopeChains?
1757 CurContext->addDecl(CDecl);
1758
Chris Lattnerda463fe2007-12-12 07:09:47 +00001759 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001760 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1761 NumProtoRefs, ProtoLocs);
1762 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001763 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001764 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001765 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001766 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001767 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001768 }
Mike Stump11289f42009-09-09 15:08:12 +00001769
Anders Carlssona6b508a2008-11-04 16:57:32 +00001770 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001771 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001772}
1773
1774/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001775/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001776/// object.
John McCall48871652010-08-21 09:40:31 +00001777Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001778 SourceLocation AtCatImplLoc,
1779 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1780 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001781 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001782 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001783 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001784 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1785 if (!CatIDecl) {
1786 // Category @implementation with no corresponding @interface.
1787 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001788 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1789 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001790 CatName, IDecl,
1791 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001792 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001793 }
1794 }
1795
Mike Stump11289f42009-09-09 15:08:12 +00001796 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001797 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001798 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001799 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001800 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001801 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001802 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001803 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1804 diag::err_undef_interface)) {
1805 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001806 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001807
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001808 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001809 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001810
Argyrios Kyrtzidisc281c962011-10-06 23:23:27 +00001811 // If the interface is deprecated/unavailable, warn/error about it.
1812 if (IDecl)
1813 DiagnoseUseOfDecl(IDecl, ClassLoc);
1814
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001815 /// Check that CatName, category name, is not used in another implementation.
1816 if (CatIDecl) {
1817 if (CatIDecl->getImplementation()) {
1818 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1819 << CatName;
1820 Diag(CatIDecl->getImplementation()->getLocation(),
1821 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001822 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001823 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001824 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001825 // Warn on implementating category of deprecated class under
1826 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001827 DiagnoseObjCImplementedDeprecations(*this,
1828 dyn_cast<NamedDecl>(IDecl),
1829 CDecl->getLocation(), 2);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001830 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001831 }
Mike Stump11289f42009-09-09 15:08:12 +00001832
Anders Carlssona6b508a2008-11-04 16:57:32 +00001833 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001834 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001835}
1836
John McCall48871652010-08-21 09:40:31 +00001837Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001838 SourceLocation AtClassImplLoc,
1839 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001840 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001841 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001842 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001843 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001844 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001845 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1846 ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001847 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001848 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001849 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001850 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001851 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1852 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001853 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001854 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001855 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001856 TypoCorrection Corrected = CorrectTypo(
1857 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1858 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001859 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1860 // Suggest the (potentially) correct interface name. Don't provide a
1861 // code-modification hint or use the typo name for recovery, because
1862 // this is just a warning. The program may actually be correct.
1863 diagnoseTypo(Corrected,
1864 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1865 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001866 } else {
1867 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1868 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001869 }
Mike Stump11289f42009-09-09 15:08:12 +00001870
Chris Lattnerda463fe2007-12-12 07:09:47 +00001871 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001872 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001873 if (SuperClassname) {
1874 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001875 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1876 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001877 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001878 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1879 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001880 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001881 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001882 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001883 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001884 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001885 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001886 Diag(SuperClassLoc, diag::err_undef_superclass)
1887 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001888 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001889 // This implementation and its interface do not have the same
1890 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001891 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001892 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001893 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001894 }
1895 }
1896 }
Mike Stump11289f42009-09-09 15:08:12 +00001897
Chris Lattnerda463fe2007-12-12 07:09:47 +00001898 if (!IDecl) {
1899 // Legacy case of @implementation with no corresponding @interface.
1900 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001901
Mike Stump87c57ac2009-05-16 07:39:55 +00001902 // FIXME: Do we support attributes on the @implementation? If so we should
1903 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001904 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001905 ClassName, /*typeParamList=*/nullptr,
1906 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001907 true);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001908 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00001909 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001910 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1911 Context.getObjCInterfaceType(SDecl),
1912 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00001913 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1914 } else {
1915 IDecl->setEndOfDefinitionLoc(ClassLoc);
1916 }
1917
Douglas Gregorac345a32009-04-24 00:16:12 +00001918 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00001919 } else {
1920 // Mark the interface as being completed, even if it was just as
1921 // @class ....;
1922 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001923 if (!IDecl->hasDefinition())
1924 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001925 }
Mike Stump11289f42009-09-09 15:08:12 +00001926
1927 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001928 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00001929 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001930
Anders Carlssona6b508a2008-11-04 16:57:32 +00001931 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001932 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001933
Chris Lattnerda463fe2007-12-12 07:09:47 +00001934 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00001935 if (IDecl->getImplementation()) {
1936 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001937 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00001938 Diag(IDecl->getImplementation()->getLocation(),
1939 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001940 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00001941 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001942 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00001943 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001944 // Warn on implementating deprecated class under
1945 // -Wdeprecated-implementations flag.
Fariborz Jahaniand724a102011-02-15 17:49:58 +00001946 DiagnoseObjCImplementedDeprecations(*this,
1947 dyn_cast<NamedDecl>(IDecl),
1948 IMPDecl->getLocation(), 1);
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001949 }
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001950 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001951}
1952
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001953Sema::DeclGroupPtrTy
1954Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1955 SmallVector<Decl *, 64> DeclsInGroup;
1956 DeclsInGroup.reserve(Decls.size() + 1);
1957
1958 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1959 Decl *Dcl = Decls[i];
1960 if (!Dcl)
1961 continue;
1962 if (Dcl->getDeclContext()->isFileContext())
1963 Dcl->setTopLevelDeclInObjCContainer();
1964 DeclsInGroup.push_back(Dcl);
1965 }
1966
1967 DeclsInGroup.push_back(ObjCImpDecl);
1968
Rafael Espindolaab417692013-07-09 12:05:01 +00001969 return BuildDeclaratorGroup(DeclsInGroup, false);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00001970}
1971
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001972void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1973 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001974 SourceLocation RBrace) {
1975 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001976 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001977 if (!IDecl)
1978 return;
James Dennett634962f2012-06-14 21:40:34 +00001979 /// Check case of non-existing \@interface decl.
1980 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00001981 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00001982 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00001983 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00001984 // Add ivar's to class's DeclContext.
1985 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00001986 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00001987 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00001988 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00001989 }
1990
Chris Lattnerda463fe2007-12-12 07:09:47 +00001991 return;
1992 }
1993 // If implementation has empty ivar list, just return.
1994 if (numIvars == 0)
1995 return;
Mike Stump11289f42009-09-09 15:08:12 +00001996
Chris Lattnerda463fe2007-12-12 07:09:47 +00001997 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00001998 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00001999 if (ImpDecl->getSuperClass())
2000 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2001 for (unsigned i = 0; i < numIvars; i++) {
2002 ObjCIvarDecl* ImplIvar = ivars[i];
2003 if (const ObjCIvarDecl *ClsIvar =
2004 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2005 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2006 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2007 continue;
2008 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002009 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002010 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002011 if (const ObjCIvarDecl *ClsExtIvar =
2012 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2013 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2014 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2015 continue;
2016 }
2017 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002018 // Instance ivar to Implementation's DeclContext.
2019 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002020 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002021 ImpDecl->addDecl(ImplIvar);
2022 }
2023 return;
2024 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002025 // Check interface's Ivar list against those in the implementation.
2026 // names and types must match.
2027 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002028 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002029 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002030 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2031 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002032 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002033 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002034 assert (ImplIvar && "missing implementation ivar");
2035 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002036
Steve Naroff157599f2009-03-03 14:49:36 +00002037 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002038 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002039 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002040 << ImplIvar->getIdentifier()
2041 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002042 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002043 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2044 ImplIvar->getBitWidthValue(Context) !=
2045 ClsIvar->getBitWidthValue(Context)) {
2046 Diag(ImplIvar->getBitWidth()->getLocStart(),
2047 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2048 Diag(ClsIvar->getBitWidth()->getLocStart(),
2049 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002050 }
Steve Naroff157599f2009-03-03 14:49:36 +00002051 // Make sure the names are identical.
2052 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002053 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002054 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002055 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002056 }
2057 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002058 }
Mike Stump11289f42009-09-09 15:08:12 +00002059
Chris Lattner0f29d982007-12-12 18:11:49 +00002060 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002061 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002062 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002063 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002064}
2065
Ted Kremenekf87decd2013-12-13 05:58:44 +00002066static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2067 ObjCMethodDecl *method,
2068 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002069 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002070 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002071 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002072 switch (method->getAvailability()) {
2073 case AR_Available:
2074 case AR_Deprecated:
2075 break;
2076
2077 // Don't warn about unavailable or not-yet-introduced methods.
2078 case AR_NotYetIntroduced:
2079 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002080 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002081 }
2082
Ted Kremenek65d63572013-03-27 00:02:21 +00002083 // FIXME: For now ignore 'IncompleteImpl'.
2084 // Previously we grouped all unimplemented methods under a single
2085 // warning, but some users strongly voiced that they would prefer
2086 // separate warnings. We will give that approach a try, as that
2087 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002088 {
2089 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2090 B << method;
2091 if (NeededFor)
2092 B << NeededFor;
2093 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002094
2095 // Issue a note to the original declaration.
2096 SourceLocation MethodLoc = method->getLocStart();
2097 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002098 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002099}
2100
David Chisnallb62d15c2010-10-25 17:23:52 +00002101/// Determines if type B can be substituted for type A. Returns true if we can
2102/// guarantee that anything that the user will do to an object of type A can
2103/// also be done to an object of type B. This is trivially true if the two
2104/// types are the same, or if B is a subclass of A. It becomes more complex
2105/// in cases where protocols are involved.
2106///
2107/// Object types in Objective-C describe the minimum requirements for an
2108/// object, rather than providing a complete description of a type. For
2109/// example, if A is a subclass of B, then B* may refer to an instance of A.
2110/// The principle of substitutability means that we may use an instance of A
2111/// anywhere that we may use an instance of B - it will implement all of the
2112/// ivars of B and all of the methods of B.
2113///
2114/// This substitutability is important when type checking methods, because
2115/// the implementation may have stricter type definitions than the interface.
2116/// The interface specifies minimum requirements, but the implementation may
2117/// have more accurate ones. For example, a method may privately accept
2118/// instances of B, but only publish that it accepts instances of A. Any
2119/// object passed to it will be type checked against B, and so will implicitly
2120/// by a valid A*. Similarly, a method may return a subclass of the class that
2121/// it is declared as returning.
2122///
2123/// This is most important when considering subclassing. A method in a
2124/// subclass must accept any object as an argument that its superclass's
2125/// implementation accepts. It may, however, accept a more general type
2126/// without breaking substitutability (i.e. you can still use the subclass
2127/// anywhere that you can use the superclass, but not vice versa). The
2128/// converse requirement applies to return types: the return type for a
2129/// subclass method must be a valid object of the kind that the superclass
2130/// advertises, but it may be specified more accurately. This avoids the need
2131/// for explicit down-casting by callers.
2132///
2133/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002134static bool isObjCTypeSubstitutable(ASTContext &Context,
2135 const ObjCObjectPointerType *A,
2136 const ObjCObjectPointerType *B,
2137 bool rejectId) {
2138 // Reject a protocol-unqualified id.
2139 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002140
2141 // If B is a qualified id, then A must also be a qualified id and it must
2142 // implement all of the protocols in B. It may not be a qualified class.
2143 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2144 // stricter definition so it is not substitutable for id<A>.
2145 if (B->isObjCQualifiedIdType()) {
2146 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002147 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2148 QualType(B,0),
2149 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002150 }
2151
2152 /*
2153 // id is a special type that bypasses type checking completely. We want a
2154 // warning when it is used in one place but not another.
2155 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2156
2157
2158 // If B is a qualified id, then A must also be a qualified id (which it isn't
2159 // if we've got this far)
2160 if (B->isObjCQualifiedIdType()) return false;
2161 */
2162
2163 // Now we know that A and B are (potentially-qualified) class types. The
2164 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002165 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002166}
2167
John McCall071df462010-10-28 02:34:38 +00002168static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2169 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2170}
2171
Douglas Gregor813a0662015-06-19 18:14:38 +00002172/// Determine whether two set of Objective-C declaration qualifiers conflict.
2173static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2174 Decl::ObjCDeclQualifier y) {
2175 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2176 (y & ~Decl::OBJC_TQ_CSNullability);
2177}
2178
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002179static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002180 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002181 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002182 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002183 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002184 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002185 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002186 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2187 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002188 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002189 S.Diag(MethodImpl->getLocation(),
2190 (IsOverridingMode
2191 ? diag::warn_conflicting_overriding_ret_type_modifiers
2192 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002193 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002194 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002195 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002196 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002197 }
2198 else
2199 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002200 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002201 if (Warn && IsOverridingMode &&
2202 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2203 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2204 MethodDecl->getReturnType(),
2205 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002206 auto nullabilityMethodImpl =
2207 *MethodImpl->getReturnType()->getNullability(S.Context);
2208 auto nullabilityMethodDecl =
2209 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002210 S.Diag(MethodImpl->getLocation(),
2211 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002212 << DiagNullabilityKind(
2213 nullabilityMethodImpl,
2214 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2215 != 0))
2216 << DiagNullabilityKind(
2217 nullabilityMethodDecl,
2218 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2219 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002220 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2221 }
2222
Alp Toker314cc812014-01-25 16:55:45 +00002223 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2224 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002225 return true;
2226 if (!Warn)
2227 return false;
John McCall071df462010-10-28 02:34:38 +00002228
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002229 unsigned DiagID =
2230 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2231 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002232
2233 // Mismatches between ObjC pointers go into a different warning
2234 // category, and sometimes they're even completely whitelisted.
2235 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002236 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002237 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002238 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002239 // Allow non-matching return types as long as they don't violate
2240 // the principle of substitutability. Specifically, we permit
2241 // return types that are subclasses of the declared return type,
2242 // or that are more-qualified versions of the declared type.
2243 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002244 return false;
John McCall071df462010-10-28 02:34:38 +00002245
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002246 DiagID =
2247 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2248 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002249 }
2250 }
2251
2252 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002253 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2254 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002255 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002256 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2257 ? diag::note_previous_declaration
2258 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002259 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002260 return false;
John McCall071df462010-10-28 02:34:38 +00002261}
2262
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002263static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002264 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002265 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002266 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002267 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002268 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002269 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002270 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002271 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002272 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2273 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002274 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002275 if (IsOverridingMode)
2276 S.Diag(ImplVar->getLocation(),
2277 diag::warn_conflicting_overriding_param_modifiers)
2278 << getTypeRange(ImplVar->getTypeSourceInfo())
2279 << MethodImpl->getDeclName();
2280 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002281 diag::warn_conflicting_param_modifiers)
2282 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002283 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002284 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2285 << getTypeRange(IfaceVar->getTypeSourceInfo());
2286 }
2287 else
2288 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002289 }
2290
John McCall071df462010-10-28 02:34:38 +00002291 QualType ImplTy = ImplVar->getType();
2292 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002293 if (Warn && IsOverridingMode &&
2294 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2295 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002296 S.Diag(ImplVar->getLocation(),
2297 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002298 << DiagNullabilityKind(
2299 *ImplTy->getNullability(S.Context),
2300 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2301 != 0))
2302 << DiagNullabilityKind(
2303 *IfaceTy->getNullability(S.Context),
2304 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2305 != 0));
2306 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002307 }
John McCall071df462010-10-28 02:34:38 +00002308 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002309 return true;
2310
2311 if (!Warn)
2312 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002313 unsigned DiagID =
2314 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2315 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002316
2317 // Mismatches between ObjC pointers go into a different warning
2318 // category, and sometimes they're even completely whitelisted.
2319 if (const ObjCObjectPointerType *ImplPtrTy =
2320 ImplTy->getAs<ObjCObjectPointerType>()) {
2321 if (const ObjCObjectPointerType *IfacePtrTy =
2322 IfaceTy->getAs<ObjCObjectPointerType>()) {
2323 // Allow non-matching argument types as long as they don't
2324 // violate the principle of substitutability. Specifically, the
2325 // implementation must accept any objects that the superclass
2326 // accepts, however it may also accept others.
2327 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002328 return false;
John McCall071df462010-10-28 02:34:38 +00002329
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002330 DiagID =
2331 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2332 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002333 }
2334 }
2335
2336 S.Diag(ImplVar->getLocation(), DiagID)
2337 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002338 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2339 S.Diag(IfaceVar->getLocation(),
2340 (IsOverridingMode ? diag::note_previous_declaration
2341 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002342 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002343 return false;
John McCall071df462010-10-28 02:34:38 +00002344}
John McCall31168b02011-06-15 23:02:42 +00002345
2346/// In ARC, check whether the conventional meanings of the two methods
2347/// match. If they don't, it's a hard error.
2348static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2349 ObjCMethodDecl *decl) {
2350 ObjCMethodFamily implFamily = impl->getMethodFamily();
2351 ObjCMethodFamily declFamily = decl->getMethodFamily();
2352 if (implFamily == declFamily) return false;
2353
2354 // Since conventions are sorted by selector, the only possibility is
2355 // that the types differ enough to cause one selector or the other
2356 // to fall out of the family.
2357 assert(implFamily == OMF_None || declFamily == OMF_None);
2358
2359 // No further diagnostics required on invalid declarations.
2360 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2361
2362 const ObjCMethodDecl *unmatched = impl;
2363 ObjCMethodFamily family = declFamily;
2364 unsigned errorID = diag::err_arc_lost_method_convention;
2365 unsigned noteID = diag::note_arc_lost_method_convention;
2366 if (declFamily == OMF_None) {
2367 unmatched = decl;
2368 family = implFamily;
2369 errorID = diag::err_arc_gained_method_convention;
2370 noteID = diag::note_arc_gained_method_convention;
2371 }
2372
2373 // Indexes into a %select clause in the diagnostic.
2374 enum FamilySelector {
2375 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2376 };
2377 FamilySelector familySelector = FamilySelector();
2378
2379 switch (family) {
2380 case OMF_None: llvm_unreachable("logic error, no method convention");
2381 case OMF_retain:
2382 case OMF_release:
2383 case OMF_autorelease:
2384 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002385 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002386 case OMF_retainCount:
2387 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002388 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002389 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002390 // Mismatches for these methods don't change ownership
2391 // conventions, so we don't care.
2392 return false;
2393
2394 case OMF_init: familySelector = F_init; break;
2395 case OMF_alloc: familySelector = F_alloc; break;
2396 case OMF_copy: familySelector = F_copy; break;
2397 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2398 case OMF_new: familySelector = F_new; break;
2399 }
2400
2401 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2402 ReasonSelector reasonSelector;
2403
2404 // The only reason these methods don't fall within their families is
2405 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002406 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002407 reasonSelector = R_UnrelatedReturn;
2408 } else {
2409 reasonSelector = R_NonObjectReturn;
2410 }
2411
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002412 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2413 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002414
2415 return true;
2416}
John McCall071df462010-10-28 02:34:38 +00002417
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002418void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002419 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002420 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002421 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002422 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2423 return;
2424
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002425 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002426 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002427 true);
Mike Stump11289f42009-09-09 15:08:12 +00002428
Chris Lattner67f35b02009-04-11 19:58:42 +00002429 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002430 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2431 EF = MethodDecl->param_end();
2432 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002433 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002434 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002435 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002436
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002437 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002438 Diag(ImpMethodDecl->getLocation(),
2439 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002440 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002441 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002442}
2443
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002444void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2445 ObjCMethodDecl *Overridden,
2446 bool IsProtocolMethodDecl) {
2447
2448 CheckMethodOverrideReturn(*this, Method, Overridden,
2449 IsProtocolMethodDecl, true,
2450 true);
2451
2452 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002453 IF = Overridden->param_begin(), EM = Method->param_end(),
2454 EF = Overridden->param_end();
2455 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002456 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2457 IsProtocolMethodDecl, true, true);
2458 }
2459
2460 if (Method->isVariadic() != Overridden->isVariadic()) {
2461 Diag(Method->getLocation(),
2462 diag::warn_conflicting_overriding_variadic);
2463 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2464 }
2465}
2466
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002467/// WarnExactTypedMethods - This routine issues a warning if method
2468/// implementation declaration matches exactly that of its declaration.
2469void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2470 ObjCMethodDecl *MethodDecl,
2471 bool IsProtocolMethodDecl) {
2472 // don't issue warning when protocol method is optional because primary
2473 // class is not required to implement it and it is safe for protocol
2474 // to implement it.
2475 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2476 return;
2477 // don't issue warning when primary class's method is
2478 // depecated/unavailable.
2479 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2480 MethodDecl->hasAttr<DeprecatedAttr>())
2481 return;
2482
2483 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2484 IsProtocolMethodDecl, false, false);
2485 if (match)
2486 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002487 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2488 EF = MethodDecl->param_end();
2489 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002490 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2491 *IM, *IF,
2492 IsProtocolMethodDecl, false, false);
2493 if (!match)
2494 break;
2495 }
2496 if (match)
2497 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002498 if (match)
2499 match = !(MethodDecl->isClassMethod() &&
2500 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002501
2502 if (match) {
2503 Diag(ImpMethodDecl->getLocation(),
2504 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002505 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2506 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002507 }
2508}
2509
Mike Stump87c57ac2009-05-16 07:39:55 +00002510/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2511/// improve the efficiency of selector lookups and type checking by associating
2512/// with each protocol / interface / category the flattened instance tables. If
2513/// we used an immutable set to keep the table then it wouldn't add significant
2514/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002515
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002516typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002517typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002518
2519static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2520 ProtocolNameSet &PNS) {
2521 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2522 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002523 for (const auto *PI : PDecl->protocols())
2524 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002525}
2526
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002527/// Recursively populates a set with all conformed protocols in a class
2528/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2529/// attribute.
2530static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2531 ProtocolNameSet &PNS) {
2532 if (!Super)
2533 return;
2534
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002535 for (const auto *I : Super->all_referenced_protocols())
2536 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002537
2538 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002539}
2540
Steve Naroffa36992242008-02-08 22:06:17 +00002541/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002542/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002543static void CheckProtocolMethodDefs(Sema &S,
2544 SourceLocation ImpLoc,
2545 ObjCProtocolDecl *PDecl,
2546 bool& IncompleteImpl,
2547 const Sema::SelectorSet &InsMap,
2548 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002549 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002550 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002551 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2552 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2553 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002554 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2555
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002556 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002557 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002558
2559 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2560 // then we should check if any class in the super class hierarchy also
2561 // conforms to this protocol, either directly or via protocol inheritance.
2562 // If so, we can skip checking this protocol completely because we
2563 // know that a parent class already satisfies this protocol.
2564 //
2565 // Note: we could generalize this logic for all protocols, and merely
2566 // add the limit on looking at the super class chain for just
2567 // specially marked protocols. This may be a good optimization. This
2568 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2569 // protocols for now for controlled evaluation.
2570 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002571 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002572 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2573 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2574 }
2575 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2576 ProtocolsExplictImpl->end())
2577 return;
2578
2579 // If no super class conforms to the protocol, we should not search
2580 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002581 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002582 }
2583
Ted Kremenek285ee852013-12-13 06:26:10 +00002584 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002585 // check to see if class implements forwardInvocation method and objects
2586 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002587 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002588 // Under such conditions, which means that every method possible is
2589 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002590 // found" warnings.
2591 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002592 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2593 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002594 if (InsMap.count(fISelector))
2595 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2596 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002597 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002598 }
Mike Stump11289f42009-09-09 15:08:12 +00002599
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002600 // If this is a forward protocol declaration, get its definition.
2601 if (!PDecl->isThisDeclarationADefinition() &&
2602 PDecl->getDefinition())
2603 PDecl = PDecl->getDefinition();
2604
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002605 // If a method lookup fails locally we still need to look and see if
2606 // the method was implemented by a base class or an inherited
2607 // protocol. This lookup is slow, but occurs rarely in correct code
2608 // and otherwise would terminate in a warning.
2609
Chris Lattnerda463fe2007-12-12 07:09:47 +00002610 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002611 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002612 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002613 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002614 !method->isPropertyAccessor() &&
2615 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002616 (!Super || !Super->lookupMethod(method->getSelector(),
2617 true /* instance */,
2618 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002619 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002620 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002621 // If a method is not implemented in the category implementation but
2622 // has been declared in its primary class, superclass,
2623 // or in one of their protocols, no need to issue the warning.
2624 // This is because method will be implemented in the primary class
2625 // or one of its super class implementation.
2626
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002627 // Ugly, but necessary. Method declared in protcol might have
2628 // have been synthesized due to a property declared in the class which
2629 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002630 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002631 IDecl->lookupMethod(method->getSelector(),
2632 true /* instance */,
2633 true /* shallowCategoryLookup */,
2634 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002635 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002636 continue;
2637 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002638 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002639 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002640 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002641 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002642 }
2643 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002644 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002645 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002646 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2647 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002648 (!Super || !Super->lookupMethod(method->getSelector(),
2649 false /* class method */,
2650 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002651 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002652 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002653 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002654 if (C && IDecl->lookupMethod(method->getSelector(),
2655 false /* class */,
2656 true /* shallowCategoryLookup */,
2657 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002658 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002659
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002660 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002661 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002662 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002663 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002664 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002665 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002666 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002667 for (auto *PI : PDecl->protocols())
2668 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002669 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002670}
2671
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002672/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002673/// or protocol against those declared in their implementations.
2674///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002675void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2676 const SelectorSet &ClsMap,
2677 SelectorSet &InsMapSeen,
2678 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002679 ObjCImplDecl* IMPDecl,
2680 ObjCContainerDecl* CDecl,
2681 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002682 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002683 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002684 // Check and see if instance methods in class interface have been
2685 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002686 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002687 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002688 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002689 if (!I->isPropertyAccessor() &&
2690 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002691 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002692 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002693 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002694 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002695 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002696 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002697 IMPDecl->getInstanceMethod(I->getSelector());
2698 assert(CDecl->getInstanceMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002699 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002700 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002701 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002702 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002703 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002704 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002705 else if (!I->isPropertyAccessor())
2706 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002707 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002708 }
2709 }
Mike Stump11289f42009-09-09 15:08:12 +00002710
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002711 // Check and see if class methods in class interface have been
2712 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002713 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002714 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002715 continue;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002716 if (!ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002717 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002718 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002719 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002720 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002721 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002722 IMPDecl->getClassMethod(I->getSelector());
2723 assert(CDecl->getClassMethod(I->getSelector()) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002724 "Expected to find the method through lookup as well");
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002725 if (!WarnCategoryMethodImpl)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002726 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002727 isa<ObjCProtocolDecl>(CDecl));
2728 else
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002729 WarnExactTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002730 isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002731 }
2732 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002733
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002734 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2735 // Also, check for methods declared in protocols inherited by
2736 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002737 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002738 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002739 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002740 WarnCategoryMethodImpl);
2741 }
2742
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002743 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002744 // when checking that methods in implementation match their declaration,
2745 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2746 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002747 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002748 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002749 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman3fe486a2014-03-13 21:23:55 +00002750 IMPDecl, Cat, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002751 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002752 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002753 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002754 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002755 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002756 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002757 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002758 }
2759
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002760 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002761 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002762 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002763 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002764 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002765
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002766 // FIXME. For now, we are not checking for extact match of methods
2767 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002768 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002769 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002770 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002771 I->getSuperClass(), IncompleteImpl, false);
2772 }
2773}
2774
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002775/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2776/// category matches with those implemented in its primary class and
2777/// warns each time an exact match is found.
2778void Sema::CheckCategoryVsClassMethodMatches(
2779 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002780 // Get category's primary class.
2781 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2782 if (!CatDecl)
2783 return;
2784 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2785 if (!IDecl)
2786 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002787 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2788 SelectorSet InsMap, ClsMap;
2789
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002790 for (const auto *I : CatIMPDecl->instance_methods()) {
2791 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002792 // When checking for methods implemented in the category, skip over
2793 // those declared in category class's super class. This is because
2794 // the super class must implement the method.
2795 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2796 continue;
2797 InsMap.insert(Sel);
2798 }
2799
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002800 for (const auto *I : CatIMPDecl->class_methods()) {
2801 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002802 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2803 continue;
2804 ClsMap.insert(Sel);
2805 }
2806 if (InsMap.empty() && ClsMap.empty())
2807 return;
2808
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002809 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002810 bool IncompleteImpl = false;
2811 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2812 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002813 IncompleteImpl, false,
2814 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002815}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002816
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002817void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002818 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002819 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002820 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002821 // Check and see if instance methods in class interface have been
2822 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002823 for (const auto *I : IMPDecl->instance_methods())
2824 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002825
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002826 // Check and see if properties declared in the interface have either 1)
2827 // an implementation or 2) there is a @synthesize/@dynamic implementation
2828 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002829 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2830 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2831 LangOpts.ObjCRuntime.isNonFragile() &&
2832 !IDecl->isObjCRequiresPropertyDefs();
2833 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2834 }
2835
Douglas Gregor849ebc22015-06-19 18:14:46 +00002836 // Diagnose null-resettable synthesized setters.
2837 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2838
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002839 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002840 for (const auto *I : IMPDecl->class_methods())
2841 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002842
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002843 // Check for type conflict of methods declared in a class/protocol and
2844 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002845 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002846 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2847 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002848 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002849
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002850 // check all methods implemented in category against those declared
2851 // in its primary class.
2852 if (ObjCCategoryImplDecl *CatDecl =
2853 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2854 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002855
Chris Lattnerda463fe2007-12-12 07:09:47 +00002856 // Check the protocol list for unimplemented methods in the @implementation
2857 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002858 // Check and see if class methods in class interface have been
2859 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002860
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002861 LazyProtocolNameSet ExplicitImplProtocols;
2862
Chris Lattner9ef10f42009-03-01 00:56:52 +00002863 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002864 for (auto *PI : I->all_referenced_protocols())
2865 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2866 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002867 // Check class extensions (unnamed categories)
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002868 for (auto *Ext : I->visible_extensions())
2869 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002870 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002871 // For extended class, unimplemented methods in its protocols will
2872 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002873 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002874 for (auto *P : C->protocols())
2875 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002876 IncompleteImpl, InsMap, ClsMap, CDecl,
2877 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002878 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00002879 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002880 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002881 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002882 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002883}
2884
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002885Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00002886Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00002887 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00002888 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002889 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00002890 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002891 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002892 for (unsigned i = 0; i != NumElts; ++i) {
2893 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00002894 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00002895 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Douglas Gregorb8eaf292010-04-15 23:40:53 +00002896 LookupOrdinaryName, ForRedeclaration);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002897 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00002898 // GCC apparently allows the following idiom:
2899 //
2900 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2901 // @class XCElementToggler;
2902 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002903 // Here we have chosen to ignore the forward class declaration
2904 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00002905 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00002906 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002907 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00002908 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00002909 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00002910 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002911 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00002912 // as this will force the intended behavior which is to lookup the
2913 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002914 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00002915 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2916 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00002917 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2918 continue;
2919 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00002920 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002921 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00002922
2923 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002924 ObjCInterfaceDecl *PrevIDecl
2925 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00002926
2927 IdentifierInfo *ClassName = IdentList[i];
2928 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2929 // A previous decl with a different name is because of
2930 // @compatibility_alias, for example:
2931 // \code
2932 // @class NewImage;
2933 // @compatibility_alias OldImage NewImage;
2934 // \endcode
2935 // A lookup for 'OldImage' will return the 'NewImage' decl.
2936 //
2937 // In such a case use the real declaration name, instead of the alias one,
2938 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2939 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2940 // has been aliased.
2941 ClassName = PrevIDecl->getIdentifier();
2942 }
2943
Douglas Gregor85f3f952015-07-07 03:57:15 +00002944 // If this forward declaration has type parameters, compare them with the
2945 // type parameters of the previous declaration.
2946 ObjCTypeParamList *TypeParams = TypeParamLists[i];
2947 if (PrevIDecl && TypeParams) {
2948 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
2949 // Check for consistency with the previous declaration.
2950 if (checkTypeParamListConsistency(
2951 *this, PrevTypeParams, TypeParams,
2952 TypeParamListContext::ForwardDeclaration)) {
2953 TypeParams = nullptr;
2954 }
2955 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
2956 // The @interface does not have type parameters. Complain.
2957 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
2958 << ClassName
2959 << TypeParams->getSourceRange();
2960 Diag(Def->getLocation(), diag::note_defined_here)
2961 << ClassName;
2962
2963 TypeParams = nullptr;
2964 }
2965 }
2966
Douglas Gregordc9166c2011-12-15 20:29:51 +00002967 ObjCInterfaceDecl *IDecl
2968 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002969 ClassName, TypeParams, PrevIDecl,
2970 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00002971 IDecl->setAtEndRange(IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00002972
Douglas Gregordc9166c2011-12-15 20:29:51 +00002973 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00002974 CheckObjCDeclScope(IDecl);
2975 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002976 }
Rafael Espindolaab417692013-07-09 12:05:01 +00002977
2978 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002979}
2980
John McCall54507ab2011-06-16 01:15:19 +00002981static bool tryMatchRecordTypes(ASTContext &Context,
2982 Sema::MethodMatchStrategy strategy,
2983 const Type *left, const Type *right);
2984
John McCall31168b02011-06-15 23:02:42 +00002985static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2986 QualType leftQT, QualType rightQT) {
2987 const Type *left =
2988 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2989 const Type *right =
2990 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2991
2992 if (left == right) return true;
2993
2994 // If we're doing a strict match, the types have to match exactly.
2995 if (strategy == Sema::MMS_strict) return false;
2996
2997 if (left->isIncompleteType() || right->isIncompleteType()) return false;
2998
2999 // Otherwise, use this absurdly complicated algorithm to try to
3000 // validate the basic, low-level compatibility of the two types.
3001
3002 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003003 TypeInfo LeftTI = Context.getTypeInfo(left);
3004 TypeInfo RightTI = Context.getTypeInfo(right);
3005 if (LeftTI.Width != RightTI.Width)
3006 return false;
3007
3008 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003009 return false;
3010
3011 // Consider all the kinds of non-dependent canonical types:
3012 // - functions and arrays aren't possible as return and parameter types
3013
3014 // - vector types of equal size can be arbitrarily mixed
3015 if (isa<VectorType>(left)) return isa<VectorType>(right);
3016 if (isa<VectorType>(right)) return false;
3017
3018 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003019 // - structs, unions, and Objective-C objects must match more-or-less
3020 // exactly
John McCall31168b02011-06-15 23:02:42 +00003021 // - everything else should be a scalar
3022 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003023 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003024
John McCall9320b872011-09-09 05:25:32 +00003025 // Make scalars agree in kind, except count bools as chars, and group
3026 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003027 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3028 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3029 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3030 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003031 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3032 leftSK = Type::STK_ObjCObjectPointer;
3033 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3034 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003035
3036 // Note that data member pointers and function member pointers don't
3037 // intermix because of the size differences.
3038
3039 return (leftSK == rightSK);
3040}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003041
John McCall54507ab2011-06-16 01:15:19 +00003042static bool tryMatchRecordTypes(ASTContext &Context,
3043 Sema::MethodMatchStrategy strategy,
3044 const Type *lt, const Type *rt) {
3045 assert(lt && rt && lt != rt);
3046
3047 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3048 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3049 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3050
3051 // Require union-hood to match.
3052 if (left->isUnion() != right->isUnion()) return false;
3053
3054 // Require an exact match if either is non-POD.
3055 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3056 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3057 return false;
3058
3059 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003060 TypeInfo LeftTI = Context.getTypeInfo(lt);
3061 TypeInfo RightTI = Context.getTypeInfo(rt);
3062 if (LeftTI.Width != RightTI.Width)
3063 return false;
3064
3065 if (LeftTI.Align != RightTI.Align)
3066 return false;
John McCall54507ab2011-06-16 01:15:19 +00003067
3068 // Require fields to match.
3069 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3070 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3071 for (; li != le && ri != re; ++li, ++ri) {
3072 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3073 return false;
3074 }
3075 return (li == le && ri == re);
3076}
3077
Chris Lattnerda463fe2007-12-12 07:09:47 +00003078/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3079/// returns true, or false, accordingly.
3080/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003081bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3082 const ObjCMethodDecl *right,
3083 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003084 if (!matchTypes(Context, strategy, left->getReturnType(),
3085 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003086 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003087
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003088 // If either is hidden, it is not considered to match.
3089 if (left->isHidden() || right->isHidden())
3090 return false;
3091
David Blaikiebbafb8a2012-03-11 07:00:24 +00003092 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003093 (left->hasAttr<NSReturnsRetainedAttr>()
3094 != right->hasAttr<NSReturnsRetainedAttr>() ||
3095 left->hasAttr<NSConsumesSelfAttr>()
3096 != right->hasAttr<NSConsumesSelfAttr>()))
3097 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003098
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003099 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003100 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3101 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003102
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003103 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003104 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003105 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003106
3107 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3108 return false;
3109
David Blaikiebbafb8a2012-03-11 07:00:24 +00003110 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003111 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3112 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003113 }
3114 return true;
3115}
3116
Nico Weber2e0c8f72014-12-27 03:58:08 +00003117void Sema::addMethodToGlobalList(ObjCMethodList *List,
3118 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003119 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3120 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003121 if (ObjCCategoryDecl *CD =
3122 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003123 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003124 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003125
Douglas Gregorc454afe2012-01-25 00:19:56 +00003126 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003127 if (List->getMethod() == nullptr) {
3128 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003129 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003130 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003131 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003132
Douglas Gregorc454afe2012-01-25 00:19:56 +00003133 // We've seen a method with this name, see if we have already seen this type
3134 // signature.
3135 ObjCMethodList *Previous = List;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003136 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003137 // If we are building a module, keep all of the methods.
3138 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
3139 continue;
3140
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003141 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) {
3142 // Even if two method types do not match, we would like to say
3143 // there is more than one declaration so unavailability/deprecated
3144 // warning is not too noisy.
3145 if (!Method->isDefined())
3146 List->setHasMoreThanOneDecl(true);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003147 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003148 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003149
3150 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003151
3152 // Propagate the 'defined' bit.
3153 if (Method->isDefined())
3154 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003155 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003156 // Objective-C doesn't allow an @interface for a class after its
3157 // @implementation. So if Method is not defined and there already is
3158 // an entry for this type signature, Method has to be for a different
3159 // class than PrevObjCMethod.
3160 List->setHasMoreThanOneDecl(true);
3161 }
3162
Douglas Gregorc454afe2012-01-25 00:19:56 +00003163 // If a method is deprecated, push it in the global pool.
3164 // This is used for better diagnostics.
3165 if (Method->isDeprecated()) {
3166 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003167 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003168 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003169 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003170 // unless previous one is deprecated.
3171 if (Method->isUnavailable()) {
3172 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003173 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003174 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003175
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003176 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003177 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003178
Douglas Gregorc454afe2012-01-25 00:19:56 +00003179 // We have a new signature for an existing method - add it.
3180 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003181 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Nico Weber2e0c8f72014-12-27 03:58:08 +00003182 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003183}
3184
Sebastian Redl75d8a322010-08-02 23:18:59 +00003185/// \brief Read the contents of the method pool for a given selector from
3186/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003187void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003188 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003189 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003190}
3191
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003192void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003193 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003194 // Ignore methods of invalid containers.
3195 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003196 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003197
Douglas Gregor70f449b2012-01-25 00:59:09 +00003198 if (ExternalSource)
3199 ReadMethodPool(Method->getSelector());
3200
Sebastian Redl75d8a322010-08-02 23:18:59 +00003201 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003202 if (Pos == MethodPool.end())
3203 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3204 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003205
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003206 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003207
Sebastian Redl75d8a322010-08-02 23:18:59 +00003208 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003209 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003210}
3211
John McCall31168b02011-06-15 23:02:42 +00003212/// Determines if this is an "acceptable" loose mismatch in the global
3213/// method pool. This exists mostly as a hack to get around certain
3214/// global mismatches which we can't afford to make warnings / errors.
3215/// Really, what we want is a way to take a method out of the global
3216/// method pool.
3217static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3218 ObjCMethodDecl *other) {
3219 if (!chosen->isInstanceMethod())
3220 return false;
3221
3222 Selector sel = chosen->getSelector();
3223 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3224 return false;
3225
3226 // Don't complain about mismatches for -length if the method we
3227 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003228 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003229}
3230
Nico Weber2e0c8f72014-12-27 03:58:08 +00003231bool Sema::CollectMultipleMethodsInGlobalPool(
3232 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003233 if (ExternalSource)
3234 ReadMethodPool(Sel);
3235
3236 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3237 if (Pos == MethodPool.end())
3238 return false;
3239 // Gather the non-hidden methods.
3240 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3241 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003242 if (M->getMethod() && !M->getMethod()->isHidden())
3243 Methods.push_back(M->getMethod());
3244 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003245}
3246
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003247bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
3248 SourceRange R,
3249 bool receiverIdOrClass) {
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003250 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003251 // Test for no method in the pool which should not trigger any warning by
3252 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003253 if (Pos == MethodPool.end())
3254 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003255 ObjCMethodList &MethList =
3256 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3257
3258 // Diagnose finding more than one method in global pool
3259 SmallVector<ObjCMethodDecl *, 4> Methods;
3260 Methods.push_back(BestMethod);
Jonathan Roelofs74411362015-04-28 18:04:44 +00003261 for (ObjCMethodList *ML = &MethList; ML; ML = ML->getNext())
3262 if (ObjCMethodDecl *M = ML->getMethod())
3263 if (!M->isHidden() && M != BestMethod && !M->hasAttr<UnavailableAttr>())
3264 Methods.push_back(M);
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003265 if (Methods.size() > 1)
3266 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass);
3267
Nico Weber2e0c8f72014-12-27 03:58:08 +00003268 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003269}
3270
Sebastian Redl75d8a322010-08-02 23:18:59 +00003271ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003272 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003273 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003274 if (ExternalSource)
3275 ReadMethodPool(Sel);
3276
Sebastian Redl75d8a322010-08-02 23:18:59 +00003277 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003278 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003279 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003280
Douglas Gregor77f49a42013-01-16 18:47:38 +00003281 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003282 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003283 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003284 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003285 if (M->getMethod() && !M->getMethod()->isHidden())
3286 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003287 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003288 return nullptr;
3289}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003290
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003291void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3292 Selector Sel, SourceRange R,
3293 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003294 // We found multiple methods, so we may have to complain.
3295 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003296
Douglas Gregor77f49a42013-01-16 18:47:38 +00003297 // We support a warning which complains about *any* difference in
3298 // method signature.
3299 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003300 receiverIdOrClass &&
3301 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003302 if (strictSelectorMatch) {
3303 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3304 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3305 issueDiagnostic = true;
3306 break;
3307 }
3308 }
3309 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003310
Douglas Gregor77f49a42013-01-16 18:47:38 +00003311 // If we didn't see any strict differences, we won't see any loose
3312 // differences. In ARC, however, we also need to check for loose
3313 // mismatches, because most of them are errors.
3314 if (!strictSelectorMatch ||
3315 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3316 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3317 // This checks if the methods differ in type mismatch.
3318 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3319 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3320 issueDiagnostic = true;
3321 if (getLangOpts().ObjCAutoRefCount)
3322 issueError = true;
3323 break;
3324 }
3325 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003326
Douglas Gregor77f49a42013-01-16 18:47:38 +00003327 if (issueDiagnostic) {
3328 if (issueError)
3329 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3330 else if (strictSelectorMatch)
3331 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3332 else
3333 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003334
Douglas Gregor77f49a42013-01-16 18:47:38 +00003335 Diag(Methods[0]->getLocStart(),
3336 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003337 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003338 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3339 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003340 << Methods[I]->getSourceRange();
3341 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003342 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003343}
3344
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003345ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003346 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3347 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003348 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003349
3350 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003351 for (const ObjCMethodList *Method = &Methods.first; Method;
3352 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003353 if (Method->getMethod() &&
3354 (Method->getMethod()->isDefined() ||
3355 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003356 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003357
3358 for (const ObjCMethodList *Method = &Methods.second; Method;
3359 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003360 if (Method->getMethod() &&
3361 (Method->getMethod()->isDefined() ||
3362 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003363 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003364 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003365}
3366
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003367static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003368HelperSelectorsForTypoCorrection(
3369 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3370 StringRef Typo, const ObjCMethodDecl * Method) {
3371 const unsigned MaxEditDistance = 1;
3372 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003373 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003374
3375 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3376 if (MinPossibleEditDistance > 0 &&
3377 Typo.size() / MinPossibleEditDistance < 1)
3378 return;
3379 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3380 if (EditDistance > MaxEditDistance)
3381 return;
3382 if (EditDistance == BestEditDistance)
3383 BestMethod.push_back(Method);
3384 else if (EditDistance < BestEditDistance) {
3385 BestMethod.clear();
3386 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003387 }
3388}
3389
Fariborz Jahanian75481672013-06-17 17:10:54 +00003390static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3391 QualType ObjectType) {
3392 if (ObjectType.isNull())
3393 return true;
3394 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3395 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003396 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3397 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003398}
3399
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003400const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003401Sema::SelectorsForTypoCorrection(Selector Sel,
3402 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003403 unsigned NumArgs = Sel.getNumArgs();
3404 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003405 bool ObjectIsId = true, ObjectIsClass = true;
3406 if (ObjectType.isNull())
3407 ObjectIsId = ObjectIsClass = false;
3408 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003409 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003410 else if (const ObjCObjectPointerType *ObjCPtr =
3411 ObjectType->getAsObjCInterfacePointerType()) {
3412 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3413 ObjectIsId = ObjectIsClass = false;
3414 }
3415 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3416 ObjectIsClass = false;
3417 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3418 ObjectIsId = false;
3419 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003420 return nullptr;
3421
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003422 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3423 e = MethodPool.end(); b != e; b++) {
3424 // instance methods
3425 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003426 if (M->getMethod() &&
3427 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3428 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003429 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003430 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003431 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003432 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3433 ObjectType))
3434 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003435 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003436 // class methods
3437 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003438 if (M->getMethod() &&
3439 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3440 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003441 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003442 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003443 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003444 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3445 ObjectType))
3446 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003447 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003448 }
3449
3450 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3451 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3452 HelperSelectorsForTypoCorrection(SelectedMethods,
3453 Sel.getAsString(), Methods[i]);
3454 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003455 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003456}
3457
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003458/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003459/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003460/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003461/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003462/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003463void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3464 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003465 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003466 if (Ivar->isInvalidDecl())
3467 continue;
3468 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3469 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3470 if (prevIvar) {
3471 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3472 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3473 Ivar->setInvalidDecl();
3474 }
3475 }
3476 }
3477}
3478
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003479Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3480 switch (CurContext->getDeclKind()) {
3481 case Decl::ObjCInterface:
3482 return Sema::OCK_Interface;
3483 case Decl::ObjCProtocol:
3484 return Sema::OCK_Protocol;
3485 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003486 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003487 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003488 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003489 case Decl::ObjCImplementation:
3490 return Sema::OCK_Implementation;
3491 case Decl::ObjCCategoryImpl:
3492 return Sema::OCK_CategoryImplementation;
3493
3494 default:
3495 return Sema::OCK_None;
3496 }
3497}
3498
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003499// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003500Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003501 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003502 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003503 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003504
3505 assert(AtEnd.isValid() && "Invalid location for '@end'");
3506
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003507 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3508 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian9290ede2009-11-16 18:57:01 +00003509
Mike Stump11289f42009-09-09 15:08:12 +00003510 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003511 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3512 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003513 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003514
Steve Naroff35c62ae2009-01-08 17:28:14 +00003515 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3516 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3517 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3518
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003519 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003520 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003521 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003522
3523 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003524 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003525 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003526 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003527 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003528 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003529 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003530 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003531 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003532 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003533 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003534 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003535 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003536 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003537 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003538 if (!Context.getSourceManager().isInSystemHeader(
3539 Method->getLocation()))
3540 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3541 << Method->getDeclName();
3542 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3543 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003544 InsMap[Method->getSelector()] = Method;
3545 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003546 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003547 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003548 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003549 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003550 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003551 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003552 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003553 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003554 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003555 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003556 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003557 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003558 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003559 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003560 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003561 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003562 if (!Context.getSourceManager().isInSystemHeader(
3563 Method->getLocation()))
3564 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3565 << Method->getDeclName();
3566 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3567 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003568 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003569 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003570 }
3571 }
3572 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003573 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3574 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003575 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003576 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003577 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003578 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003579
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003580 if (C->IsClassExtension()) {
3581 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3582 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003583 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003584 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003585 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003586 if (CDecl->getIdentifier())
3587 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3588 // user-defined setter/getter. It also synthesizes setter/getter methods
3589 // and adds them to the DeclContext and global method pools.
Aaron Ballmand174edf2014-03-13 19:11:50 +00003590 for (auto *I : CDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00003591 ProcessPropertyDecl(I, CDecl);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003592 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003593 }
3594 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003595 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003596 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003597 // Any property declared in a class extension might have user
3598 // declared setter or getter in current class extension or one
3599 // of the other class extensions. Mark them as synthesized as
3600 // property will be synthesized when property with same name is
3601 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003602 for (const auto *Ext : IDecl->visible_extensions()) {
Aaron Ballmand174edf2014-03-13 19:11:50 +00003603 for (const auto *Property : Ext->properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003604 // Skip over properties declared @dynamic
3605 if (const ObjCPropertyImplDecl *PIDecl
3606 = IC->FindPropertyImplDecl(Property->getIdentifier()))
3607 if (PIDecl->getPropertyImplementation()
3608 == ObjCPropertyImplDecl::Dynamic)
3609 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003610
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003611 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003612 if (ObjCMethodDecl *GetterMethod
3613 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003614 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003615 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003616 if (ObjCMethodDecl *SetterMethod
3617 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003618 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003619 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003620 }
3621 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003622 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003623 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003624 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003625 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003626 if (IDecl->hasDesignatedInitializers())
3627 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003628
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003629 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00003630 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003631 // This class has no superclass, so check that it has been marked with
3632 // __attribute((objc_root_class)).
3633 if (!HasRootClassAttr) {
3634 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00003635 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003636 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3637 << IDecl->getIdentifier();
3638 // See if NSObject is in the current scope, and if it is, suggest
3639 // adding " : NSObject " to the class declaration.
3640 NamedDecl *IF = LookupSingleName(TUScope,
3641 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3642 DeclLoc, LookupOrdinaryName);
3643 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3644 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3645 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3646 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3647 } else {
3648 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3649 }
3650 }
3651 } else if (HasRootClassAttr) {
3652 // Complain that only root classes may have this attribute.
3653 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3654 }
3655
John McCall5fb5df92012-06-20 06:18:46 +00003656 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003657 while (IDecl->getSuperClass()) {
3658 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3659 IDecl = IDecl->getSuperClass();
3660 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003661 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003662 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003663 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00003664 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00003665 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003666 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003667
Chris Lattnerda463fe2007-12-12 07:09:47 +00003668 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00003669 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00003670 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003671 if (ObjCCategoryDecl *Cat
3672 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3673 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003674 }
3675 }
3676 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003677 if (isInterfaceDeclKind) {
3678 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003679 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003680 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003681 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3682 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003683 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00003684 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00003685 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003686 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003687 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00003688 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003689
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003690 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003691 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003692 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3693 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003694 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3695 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003696
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00003697 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003698 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003699}
3700
3701
3702/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3703/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00003704static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003705CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00003706 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003707}
3708
Douglas Gregor33823722011-06-11 01:09:30 +00003709/// \brief Check whether the declared result type of the given Objective-C
3710/// method declaration is compatible with the method's class.
3711///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003712static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00003713CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3714 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00003715 QualType ResultType = Method->getReturnType();
3716
Douglas Gregor33823722011-06-11 01:09:30 +00003717 // If an Objective-C method inherits its related result type, then its
3718 // declared result type must be compatible with its own class type. The
3719 // declared result type is compatible if:
3720 if (const ObjCObjectPointerType *ResultObjectType
3721 = ResultType->getAs<ObjCObjectPointerType>()) {
3722 // - it is id or qualified id, or
3723 if (ResultObjectType->isObjCIdType() ||
3724 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003725 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003726
3727 if (CurrentClass) {
3728 if (ObjCInterfaceDecl *ResultClass
3729 = ResultObjectType->getInterfaceDecl()) {
3730 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00003731 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003732 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003733
3734 // - it is a superclass of the method's class type
3735 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003736 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003737 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00003738 } else {
3739 // Any Objective-C pointer type might be acceptable for a protocol
3740 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003741 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00003742 }
3743 }
3744
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003745 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003746}
3747
John McCalld2930c22011-07-22 02:45:48 +00003748namespace {
3749/// A helper class for searching for methods which a particular method
3750/// overrides.
3751class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003752public:
John McCalld2930c22011-07-22 02:45:48 +00003753 Sema &S;
3754 ObjCMethodDecl *Method;
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003755 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00003756 bool Recursive;
3757
3758public:
3759 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
3760 Selector selector = method->getSelector();
3761
3762 // Bypass this search if we've never seen an instance/class method
3763 // with this selector before.
3764 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
3765 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00003766 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00003767 S.ReadMethodPool(selector);
3768
3769 it = S.MethodPool.find(selector);
3770 if (it == S.MethodPool.end())
3771 return;
John McCalld2930c22011-07-22 02:45:48 +00003772 }
3773 ObjCMethodList &list =
3774 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003775 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00003776
3777 ObjCContainerDecl *container
3778 = cast<ObjCContainerDecl>(method->getDeclContext());
3779
3780 // Prevent the search from reaching this container again. This is
3781 // important with categories, which override methods from the
3782 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003783 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
3784 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003785 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
3786 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003787 } else {
3788 searchFromContainer(container);
3789 }
Douglas Gregor33823722011-06-11 01:09:30 +00003790 }
John McCalld2930c22011-07-22 02:45:48 +00003791
Daniel Dunbard6d74c32012-02-29 03:04:05 +00003792 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00003793 iterator begin() const { return Overridden.begin(); }
3794 iterator end() const { return Overridden.end(); }
3795
3796private:
3797 void searchFromContainer(ObjCContainerDecl *container) {
3798 if (container->isInvalidDecl()) return;
3799
3800 switch (container->getDeclKind()) {
3801#define OBJCCONTAINER(type, base) \
3802 case Decl::type: \
3803 searchFrom(cast<type##Decl>(container)); \
3804 break;
3805#define ABSTRACT_DECL(expansion)
3806#define DECL(type, base) \
3807 case Decl::type:
3808#include "clang/AST/DeclNodes.inc"
3809 llvm_unreachable("not an ObjC container!");
3810 }
3811 }
3812
3813 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00003814 if (!protocol->hasDefinition())
3815 return;
3816
John McCalld2930c22011-07-22 02:45:48 +00003817 // A method in a protocol declaration overrides declarations from
3818 // referenced ("parent") protocols.
3819 search(protocol->getReferencedProtocols());
3820 }
3821
3822 void searchFrom(ObjCCategoryDecl *category) {
3823 // A method in a category declaration overrides declarations from
3824 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00003825 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00003826 search(category->getReferencedProtocols());
3827 }
3828
3829 void searchFrom(ObjCCategoryImplDecl *impl) {
3830 // A method in a category definition that has a category
3831 // declaration overrides declarations from the category
3832 // declaration.
3833 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
3834 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00003835 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
3836 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003837
3838 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003839 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
3840 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003841 }
3842 }
3843
3844 void searchFrom(ObjCInterfaceDecl *iface) {
3845 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00003846 if (!iface->hasDefinition())
3847 return;
3848
John McCalld2930c22011-07-22 02:45:48 +00003849 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00003850 for (auto *Cat : iface->known_categories())
3851 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00003852
3853 // - the super class, and
3854 if (ObjCInterfaceDecl *super = iface->getSuperClass())
3855 search(super);
3856
3857 // - any referenced protocols.
3858 search(iface->getReferencedProtocols());
3859 }
3860
3861 void searchFrom(ObjCImplementationDecl *impl) {
3862 // A method in a class implementation overrides declarations from
3863 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00003864 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
3865 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00003866 }
3867
3868
3869 void search(const ObjCProtocolList &protocols) {
3870 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
3871 i != e; ++i)
3872 search(*i);
3873 }
3874
3875 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00003876 // Check for a method in this container which matches this selector.
3877 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00003878 Method->isInstanceMethod(),
3879 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00003880
3881 // If we find one, record it and bail out.
3882 if (meth) {
3883 Overridden.insert(meth);
3884 return;
3885 }
3886
3887 // Otherwise, search for methods that a hypothetical method here
3888 // would have overridden.
3889
3890 // Note that we're now in a recursive case.
3891 Recursive = true;
3892
3893 searchFromContainer(container);
3894 }
3895};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003896}
Douglas Gregor33823722011-06-11 01:09:30 +00003897
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003898void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
3899 ObjCInterfaceDecl *CurrentClass,
3900 ResultTypeCompatibilityKind RTC) {
3901 // Search for overridden methods and merge information down from them.
3902 OverrideSearch overrides(*this, ObjCMethod);
3903 // Keep track if the method overrides any method in the class's base classes,
3904 // its protocols, or its categories' protocols; we will keep that info
3905 // in the ObjCMethodDecl.
3906 // For this info, a method in an implementation is not considered as
3907 // overriding the same method in the interface or its categories.
3908 bool hasOverriddenMethodsInBaseOrProtocol = false;
3909 for (OverrideSearch::iterator
3910 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
3911 ObjCMethodDecl *overridden = *i;
3912
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003913 if (!hasOverriddenMethodsInBaseOrProtocol) {
3914 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3915 CurrentClass != overridden->getClassInterface() ||
3916 overridden->isOverriding()) {
3917 hasOverriddenMethodsInBaseOrProtocol = true;
3918
3919 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3920 // OverrideSearch will return as "overridden" the same method in the
3921 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3922 // check whether a category of a base class introduced a method with the
3923 // same selector, after the interface method declaration.
3924 // To avoid unnecessary lookups in the majority of cases, we use the
3925 // extra info bits in GlobalMethodPool to check whether there were any
3926 // category methods with this selector.
3927 GlobalMethodPool::iterator It =
3928 MethodPool.find(ObjCMethod->getSelector());
3929 if (It != MethodPool.end()) {
3930 ObjCMethodList &List =
3931 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3932 unsigned CategCount = List.getBits();
3933 if (CategCount > 0) {
3934 // If the method is in a category we'll do lookup if there were at
3935 // least 2 category methods recorded, otherwise only one will do.
3936 if (CategCount > 1 ||
3937 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3938 OverrideSearch overrides(*this, overridden);
3939 for (OverrideSearch::iterator
3940 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3941 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003942 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3943 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00003944 hasOverriddenMethodsInBaseOrProtocol = true;
3945 overridden->setOverriding(true);
3946 break;
3947 }
3948 }
3949 }
3950 }
3951 }
3952 }
3953 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003954
3955 // Propagate down the 'related result type' bit from overridden methods.
3956 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3957 ObjCMethod->SetRelatedResultType();
3958
3959 // Then merge the declarations.
3960 mergeObjCMethodDecls(ObjCMethod, overridden);
3961
3962 if (ObjCMethod->isImplicit() && overridden->isImplicit())
3963 continue; // Conflicting properties are detected elsewhere.
3964
3965 // Check for overriding methods
3966 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3967 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3968 CheckConflictingOverridingMethod(ObjCMethod, overridden,
3969 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3970
3971 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00003972 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3973 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003974 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3975 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003976 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3977 PrevE = overridden->param_end();
3978 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003979 assert(PrevI != overridden->param_end() && "Param mismatch");
3980 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3981 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3982 // If type of argument of method in this class does not match its
3983 // respective argument type in the super class method, issue warning;
3984 if (!Context.typesAreCompatible(T1, T2)) {
3985 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3986 << T1 << T2;
3987 Diag(overridden->getLocation(), diag::note_previous_declaration);
3988 break;
3989 }
3990 }
3991 }
3992 }
3993
3994 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3995}
3996
Douglas Gregor813a0662015-06-19 18:14:38 +00003997/// Merge type nullability from for a redeclaration of the same entity,
3998/// producing the updated type of the redeclared entity.
3999static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4000 QualType type,
4001 bool usesCSKeyword,
4002 SourceLocation prevLoc,
4003 QualType prevType,
4004 bool prevUsesCSKeyword) {
4005 // Determine the nullability of both types.
4006 auto nullability = type->getNullability(S.Context);
4007 auto prevNullability = prevType->getNullability(S.Context);
4008
4009 // Easy case: both have nullability.
4010 if (nullability.hasValue() == prevNullability.hasValue()) {
4011 // Neither has nullability; continue.
4012 if (!nullability)
4013 return type;
4014
4015 // The nullabilities are equivalent; do nothing.
4016 if (*nullability == *prevNullability)
4017 return type;
4018
4019 // Complain about mismatched nullability.
4020 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004021 << DiagNullabilityKind(*nullability, usesCSKeyword)
4022 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004023 return type;
4024 }
4025
4026 // If it's the redeclaration that has nullability, don't change anything.
4027 if (nullability)
4028 return type;
4029
4030 // Otherwise, provide the result with the same nullability.
4031 return S.Context.getAttributedType(
4032 AttributedType::getNullabilityAttrKind(*prevNullability),
4033 type, type);
4034}
4035
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004036/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004037/// (or a category/extension) into the corresponding method in the
4038/// @implementation (for a class or category).
4039static void mergeInterfaceMethodToImpl(Sema &S,
4040 ObjCMethodDecl *method,
4041 ObjCMethodDecl *prevMethod) {
4042 // Merge the objc_requires_super attribute.
4043 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4044 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4045 // merge the attribute into implementation.
4046 method->addAttr(
4047 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4048 method->getLocation()));
4049 }
4050
4051 // Merge nullability of the result type.
4052 QualType newReturnType
4053 = mergeTypeNullabilityForRedecl(
4054 S, method->getReturnTypeSourceRange().getBegin(),
4055 method->getReturnType(),
4056 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4057 prevMethod->getReturnTypeSourceRange().getBegin(),
4058 prevMethod->getReturnType(),
4059 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4060 method->setReturnType(newReturnType);
4061
4062 // Handle each of the parameters.
4063 unsigned numParams = method->param_size();
4064 unsigned numPrevParams = prevMethod->param_size();
4065 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4066 ParmVarDecl *param = method->param_begin()[i];
4067 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4068
4069 // Merge nullability.
4070 QualType newParamType
4071 = mergeTypeNullabilityForRedecl(
4072 S, param->getLocation(), param->getType(),
4073 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4074 prevParam->getLocation(), prevParam->getType(),
4075 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4076 param->setType(newParamType);
4077 }
4078}
4079
John McCall48871652010-08-21 09:40:31 +00004080Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004081 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004082 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004083 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004084 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004085 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004086 Selector Sel,
4087 // optional arguments. The number of types/arguments is obtained
4088 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004089 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004090 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004091 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004092 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004093 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004094 if (!CurContext->isObjCContainer()) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004095 Diag(MethodLoc, diag::error_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004096 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004097 }
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004098 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4099 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004100 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004101
Douglas Gregorbab8a962011-09-08 01:46:34 +00004102 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004103 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004104 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004105 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004106
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004107 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004108 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004109
Douglas Gregor813a0662015-06-19 18:14:38 +00004110 QualType bareResultType = resultDeclType;
4111 (void)AttributedType::stripOuterNullability(bareResultType);
4112 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004113 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004114 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004115 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004116 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004117 }
Mike Stump11289f42009-09-09 15:08:12 +00004118
Alp Toker314cc812014-01-25 16:55:45 +00004119 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4120 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4121 MethodType == tok::minus, isVariadic,
4122 /*isPropertyAccessor=*/false,
4123 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4124 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4125 : ObjCMethodDecl::Required,
4126 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004127
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004128 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004129
Chris Lattner23b0faf2009-04-11 19:42:43 +00004130 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004131 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004132 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004133
David Blaikie7d170102013-05-15 07:37:26 +00004134 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004135 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004136 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004137 } else {
John McCall856bbea2009-10-23 21:48:59 +00004138 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004139 }
Mike Stump11289f42009-09-09 15:08:12 +00004140
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004141 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4142 LookupOrdinaryName, ForRedeclaration);
4143 LookupName(R, S);
4144 if (R.isSingleResult()) {
4145 NamedDecl *PrevDecl = R.getFoundDecl();
4146 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004147 Diag(ArgInfo[i].NameLoc,
4148 (MethodDefinition ? diag::warn_method_param_redefinition
4149 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004150 << ArgInfo[i].Name;
4151 Diag(PrevDecl->getLocation(),
4152 diag::note_previous_declaration);
4153 }
4154 }
4155
Abramo Bagnaradff19302011-03-08 08:55:46 +00004156 SourceLocation StartLoc = DI
4157 ? DI->getTypeLoc().getBeginLoc()
4158 : ArgInfo[i].NameLoc;
4159
John McCalld44f4d72011-04-23 02:46:06 +00004160 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4161 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004162 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004163
John McCall82490832011-05-02 00:30:12 +00004164 Param->setObjCMethodScopeInfo(i);
4165
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004166 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004167 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004168
Chris Lattner9713a1c2009-04-11 19:34:56 +00004169 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004170 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Mike Stump11289f42009-09-09 15:08:12 +00004171
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004172 if (Param->hasAttr<BlocksAttr>()) {
4173 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4174 Param->setInvalidDecl();
4175 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004176 S->AddDecl(Param);
4177 IdResolver.AddDecl(Param);
4178
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004179 Params.push_back(Param);
4180 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004181
Fariborz Jahanian60462092010-04-08 00:30:06 +00004182 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004183 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004184 QualType ArgType = Param->getType();
4185 if (ArgType.isNull())
4186 ArgType = Context.getObjCIdType();
4187 else
4188 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004189 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004190
Fariborz Jahanian60462092010-04-08 00:30:06 +00004191 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004192 Params.push_back(Param);
4193 }
4194
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004195 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004196 ObjCMethod->setObjCDeclQualifier(
4197 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004198
4199 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004200 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Mike Stump11289f42009-09-09 15:08:12 +00004201
Douglas Gregor87e92752010-12-21 17:34:17 +00004202 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004203 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004204 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004205 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004206 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4207 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004208 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004209 PrevMethod = ImpDecl->getClassMethod(Sel);
4210 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004211 }
Douglas Gregor33823722011-06-11 01:09:30 +00004212
Douglas Gregor813a0662015-06-19 18:14:38 +00004213 // Merge information from the @interface declaration into the
4214 // @implementation.
4215 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4216 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4217 ObjCMethod->isInstanceMethod())) {
4218 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4219
4220 // Warn about defining -dealloc in a category.
4221 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4222 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4223 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4224 << ObjCMethod->getDeclName();
4225 }
4226 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004227 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004228 } else {
4229 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004230 }
John McCalld2930c22011-07-22 02:45:48 +00004231
Chris Lattnerda463fe2007-12-12 07:09:47 +00004232 if (PrevMethod) {
4233 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004234 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004235 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004236 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004237 ObjCMethod->setInvalidDecl();
4238 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004239 }
John McCall28a6aea2009-11-04 02:18:39 +00004240
Douglas Gregor33823722011-06-11 01:09:30 +00004241 // If this Objective-C method does not have a related result type, but we
4242 // are allowed to infer related result types, try to do so based on the
4243 // method family.
4244 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4245 if (!CurrentClass) {
4246 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4247 CurrentClass = Cat->getClassInterface();
4248 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4249 CurrentClass = Impl->getClassInterface();
4250 else if (ObjCCategoryImplDecl *CatImpl
4251 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4252 CurrentClass = CatImpl->getClassInterface();
4253 }
John McCalld2930c22011-07-22 02:45:48 +00004254
Douglas Gregorbab8a962011-09-08 01:46:34 +00004255 ResultTypeCompatibilityKind RTC
4256 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004257
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004258 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004259
John McCall31168b02011-06-15 23:02:42 +00004260 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004261 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004262 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004263
Douglas Gregorbab8a962011-09-08 01:46:34 +00004264 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004265 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004266 !ObjCMethod->hasRelatedResultType() &&
4267 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004268 bool InferRelatedResultType = false;
4269 switch (ObjCMethod->getMethodFamily()) {
4270 case OMF_None:
4271 case OMF_copy:
4272 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004273 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004274 case OMF_mutableCopy:
4275 case OMF_release:
4276 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004277 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004278 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004279 break;
4280
4281 case OMF_alloc:
4282 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004283 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004284 break;
4285
4286 case OMF_init:
4287 case OMF_autorelease:
4288 case OMF_retain:
4289 case OMF_self:
4290 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4291 break;
4292 }
4293
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004294 if (InferRelatedResultType &&
4295 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004296 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004297 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004298
4299 ActOnDocumentableDecl(ObjCMethod);
4300
John McCall48871652010-08-21 09:40:31 +00004301 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004302}
4303
Chris Lattner438e5012008-12-17 07:13:27 +00004304bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004305 // Following is also an error. But it is caused by a missing @end
4306 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004307 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004308 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004309
4310 // If we switched context to translation unit while we are still lexically in
4311 // an objc container, it means the parser missed emitting an error.
4312 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4313 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004314
Anders Carlssona6b508a2008-11-04 16:57:32 +00004315 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4316 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004317
Anders Carlssona6b508a2008-11-04 16:57:32 +00004318 return true;
4319}
Chris Lattner438e5012008-12-17 07:13:27 +00004320
James Dennett634962f2012-06-14 21:40:34 +00004321/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004322/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004323void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004324 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004325 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004326 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004327 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004328 if (!Class) {
4329 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4330 return;
4331 }
John McCall5fb5df92012-06-20 06:18:46 +00004332 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004333 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4334 return;
4335 }
Mike Stump11289f42009-09-09 15:08:12 +00004336
Chris Lattner438e5012008-12-17 07:13:27 +00004337 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004338 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004339 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004340 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004341 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004342 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCall48871652010-08-21 09:40:31 +00004343 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004344 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4345 /*FIXME: StartL=*/ID->getLocation(),
4346 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004347 ID->getIdentifier(), ID->getType(),
4348 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004349 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004350 }
Mike Stump11289f42009-09-09 15:08:12 +00004351
Chris Lattner438e5012008-12-17 07:13:27 +00004352 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004353 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004354 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004355 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004356 if (getLangOpts().CPlusPlus)
Chris Lattner438e5012008-12-17 07:13:27 +00004357 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCall48871652010-08-21 09:40:31 +00004358 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004359 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004360 }
4361}
4362
Douglas Gregorf3564192010-04-26 17:32:49 +00004363/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004364VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4365 SourceLocation StartLoc,
4366 SourceLocation IdLoc,
4367 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004368 bool Invalid) {
4369 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4370 // duration shall not be qualified by an address-space qualifier."
4371 // Since all parameters have automatic store duration, they can not have
4372 // an address space.
4373 if (T.getAddressSpace() != 0) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004374 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004375 Invalid = true;
4376 }
4377
4378 // An @catch parameter must be an unqualified object pointer type;
4379 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4380 if (Invalid) {
4381 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004382 } else if (T->isDependentType()) {
4383 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004384 } else if (!T->isObjCObjectPointerType()) {
4385 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004386 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004387 } else if (T->isObjCQualifiedIdType()) {
4388 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004389 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004390 }
4391
Abramo Bagnaradff19302011-03-08 08:55:46 +00004392 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004393 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004394 New->setExceptionVariable(true);
4395
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004396 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004397 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004398 Invalid = true;
4399
Douglas Gregorf3564192010-04-26 17:32:49 +00004400 if (Invalid)
4401 New->setInvalidDecl();
4402 return New;
4403}
4404
John McCall48871652010-08-21 09:40:31 +00004405Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004406 const DeclSpec &DS = D.getDeclSpec();
4407
4408 // We allow the "register" storage class on exception variables because
4409 // GCC did, but we drop it completely. Any other storage class is an error.
4410 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4411 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4412 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004413 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004414 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004415 << DeclSpec::getSpecifierName(SCS);
4416 }
4417 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4418 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4419 diag::err_invalid_thread)
4420 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004421 D.getMutableDeclSpec().ClearStorageClassSpecs();
4422
Richard Smithb1402ae2013-03-18 22:52:47 +00004423 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004424
4425 // Check that there are no default arguments inside the type of this
4426 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004427 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004428 CheckExtraCXXDefaultArguments(D);
4429
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004430 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004431 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004432
Abramo Bagnaradff19302011-03-08 08:55:46 +00004433 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4434 D.getSourceRange().getBegin(),
4435 D.getIdentifierLoc(),
4436 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004437 D.isInvalidType());
4438
4439 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4440 if (D.getCXXScopeSpec().isSet()) {
4441 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4442 << D.getCXXScopeSpec().getRange();
4443 New->setInvalidDecl();
4444 }
4445
4446 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004447 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004448 if (D.getIdentifier())
4449 IdResolver.AddDecl(New);
4450
4451 ProcessDeclAttributes(S, New, D);
4452
4453 if (New->hasAttr<BlocksAttr>())
4454 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004455 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004456}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004457
4458/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004459/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004460void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004461 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004462 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4463 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004464 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004465 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004466 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004467 }
4468}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004469
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004470void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004471 // Load referenced selectors from the external source.
4472 if (ExternalSource) {
4473 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4474 ExternalSource->ReadReferencedSelectors(Sels);
4475 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4476 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4477 }
4478
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004479 // Warning will be issued only when selector table is
4480 // generated (which means there is at lease one implementation
4481 // in the TU). This is to match gcc's behavior.
4482 if (ReferencedSelectors.empty() ||
4483 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004484 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004485 for (auto &SelectorAndLocation : ReferencedSelectors) {
4486 Selector Sel = SelectorAndLocation.first;
4487 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004488 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004489 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004490 }
4491 return;
4492}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004493
4494ObjCIvarDecl *
4495Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4496 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004497 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004498 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004499 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4500 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004501 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004502 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4503 /*shallowCategoryLookup=*/false,
4504 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004505 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004506 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004507 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004508 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4509 // property backing ivar must belong to property's class
4510 // or be a private ivar in class's implementation.
4511 // FIXME. fix the const-ness issue.
4512 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4513 IV->getIdentifier());
4514 return IV;
4515 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004516 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004517}
4518
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004519namespace {
4520 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4521 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004522 class UnusedBackingIvarChecker :
4523 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004524 public:
4525 Sema &S;
4526 const ObjCMethodDecl *Method;
4527 const ObjCIvarDecl *IvarD;
4528 bool AccessedIvar;
4529 bool InvokedSelfMethod;
4530
4531 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4532 const ObjCIvarDecl *IvarD)
4533 : S(S), Method(Method), IvarD(IvarD),
4534 AccessedIvar(false), InvokedSelfMethod(false) {
4535 assert(IvarD);
4536 }
4537
4538 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4539 if (E->getDecl() == IvarD) {
4540 AccessedIvar = true;
4541 return false;
4542 }
4543 return true;
4544 }
4545
4546 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4547 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4548 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4549 InvokedSelfMethod = true;
4550 }
4551 return true;
4552 }
4553 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004554}
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004555
4556void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4557 const ObjCImplementationDecl *ImplD) {
4558 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004559 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004560
Aaron Ballmanf26acce2014-03-13 19:50:17 +00004561 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004562 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4563 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004564 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004565 continue;
4566
4567 const ObjCPropertyDecl *PDecl;
4568 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4569 if (!IV)
4570 continue;
4571
4572 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4573 Checker.TraverseStmt(CurMethod->getBody());
4574 if (Checker.AccessedIvar)
4575 continue;
4576
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004577 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004578 // implementation makes a self call. This is to prevent false positive in
4579 // cases where the ivar is accessed by another method that the accessor
4580 // delegates to.
4581 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00004582 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004583 Diag(PDecl->getLocation(), diag::note_property_declare);
4584 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004585 }
4586}