blob: fc9fdb1afaefb5b8cbbbf6ee743363029d6d4bff [file] [log] [blame]
Chris Lattner4d391482007-12-12 07:09:47 +00001//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-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 Lattner4d391482007-12-12 07:09:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCallf85e1932011-06-15 23:02:42 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070018#include "clang/AST/DataRecursiveASTVisitor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000019#include "clang/AST/DeclObjC.h"
Steve Naroffca331292009-03-03 14:49:36 +000020#include "clang/AST/Expr.h"
John McCallf85e1932011-06-15 23:02:42 +000021#include "clang/AST/ExprObjC.h"
John McCallf85e1932011-06-15 23:02:42 +000022#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
24#include "clang/Sema/ExternalSemaSource.h"
25#include "clang/Sema/Lookup.h"
26#include "clang/Sema/Scope.h"
27#include "clang/Sema/ScopeInfo.h"
John McCall50df6ae2010-08-25 07:03:20 +000028#include "llvm/ADT/DenseSet.h"
29
Chris Lattner4d391482007-12-12 07:09:47 +000030using namespace clang;
31
John McCallf85e1932011-06-15 23:02:42 +000032/// Check whether the given method, which must be in the 'init'
33/// family, is a valid member of that family.
34///
35/// \param receiverTypeIfCall - if null, check this as if declaring it;
36/// if non-null, check this as if making a call to it with the given
37/// receiver type
38///
39/// \return true to indicate that there was an error and appropriate
40/// actions were taken
41bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
44
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
48
49 // We ignore protocols here. Should we? What about Class?
50
Stephen Hines651f13c2014-04-23 16:59:28 -070051 const ObjCObjectType *result =
52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCallf85e1932011-06-15 23:02:42 +000053
54 if (result->isObjCId()) {
55 return false;
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
58 } else {
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
61
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
Douglas Gregor7723fec2011-12-15 20:29:51 +000064 if (!resultClass->hasDefinition()) {
John McCallf85e1932011-06-15 23:02:42 +000065 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
67 return false;
68
69 // Otherwise, we try to compare class types.
70 } else {
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
Stephen Hines6bcf27b2014-05-29 04:14:42 -070073 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCallf85e1932011-06-15 23:02:42 +000074 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
76 return false;
77
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79 ->getInterfaceDecl();
80
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
83 } else {
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
86 }
87
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
91 return false;
92 }
93 }
94
95 SourceLocation loc = method->getLocation();
96
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700100 method->addAttr(UnavailableAttr::CreateImplicit(Context,
101 "init method returns a type unrelated to its receiver type",
102 loc));
John McCallf85e1932011-06-15 23:02:42 +0000103 return true;
104 }
105
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
109 return true;
110}
111
Fariborz Jahanian3240fe32011-09-27 22:35:36 +0000112void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregorf4d918f2013-01-15 22:43:08 +0000113 const ObjCMethodDecl *Overridden) {
Douglas Gregor926df6c2011-06-11 01:09:30 +0000114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
Stephen Hines651f13c2014-04-23 16:59:28 -0700120 QualType ResultType = NewMethod->getReturnType();
Douglas Gregor926df6c2011-06-11 01:09:30 +0000121 SourceRange ResultTypeRange;
Stephen Hines651f13c2014-04-23 16:59:28 -0700122 if (const TypeSourceInfo *ResultTypeInfo =
123 NewMethod->getReturnTypeSourceInfo())
Douglas Gregor926df6c2011-06-11 01:09:30 +0000124 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
125
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 Gregore97179c2011-09-08 01:46:34 +0000153 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
154 Diag(Overridden->getLocation(),
John McCall7cca8212013-03-19 07:04:25 +0000155 diag::note_related_result_type_family)
156 << /*overridden method*/ 0
Douglas Gregore97179c2011-09-08 01:46:34 +0000157 << Family;
158 else
159 Diag(Overridden->getLocation(),
160 diag::note_related_result_type_overridden);
Douglas Gregor926df6c2011-06-11 01:09:30 +0000161 }
David Blaikie4e4d0842012-03-11 07:00:24 +0000162 if (getLangOpts().ObjCAutoRefCount) {
Fariborz Jahanian3240fe32011-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 Gregor0a4a23a2012-05-17 23:13:29 +0000177 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
178 oe = Overridden->param_end();
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000179 for (ObjCMethodDecl::param_iterator
180 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +0000181 ni != ne && oi != oe; ++ni, ++oi) {
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +0000182 const ParmVarDecl *oldDecl = (*oi);
Fariborz Jahanian3240fe32011-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 Gregor926df6c2011-06-11 01:09:30 +0000193}
194
John McCallf85e1932011-06-15 23:02:42 +0000195/// \brief Check a method declaration for compatibility with the Objective-C
196/// ARC conventions.
John McCallb8463812013-04-04 01:38:37 +0000197bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCallf85e1932011-06-15 23:02:42 +0000198 ObjCMethodFamily family = method->getMethodFamily();
199 switch (family) {
200 case OMF_None:
Nico Weber80cb6e62011-08-28 22:35:17 +0000201 case OMF_finalize:
John McCallf85e1932011-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:
John McCall6c2c2502011-07-22 02:45:48 +0000207 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000208 return false;
209
Fariborz Jahanian1b0a13e2012-07-30 20:52:48 +0000210 case OMF_dealloc:
Stephen Hines651f13c2014-04-23 16:59:28 -0700211 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Fariborz Jahanian1b0a13e2012-07-30 20:52:48 +0000212 SourceRange ResultTypeRange;
Stephen Hines651f13c2014-04-23 16:59:28 -0700213 if (const TypeSourceInfo *ResultTypeInfo =
214 method->getReturnTypeSourceInfo())
Fariborz Jahanian1b0a13e2012-07-30 20:52:48 +0000215 ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
216 if (ResultTypeRange.isInvalid())
Stephen Hines651f13c2014-04-23 16:59:28 -0700217 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
218 << method->getReturnType()
219 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanian1b0a13e2012-07-30 20:52:48 +0000220 else
Stephen Hines651f13c2014-04-23 16:59:28 -0700221 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
222 << method->getReturnType()
223 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanian1b0a13e2012-07-30 20:52:48 +0000224 return true;
225 }
226 return false;
227
John McCallf85e1932011-06-15 23:02:42 +0000228 case OMF_init:
229 // If the method doesn't obey the init rules, don't bother annotating it.
John McCallb8463812013-04-04 01:38:37 +0000230 if (checkInitMethod(method, QualType()))
John McCallf85e1932011-06-15 23:02:42 +0000231 return true;
232
Stephen Hines651f13c2014-04-23 16:59:28 -0700233 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCallf85e1932011-06-15 23:02:42 +0000234
235 // Don't add a second copy of this attribute, but otherwise don't
236 // let it be suppressed.
237 if (method->hasAttr<NSReturnsRetainedAttr>())
238 return false;
239 break;
240
241 case OMF_alloc:
242 case OMF_copy:
243 case OMF_mutableCopy:
244 case OMF_new:
245 if (method->hasAttr<NSReturnsRetainedAttr>() ||
246 method->hasAttr<NSReturnsNotRetainedAttr>() ||
247 method->hasAttr<NSReturnsAutoreleasedAttr>())
248 return false;
249 break;
250 }
251
Stephen Hines651f13c2014-04-23 16:59:28 -0700252 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCallf85e1932011-06-15 23:02:42 +0000253 return false;
254}
255
Fariborz Jahanian5ac96d52011-02-15 17:49:58 +0000256static void DiagnoseObjCImplementedDeprecations(Sema &S,
257 NamedDecl *ND,
258 SourceLocation ImplLoc,
259 int select) {
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000260 if (ND && ND->isDeprecated()) {
Fariborz Jahanian98d810e2011-02-16 00:30:31 +0000261 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
Fariborz Jahanian5ac96d52011-02-15 17:49:58 +0000262 if (select == 0)
Ted Kremenek3306ec12012-02-27 22:55:11 +0000263 S.Diag(ND->getLocation(), diag::note_method_declared_at)
264 << ND->getDeclName();
Fariborz Jahanian5ac96d52011-02-15 17:49:58 +0000265 else
266 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
267 }
268}
269
Fariborz Jahanian140ab232011-08-31 17:37:55 +0000270/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
271/// pool.
272void Sema::AddAnyMethodToGlobalPool(Decl *D) {
273 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
274
275 // If we don't have a valid method decl, simply return.
276 if (!MDecl)
277 return;
278 if (MDecl->isInstanceMethod())
279 AddInstanceMethodToGlobalPool(MDecl, true);
280 else
281 AddFactoryMethodToGlobalPool(MDecl, true);
282}
283
Fariborz Jahaniana1a32f72012-09-13 18:53:14 +0000284/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
285/// has explicit ownership attribute; false otherwise.
286static bool
287HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
288 QualType T = Param->getType();
289
Fariborz Jahaniana1a32f72012-09-13 18:53:14 +0000290 if (const PointerType *PT = T->getAs<PointerType>()) {
291 T = PT->getPointeeType();
292 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
293 T = RT->getPointeeType();
294 } else {
295 return true;
296 }
297
298 // If we have a lifetime qualifier, but it's local, we must have
299 // inferred it. So, it is implicit.
300 return !T.getLocalQualifiers().hasObjCLifetime();
301}
302
Fariborz Jahanian8c6cb462012-08-08 23:41:08 +0000303/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
304/// and user declared, in the method definition's AST.
305void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700306 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCalld226f652010-08-21 09:40:31 +0000307 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian6c89eaf2012-07-02 23:37:09 +0000308
Steve Naroff394f3f42008-07-25 17:57:26 +0000309 // If we don't have a valid method decl, simply return.
310 if (!MDecl)
311 return;
Steve Naroffa56f6162007-12-18 01:30:32 +0000312
Chris Lattner4d391482007-12-12 07:09:47 +0000313 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor44b43212008-12-11 16:49:14 +0000314 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9ea9bdb2010-03-01 23:15:13 +0000315 PushFunctionScope();
316
Chris Lattner4d391482007-12-12 07:09:47 +0000317 // Create Decl objects for each parameter, entrring them in the scope for
318 // binding to their use.
Chris Lattner4d391482007-12-12 07:09:47 +0000319
320 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanianfef30b52008-12-09 20:23:04 +0000321 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Daniel Dunbar451318c2008-08-26 06:07:48 +0000323 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
324 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattner04421082008-04-08 04:40:51 +0000325
Reid Kleckner8c0501c2013-06-24 14:38:26 +0000326 // The ObjC parser requires parameter names so there's no need to check.
327 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
328 /*CheckParameterNames=*/false);
329
Chris Lattner8123a952008-04-10 02:22:51 +0000330 // Introduce all of the other parameters into this scope.
Stephen Hines651f13c2014-04-23 16:59:28 -0700331 for (auto *Param : MDecl->params()) {
Fariborz Jahanian23c01042010-09-17 22:07:07 +0000332 if (!Param->isInvalidDecl() &&
Fariborz Jahaniana1a32f72012-09-13 18:53:14 +0000333 getLangOpts().ObjCAutoRefCount &&
334 !HasExplicitOwnershipAttr(*this, Param))
335 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
336 Param->getType();
Fariborz Jahanian918546c2012-08-30 23:56:02 +0000337
Stephen Hines651f13c2014-04-23 16:59:28 -0700338 if (Param->getIdentifier())
339 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanian23c01042010-09-17 22:07:07 +0000340 }
John McCallf85e1932011-06-15 23:02:42 +0000341
342 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikie4e4d0842012-03-11 07:00:24 +0000343 if (getLangOpts().ObjCAutoRefCount) {
John McCallf85e1932011-06-15 23:02:42 +0000344 switch (MDecl->getMethodFamily()) {
345 case OMF_retain:
346 case OMF_retainCount:
347 case OMF_release:
348 case OMF_autorelease:
349 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanianb8ed0712013-05-16 19:08:44 +0000350 << 0 << MDecl->getSelector();
John McCallf85e1932011-06-15 23:02:42 +0000351 break;
352
353 case OMF_None:
354 case OMF_dealloc:
Nico Weber80cb6e62011-08-28 22:35:17 +0000355 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +0000356 case OMF_alloc:
357 case OMF_init:
358 case OMF_mutableCopy:
359 case OMF_copy:
360 case OMF_new:
361 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +0000362 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +0000363 break;
364 }
365 }
366
Nico Weber9a1ecf02011-08-22 17:25:57 +0000367 // Warn on deprecated methods under -Wdeprecated-implementations,
368 // and prepare for warning on missing super calls.
369 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian84101132012-09-07 23:46:23 +0000370 ObjCMethodDecl *IMD =
371 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
372
Fariborz Jahanian5fa66762012-11-17 20:53:53 +0000373 if (IMD) {
374 ObjCImplDecl *ImplDeclOfMethodDef =
375 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
376 ObjCContainerDecl *ContDeclOfMethodDecl =
377 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700378 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahanian5fa66762012-11-17 20:53:53 +0000379 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
380 ImplDeclOfMethodDecl = OID->getImplementation();
Stephen Hines651f13c2014-04-23 16:59:28 -0700381 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
382 if (CD->IsClassExtension()) {
383 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
384 ImplDeclOfMethodDecl = OID->getImplementation();
385 } else
386 ImplDeclOfMethodDecl = CD->getImplementation();
387 }
Fariborz Jahanian5fa66762012-11-17 20:53:53 +0000388 // No need to issue deprecated warning if deprecated mehod in class/category
389 // is being implemented in its own implementation (no overriding is involved).
390 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
391 DiagnoseObjCImplementedDeprecations(*this,
Fariborz Jahanian5ac96d52011-02-15 17:49:58 +0000392 dyn_cast<NamedDecl>(IMD),
393 MDecl->getLocation(), 0);
Fariborz Jahanian5fa66762012-11-17 20:53:53 +0000394 }
Nico Weber9a1ecf02011-08-22 17:25:57 +0000395
Stephen Hines651f13c2014-04-23 16:59:28 -0700396 if (MDecl->getMethodFamily() == OMF_init) {
397 if (MDecl->isDesignatedInitializerForTheInterface()) {
398 getCurFunction()->ObjCIsDesignatedInit = true;
399 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700400 IC->getSuperClass() != nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -0700401 } else if (IC->hasDesignatedInitializers()) {
402 getCurFunction()->ObjCIsSecondaryInit = true;
403 getCurFunction()->ObjCWarnForNoInitDelegation = true;
404 }
405 }
406
Nico Weber80cb6e62011-08-28 22:35:17 +0000407 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber9a1ecf02011-08-22 17:25:57 +0000408 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
409 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
410 // Only do this if the current class actually has a superclass.
Jordan Rose41f3f3a2013-03-05 01:27:54 +0000411 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose535a5d02012-10-19 16:05:26 +0000412 ObjCMethodFamily Family = MDecl->getMethodFamily();
413 if (Family == OMF_dealloc) {
414 if (!(getLangOpts().ObjCAutoRefCount ||
415 getLangOpts().getGC() == LangOptions::GCOnly))
416 getCurFunction()->ObjCShouldCallSuper = true;
417
418 } else if (Family == OMF_finalize) {
419 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
420 getCurFunction()->ObjCShouldCallSuper = true;
421
Fariborz Jahanian2b610392013-11-05 00:28:21 +0000422 } else {
Jordan Rose535a5d02012-10-19 16:05:26 +0000423 const ObjCMethodDecl *SuperMethod =
Jordan Rose41f3f3a2013-03-05 01:27:54 +0000424 SuperClass->lookupMethod(MDecl->getSelector(),
425 MDecl->isInstanceMethod());
Jordan Rose535a5d02012-10-19 16:05:26 +0000426 getCurFunction()->ObjCShouldCallSuper =
427 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahanian6f938602012-09-10 18:04:25 +0000428 }
Nico Weber80cb6e62011-08-28 22:35:17 +0000429 }
Nico Weber9a1ecf02011-08-22 17:25:57 +0000430 }
Chris Lattner4d391482007-12-12 07:09:47 +0000431}
432
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000433namespace {
434
435// Callback to only accept typo corrections that are Objective-C classes.
436// If an ObjCInterfaceDecl* is given to the constructor, then the validation
437// function will reject corrections to that class.
438class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
439 public:
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700440 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000441 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
442 : CurrentIDecl(IDecl) {}
443
Stephen Hines651f13c2014-04-23 16:59:28 -0700444 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000445 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
446 return ID && !declaresSameEntity(ID, CurrentIDecl);
447 }
448
449 private:
450 ObjCInterfaceDecl *CurrentIDecl;
451};
452
453}
454
John McCalld226f652010-08-21 09:40:31 +0000455Decl *Sema::
Chris Lattner7caeabd2008-07-21 22:17:28 +0000456ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
457 IdentifierInfo *ClassName, SourceLocation ClassLoc,
458 IdentifierInfo *SuperName, SourceLocation SuperLoc,
John McCalld226f652010-08-21 09:40:31 +0000459 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor18df52b2010-01-16 15:02:53 +0000460 const SourceLocation *ProtoLocs,
Chris Lattner7caeabd2008-07-21 22:17:28 +0000461 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattner4d391482007-12-12 07:09:47 +0000462 assert(ClassName && "Missing class identifier");
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Chris Lattner4d391482007-12-12 07:09:47 +0000464 // Check for another declaration kind with the same name.
Douglas Gregorc83c6872010-04-15 22:33:43 +0000465 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000466 LookupOrdinaryName, ForRedeclaration);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000467
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000468 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000469 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner5f4a6822008-11-23 23:12:31 +0000470 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4d391482007-12-12 07:09:47 +0000471 }
Mike Stump1eb44332009-09-09 15:08:12 +0000472
Douglas Gregor7723fec2011-12-15 20:29:51 +0000473 // Create a declaration to describe this @interface.
Douglas Gregor0af55012011-12-16 03:12:41 +0000474 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidise7e8fca2013-06-18 21:26:33 +0000475
476 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
477 // A previous decl with a different name is because of
478 // @compatibility_alias, for example:
479 // \code
480 // @class NewImage;
481 // @compatibility_alias OldImage NewImage;
482 // \endcode
483 // A lookup for 'OldImage' will return the 'NewImage' decl.
484 //
485 // In such a case use the real declaration name, instead of the alias one,
486 // otherwise we will break IdentifierResolver and redecls-chain invariants.
487 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
488 // has been aliased.
489 ClassName = PrevIDecl->getIdentifier();
490 }
491
Douglas Gregor7723fec2011-12-15 20:29:51 +0000492 ObjCInterfaceDecl *IDecl
493 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor0af55012011-12-16 03:12:41 +0000494 PrevIDecl, ClassLoc);
Douglas Gregor7723fec2011-12-15 20:29:51 +0000495
Douglas Gregor7723fec2011-12-15 20:29:51 +0000496 if (PrevIDecl) {
497 // Class already seen. Was it a definition?
498 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
499 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
500 << PrevIDecl->getDeclName();
Douglas Gregor2e5c15b2011-12-15 05:27:12 +0000501 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor7723fec2011-12-15 20:29:51 +0000502 IDecl->setInvalidDecl();
Chris Lattner4d391482007-12-12 07:09:47 +0000503 }
Chris Lattner4d391482007-12-12 07:09:47 +0000504 }
Douglas Gregor7723fec2011-12-15 20:29:51 +0000505
506 if (AttrList)
507 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
508 PushOnScopeChains(IDecl, TUScope);
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Douglas Gregor7723fec2011-12-15 20:29:51 +0000510 // Start the definition of this class. If we're in a redefinition case, there
511 // may already be a definition, so we'll end up adding to it.
Douglas Gregor2e5c15b2011-12-15 05:27:12 +0000512 if (!IDecl->hasDefinition())
513 IDecl->startDefinition();
514
Chris Lattner4d391482007-12-12 07:09:47 +0000515 if (SuperName) {
Chris Lattner4d391482007-12-12 07:09:47 +0000516 // Check if a different kind of symbol declared in this scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +0000517 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
518 LookupOrdinaryName);
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000519
520 if (!PrevDecl) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000521 // Try to correct for a typo in the superclass name without correcting
522 // to the class we're defining.
523 ObjCInterfaceValidatorCCC Validator(IDecl);
524 if (TypoCorrection Corrected = CorrectTypo(
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000525 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700526 nullptr, Validator, CTK_ErrorRecovery)) {
Richard Smith2d670972013-08-17 00:46:16 +0000527 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
528 << SuperName << ClassName);
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000529 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000530 }
531 }
532
Douglas Gregor60ef3082011-12-15 00:29:59 +0000533 if (declaresSameEntity(PrevDecl, IDecl)) {
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000534 Diag(SuperLoc, diag::err_recursive_superclass)
535 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
Douglas Gregor05c272f2011-12-15 22:34:59 +0000536 IDecl->setEndOfDefinitionLoc(ClassLoc);
Mike Stumpac5fc7c2009-08-04 21:02:39 +0000537 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000538 ObjCInterfaceDecl *SuperClassDecl =
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000539 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Chris Lattner3c73c412008-11-19 08:23:25 +0000540
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000541 // Diagnose classes that inherit from deprecated classes.
542 if (SuperClassDecl)
543 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
Mike Stump1eb44332009-09-09 15:08:12 +0000544
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700545 if (PrevDecl && !SuperClassDecl) {
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000546 // The previous declaration was not a class decl. Check if we have a
547 // typedef. If we do, get the underlying class type.
Richard Smith162e1c12011-04-15 14:24:37 +0000548 if (const TypedefNameDecl *TDecl =
549 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000550 QualType T = TDecl->getUnderlyingType();
John McCallc12c5bb2010-05-15 11:32:37 +0000551 if (T->isObjCObjectType()) {
Fariborz Jahanian740991b2013-04-04 18:45:52 +0000552 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Douglas Gregordeacbdc2010-08-11 12:19:30 +0000553 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian740991b2013-04-04 18:45:52 +0000554 // This handles the following case:
555 // @interface NewI @end
556 // typedef NewI DeprI __attribute__((deprecated("blah")))
557 // @interface SI : DeprI /* warn here */ @end
558 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
559 }
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000560 }
561 }
Mike Stump1eb44332009-09-09 15:08:12 +0000562
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000563 // This handles the following case:
564 //
565 // typedef int SuperClass;
566 // @interface MyClass : SuperClass {} @end
567 //
568 if (!SuperClassDecl) {
569 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
570 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Steve Naroff818cb9e2009-02-04 17:14:05 +0000571 }
572 }
Mike Stump1eb44332009-09-09 15:08:12 +0000573
Richard Smith162e1c12011-04-15 14:24:37 +0000574 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000575 if (!SuperClassDecl)
576 Diag(SuperLoc, diag::err_undef_superclass)
577 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
Douglas Gregorb3029962011-11-14 22:10:01 +0000578 else if (RequireCompleteType(SuperLoc,
Douglas Gregord10099e2012-05-04 16:32:21 +0000579 Context.getObjCInterfaceType(SuperClassDecl),
580 diag::err_forward_superclass,
581 SuperClassDecl->getDeclName(),
582 ClassName,
583 SourceRange(AtInterfaceLoc, ClassLoc))) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700584 SuperClassDecl = nullptr;
Fariborz Jahaniana8139732011-06-23 23:16:19 +0000585 }
Steve Naroff818cb9e2009-02-04 17:14:05 +0000586 }
Fariborz Jahanianfdee0892009-07-09 22:08:26 +0000587 IDecl->setSuperClass(SuperClassDecl);
588 IDecl->setSuperClassLoc(SuperLoc);
Douglas Gregor05c272f2011-12-15 22:34:59 +0000589 IDecl->setEndOfDefinitionLoc(SuperLoc);
Steve Naroff818cb9e2009-02-04 17:14:05 +0000590 }
Chris Lattner4d391482007-12-12 07:09:47 +0000591 } else { // we have a root class.
Douglas Gregor05c272f2011-12-15 22:34:59 +0000592 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattner4d391482007-12-12 07:09:47 +0000593 }
Mike Stump1eb44332009-09-09 15:08:12 +0000594
Sebastian Redl0b17c612010-08-13 00:28:03 +0000595 // Check then save referenced protocols.
Chris Lattner06036d32008-07-26 04:13:19 +0000596 if (NumProtoRefs) {
Roman Divacky31ba6132012-09-06 15:59:27 +0000597 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor18df52b2010-01-16 15:02:53 +0000598 ProtoLocs, Context);
Douglas Gregor05c272f2011-12-15 22:34:59 +0000599 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattner4d391482007-12-12 07:09:47 +0000600 }
Mike Stump1eb44332009-09-09 15:08:12 +0000601
Anders Carlsson15281452008-11-04 16:57:32 +0000602 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +0000603 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattner4d391482007-12-12 07:09:47 +0000604}
605
Fariborz Jahaniana924f842013-09-25 19:36:32 +0000606/// ActOnTypedefedProtocols - this action finds protocol list as part of the
607/// typedef'ed use for a qualified super class and adds them to the list
608/// of the protocols.
609void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
610 IdentifierInfo *SuperName,
611 SourceLocation SuperLoc) {
612 if (!SuperName)
613 return;
614 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
615 LookupOrdinaryName);
616 if (!IDecl)
617 return;
618
619 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
620 QualType T = TDecl->getUnderlyingType();
621 if (T->isObjCObjectType())
622 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
Stephen Hines651f13c2014-04-23 16:59:28 -0700623 for (auto *I : OPT->quals())
624 ProtocolRefs.push_back(I);
Fariborz Jahaniana924f842013-09-25 19:36:32 +0000625 }
626}
627
Richard Smithde01b7a2012-08-08 23:32:13 +0000628/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett1dfbd922012-06-14 21:40:34 +0000629/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithde01b7a2012-08-08 23:32:13 +0000630Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
631 IdentifierInfo *AliasName,
632 SourceLocation AliasLocation,
633 IdentifierInfo *ClassName,
634 SourceLocation ClassLocation) {
Chris Lattner4d391482007-12-12 07:09:47 +0000635 // Look for previous declaration of alias name
Douglas Gregorc83c6872010-04-15 22:33:43 +0000636 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000637 LookupOrdinaryName, ForRedeclaration);
Chris Lattner4d391482007-12-12 07:09:47 +0000638 if (ADecl) {
Eli Friedman104f96b2013-06-21 01:49:53 +0000639 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattner8b265bd2008-11-23 23:20:13 +0000640 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700641 return nullptr;
Chris Lattner4d391482007-12-12 07:09:47 +0000642 }
643 // Check for class declaration
Douglas Gregorc83c6872010-04-15 22:33:43 +0000644 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000645 LookupOrdinaryName, ForRedeclaration);
Richard Smith162e1c12011-04-15 14:24:37 +0000646 if (const TypedefNameDecl *TDecl =
647 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian305c6582009-01-08 01:10:55 +0000648 QualType T = TDecl->getUnderlyingType();
John McCallc12c5bb2010-05-15 11:32:37 +0000649 if (T->isObjCObjectType()) {
650 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian305c6582009-01-08 01:10:55 +0000651 ClassName = IDecl->getIdentifier();
Douglas Gregorc83c6872010-04-15 22:33:43 +0000652 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Douglas Gregorc0b39642010-04-15 23:40:53 +0000653 LookupOrdinaryName, ForRedeclaration);
Fariborz Jahanian305c6582009-01-08 01:10:55 +0000654 }
655 }
656 }
Chris Lattnerf8d17a52008-03-16 21:17:37 +0000657 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700658 if (!CDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000659 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattnerf8d17a52008-03-16 21:17:37 +0000660 if (CDeclU)
Chris Lattner8b265bd2008-11-23 23:20:13 +0000661 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700662 return nullptr;
Chris Lattner4d391482007-12-12 07:09:47 +0000663 }
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Chris Lattnerf8d17a52008-03-16 21:17:37 +0000665 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump1eb44332009-09-09 15:08:12 +0000666 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregord0434102009-01-09 00:49:46 +0000667 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Anders Carlsson15281452008-11-04 16:57:32 +0000669 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor516ff432009-04-24 02:57:34 +0000670 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregord0434102009-01-09 00:49:46 +0000671
John McCalld226f652010-08-21 09:40:31 +0000672 return AliasDecl;
Chris Lattner4d391482007-12-12 07:09:47 +0000673}
674
Fariborz Jahanian819e9bf2011-05-13 18:02:08 +0000675bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff61d68522009-03-05 15:22:01 +0000676 IdentifierInfo *PName,
677 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian819e9bf2011-05-13 18:02:08 +0000678 const ObjCList<ObjCProtocolDecl> &PList) {
679
680 bool res = false;
Steve Naroff61d68522009-03-05 15:22:01 +0000681 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
682 E = PList.end(); I != E; ++I) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000683 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
684 Ploc)) {
Steve Naroff61d68522009-03-05 15:22:01 +0000685 if (PDecl->getIdentifier() == PName) {
686 Diag(Ploc, diag::err_protocol_has_circular_dependency);
687 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian819e9bf2011-05-13 18:02:08 +0000688 res = true;
Steve Naroff61d68522009-03-05 15:22:01 +0000689 }
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +0000690
691 if (!PDecl->hasDefinition())
692 continue;
693
Fariborz Jahanian819e9bf2011-05-13 18:02:08 +0000694 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
695 PDecl->getLocation(), PDecl->getReferencedProtocols()))
696 res = true;
Steve Naroff61d68522009-03-05 15:22:01 +0000697 }
698 }
Fariborz Jahanian819e9bf2011-05-13 18:02:08 +0000699 return res;
Steve Naroff61d68522009-03-05 15:22:01 +0000700}
701
John McCalld226f652010-08-21 09:40:31 +0000702Decl *
Chris Lattnere13b9592008-07-26 04:03:38 +0000703Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
704 IdentifierInfo *ProtocolName,
705 SourceLocation ProtocolLoc,
John McCalld226f652010-08-21 09:40:31 +0000706 Decl * const *ProtoRefs,
Chris Lattnere13b9592008-07-26 04:03:38 +0000707 unsigned NumProtoRefs,
Douglas Gregor18df52b2010-01-16 15:02:53 +0000708 const SourceLocation *ProtoLocs,
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000709 SourceLocation EndProtoLoc,
710 AttributeList *AttrList) {
Fariborz Jahanian96b69a72011-05-12 22:04:39 +0000711 bool err = false;
Daniel Dunbar246e70f2008-09-26 04:48:09 +0000712 // FIXME: Deal with AttrList.
Chris Lattner4d391482007-12-12 07:09:47 +0000713 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor27c6da22012-01-01 20:30:41 +0000714 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
715 ForRedeclaration);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700716 ObjCProtocolDecl *PDecl = nullptr;
717 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor27c6da22012-01-01 20:30:41 +0000718 // If we already have a definition, complain.
719 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
720 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Douglas Gregor27c6da22012-01-01 20:30:41 +0000722 // Create a new protocol that is completely distinct from previous
723 // declarations, and do not make this protocol available for name lookup.
724 // That way, we'll end up completely ignoring the duplicate.
725 // FIXME: Can we turn this into an error?
726 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
727 ProtocolLoc, AtProtoInterfaceLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700728 /*PrevDecl=*/nullptr);
Douglas Gregor27c6da22012-01-01 20:30:41 +0000729 PDecl->startDefinition();
730 } else {
731 if (PrevDecl) {
732 // Check for circular dependencies among protocol declarations. This can
733 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis4fc04da2011-11-13 22:08:30 +0000734 ObjCList<ObjCProtocolDecl> PList;
735 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
736 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor27c6da22012-01-01 20:30:41 +0000737 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis4fc04da2011-11-13 22:08:30 +0000738 }
Douglas Gregor27c6da22012-01-01 20:30:41 +0000739
740 // Create the new declaration.
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +0000741 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidisb05d7b22011-10-17 19:48:06 +0000742 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregorc9d3c7e2012-01-01 22:06:18 +0000743 /*PrevDecl=*/PrevDecl);
Douglas Gregor27c6da22012-01-01 20:30:41 +0000744
Douglas Gregor6e378de2009-04-23 23:18:26 +0000745 PushOnScopeChains(PDecl, TUScope);
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +0000746 PDecl->startDefinition();
Chris Lattnercca59d72008-03-16 01:23:04 +0000747 }
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +0000748
Fariborz Jahanianbc1c8772008-12-17 01:07:27 +0000749 if (AttrList)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000750 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Douglas Gregor27c6da22012-01-01 20:30:41 +0000751
752 // Merge attributes from previous declarations.
753 if (PrevDecl)
754 mergeDeclAttributes(PDecl, PrevDecl);
755
Fariborz Jahanian96b69a72011-05-12 22:04:39 +0000756 if (!err && NumProtoRefs ) {
Chris Lattnerc8581052008-03-16 20:19:15 +0000757 /// Check then save referenced protocols.
Roman Divacky31ba6132012-09-06 15:59:27 +0000758 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor18df52b2010-01-16 15:02:53 +0000759 ProtoLocs, Context);
Chris Lattner4d391482007-12-12 07:09:47 +0000760 }
Mike Stump1eb44332009-09-09 15:08:12 +0000761
762 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +0000763 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattner4d391482007-12-12 07:09:47 +0000764}
765
Stephen Hines651f13c2014-04-23 16:59:28 -0700766static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
767 ObjCProtocolDecl *&UndefinedProtocol) {
768 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
769 UndefinedProtocol = PDecl;
770 return true;
771 }
772
773 for (auto *PI : PDecl->protocols())
774 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
775 UndefinedProtocol = PI;
776 return true;
777 }
778 return false;
779}
780
Chris Lattner4d391482007-12-12 07:09:47 +0000781/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbar7ad1b1f2008-09-04 20:01:15 +0000782/// issues an error if they are not declared. It returns list of
783/// protocol declarations in its 'Protocols' argument.
Chris Lattner4d391482007-12-12 07:09:47 +0000784void
Chris Lattnere13b9592008-07-26 04:03:38 +0000785Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
Chris Lattner7caeabd2008-07-21 22:17:28 +0000786 const IdentifierLocPair *ProtocolId,
Chris Lattner4d391482007-12-12 07:09:47 +0000787 unsigned NumProtocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000788 SmallVectorImpl<Decl *> &Protocols) {
Chris Lattner4d391482007-12-12 07:09:47 +0000789 for (unsigned i = 0; i != NumProtocols; ++i) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000790 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
791 ProtocolId[i].second);
Chris Lattnereacc3922008-07-26 03:47:43 +0000792 if (!PDecl) {
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +0000793 DeclFilterCCC<ObjCProtocolDecl> Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000794 TypoCorrection Corrected = CorrectTypo(
795 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700796 LookupObjCProtocolName, TUScope, nullptr, Validator,
797 CTK_ErrorRecovery);
Richard Smith2d670972013-08-17 00:46:16 +0000798 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
799 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
800 << ProtocolId[i].first);
Douglas Gregorf06cdae2010-01-03 18:01:57 +0000801 }
802
803 if (!PDecl) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000804 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
Chris Lattner3c73c412008-11-19 08:23:25 +0000805 << ProtocolId[i].first;
Chris Lattnereacc3922008-07-26 03:47:43 +0000806 continue;
807 }
Fariborz Jahanian3c9a0242013-04-09 17:52:29 +0000808 // If this is a forward protocol declaration, get its definition.
809 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
810 PDecl = PDecl->getDefinition();
811
Douglas Gregor48f3bb92009-02-18 21:56:37 +0000812 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
Chris Lattnereacc3922008-07-26 03:47:43 +0000813
814 // If this is a forward declaration and we are supposed to warn in this
815 // case, do it.
Douglas Gregor0f9b9f32013-01-17 00:38:46 +0000816 // FIXME: Recover nicely in the hidden case.
Stephen Hines651f13c2014-04-23 16:59:28 -0700817 ObjCProtocolDecl *UndefinedProtocol;
818
Douglas Gregor0f9b9f32013-01-17 00:38:46 +0000819 if (WarnOnDeclarations &&
Stephen Hines651f13c2014-04-23 16:59:28 -0700820 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000821 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
Chris Lattner3c73c412008-11-19 08:23:25 +0000822 << ProtocolId[i].first;
Stephen Hines651f13c2014-04-23 16:59:28 -0700823 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
824 << UndefinedProtocol;
825 }
John McCalld226f652010-08-21 09:40:31 +0000826 Protocols.push_back(PDecl);
Chris Lattner4d391482007-12-12 07:09:47 +0000827 }
828}
829
Fariborz Jahanian78c39c72009-03-02 19:06:08 +0000830/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanianb7f95f52009-03-02 19:05:07 +0000831/// a class method in its extension.
832///
Mike Stump1eb44332009-09-09 15:08:12 +0000833void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanianb7f95f52009-03-02 19:05:07 +0000834 ObjCInterfaceDecl *ID) {
835 if (!ID)
836 return; // Possibly due to previous error
837
838 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Stephen Hines651f13c2014-04-23 16:59:28 -0700839 for (auto *MD : ID->methods())
Fariborz Jahanianb7f95f52009-03-02 19:05:07 +0000840 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanianb7f95f52009-03-02 19:05:07 +0000841
842 if (MethodMap.empty())
843 return;
Stephen Hines651f13c2014-04-23 16:59:28 -0700844 for (const auto *Method : CAT->methods()) {
Fariborz Jahanianb7f95f52009-03-02 19:05:07 +0000845 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Stephen Hines651f13c2014-04-23 16:59:28 -0700846 if (PrevMethod &&
847 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
848 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanianb7f95f52009-03-02 19:05:07 +0000849 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
850 << Method->getDeclName();
851 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
852 }
853 }
854}
855
James Dennett1dfbd922012-06-14 21:40:34 +0000856/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000857Sema::DeclGroupPtrTy
Chris Lattner4d391482007-12-12 07:09:47 +0000858Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Chris Lattner7caeabd2008-07-21 22:17:28 +0000859 const IdentifierLocPair *IdentList,
Fariborz Jahanianbc1c8772008-12-17 01:07:27 +0000860 unsigned NumElts,
861 AttributeList *attrList) {
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000862 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4d391482007-12-12 07:09:47 +0000863 for (unsigned i = 0; i != NumElts; ++i) {
Chris Lattner7caeabd2008-07-21 22:17:28 +0000864 IdentifierInfo *Ident = IdentList[i].first;
Douglas Gregor27c6da22012-01-01 20:30:41 +0000865 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
866 ForRedeclaration);
867 ObjCProtocolDecl *PDecl
868 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
869 IdentList[i].second, AtProtocolLoc,
Douglas Gregorc9d3c7e2012-01-01 22:06:18 +0000870 PrevDecl);
Douglas Gregor27c6da22012-01-01 20:30:41 +0000871
872 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000873 CheckObjCDeclScope(PDecl);
Douglas Gregor27c6da22012-01-01 20:30:41 +0000874
Douglas Gregor3937f872012-01-01 20:33:24 +0000875 if (attrList)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +0000876 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Douglas Gregor27c6da22012-01-01 20:30:41 +0000877
878 if (PrevDecl)
879 mergeDeclAttributes(PDecl, PrevDecl);
880
Douglas Gregorbd9482d2012-01-01 21:23:57 +0000881 DeclsInGroup.push_back(PDecl);
Chris Lattner4d391482007-12-12 07:09:47 +0000882 }
Mike Stump1eb44332009-09-09 15:08:12 +0000883
Rafael Espindola4549d7f2013-07-09 12:05:01 +0000884 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattner4d391482007-12-12 07:09:47 +0000885}
886
John McCalld226f652010-08-21 09:40:31 +0000887Decl *Sema::
Chris Lattner7caeabd2008-07-21 22:17:28 +0000888ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
889 IdentifierInfo *ClassName, SourceLocation ClassLoc,
890 IdentifierInfo *CategoryName,
891 SourceLocation CategoryLoc,
John McCalld226f652010-08-21 09:40:31 +0000892 Decl * const *ProtoRefs,
Chris Lattner7caeabd2008-07-21 22:17:28 +0000893 unsigned NumProtoRefs,
Douglas Gregor18df52b2010-01-16 15:02:53 +0000894 const SourceLocation *ProtoLocs,
Chris Lattner7caeabd2008-07-21 22:17:28 +0000895 SourceLocation EndProtoLoc) {
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000896 ObjCCategoryDecl *CDecl;
Douglas Gregorc83c6872010-04-15 22:33:43 +0000897 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek09b68972010-02-23 19:39:46 +0000898
899 /// Check that class of this category is already completely declared.
Douglas Gregorb3029962011-11-14 22:10:01 +0000900
901 if (!IDecl
902 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregord10099e2012-05-04 16:32:21 +0000903 diag::err_category_forward_interface,
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700904 CategoryName == nullptr)) {
Ted Kremenek09b68972010-02-23 19:39:46 +0000905 // Create an invalid ObjCCategoryDecl to serve as context for
906 // the enclosing method declarations. We mark the decl invalid
907 // to make it clear that this isn't a valid AST.
908 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Argyrios Kyrtzidis955fadb2011-08-30 19:43:26 +0000909 ClassLoc, CategoryLoc, CategoryName,IDecl);
Ted Kremenek09b68972010-02-23 19:39:46 +0000910 CDecl->setInvalidDecl();
Argyrios Kyrtzidis9a0b6b42012-03-12 18:34:26 +0000911 CurContext->addDecl(CDecl);
Douglas Gregorb3029962011-11-14 22:10:01 +0000912
913 if (!IDecl)
914 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +0000915 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek09b68972010-02-23 19:39:46 +0000916 }
917
Fariborz Jahanian80aa1cd2010-06-22 23:20:40 +0000918 if (!CategoryName && IDecl->getImplementation()) {
919 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
920 Diag(IDecl->getImplementation()->getLocation(),
921 diag::note_implementation_declared);
Ted Kremenek09b68972010-02-23 19:39:46 +0000922 }
923
Fariborz Jahanian25760612010-02-15 21:55:26 +0000924 if (CategoryName) {
925 /// Check for duplicate interface declaration for this category
Douglas Gregord3297242013-01-16 23:00:23 +0000926 if (ObjCCategoryDecl *Previous
927 = IDecl->FindCategoryDeclaration(CategoryName)) {
928 // Class extensions can be declared multiple times, categories cannot.
929 Diag(CategoryLoc, diag::warn_dup_category_def)
930 << ClassName << CategoryName;
931 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner70f19542009-02-16 21:26:43 +0000932 }
933 }
Chris Lattner70f19542009-02-16 21:26:43 +0000934
Argyrios Kyrtzidis955fadb2011-08-30 19:43:26 +0000935 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
936 ClassLoc, CategoryLoc, CategoryName, IDecl);
937 // FIXME: PushOnScopeChains?
938 CurContext->addDecl(CDecl);
939
Chris Lattner4d391482007-12-12 07:09:47 +0000940 if (NumProtoRefs) {
Roman Divacky31ba6132012-09-06 15:59:27 +0000941 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor18df52b2010-01-16 15:02:53 +0000942 ProtoLocs, Context);
Fariborz Jahanian339798e2009-10-05 20:41:32 +0000943 // Protocols in the class extension belong to the class.
Fariborz Jahanian25760612010-02-15 21:55:26 +0000944 if (CDecl->IsClassExtension())
Roman Divacky31ba6132012-09-06 15:59:27 +0000945 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek53b94412010-09-01 01:21:15 +0000946 NumProtoRefs, Context);
Chris Lattner4d391482007-12-12 07:09:47 +0000947 }
Mike Stump1eb44332009-09-09 15:08:12 +0000948
Anders Carlsson15281452008-11-04 16:57:32 +0000949 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +0000950 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattner4d391482007-12-12 07:09:47 +0000951}
952
953/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000954/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattner4d391482007-12-12 07:09:47 +0000955/// object.
John McCalld226f652010-08-21 09:40:31 +0000956Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattner4d391482007-12-12 07:09:47 +0000957 SourceLocation AtCatImplLoc,
958 IdentifierInfo *ClassName, SourceLocation ClassLoc,
959 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorc83c6872010-04-15 22:33:43 +0000960 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Stephen Hines6bcf27b2014-05-29 04:14:42 -0700961 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis5a61e0c2012-03-02 19:14:29 +0000962 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000963 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
964 if (!CatIDecl) {
965 // Category @implementation with no corresponding @interface.
966 // Create and install one.
Argyrios Kyrtzidis37f40572011-11-23 20:27:26 +0000967 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
968 ClassLoc, CatLoc,
Argyrios Kyrtzidis955fadb2011-08-30 19:43:26 +0000969 CatName, IDecl);
Argyrios Kyrtzidis37f40572011-11-23 20:27:26 +0000970 CatIDecl->setImplicit();
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000971 }
972 }
973
Mike Stump1eb44332009-09-09 15:08:12 +0000974 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +0000975 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidisc6994002011-12-09 00:31:40 +0000976 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattner4d391482007-12-12 07:09:47 +0000977 /// Check that class of this category is already completely declared.
Douglas Gregorb3029962011-11-14 22:10:01 +0000978 if (!IDecl) {
Chris Lattner3c73c412008-11-19 08:23:25 +0000979 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCall6c2c2502011-07-22 02:45:48 +0000980 CDecl->setInvalidDecl();
Douglas Gregorb3029962011-11-14 22:10:01 +0000981 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
982 diag::err_undef_interface)) {
983 CDecl->setInvalidDecl();
John McCall6c2c2502011-07-22 02:45:48 +0000984 }
Chris Lattner4d391482007-12-12 07:09:47 +0000985
Douglas Gregord0434102009-01-09 00:49:46 +0000986 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000987 CurContext->addDecl(CDecl);
Douglas Gregord0434102009-01-09 00:49:46 +0000988
Argyrios Kyrtzidisc076e372011-10-06 23:23:27 +0000989 // If the interface is deprecated/unavailable, warn/error about it.
990 if (IDecl)
991 DiagnoseUseOfDecl(IDecl, ClassLoc);
992
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +0000993 /// Check that CatName, category name, is not used in another implementation.
994 if (CatIDecl) {
995 if (CatIDecl->getImplementation()) {
996 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
997 << CatName;
998 Diag(CatIDecl->getImplementation()->getLocation(),
999 diag::note_previous_definition);
Argyrios Kyrtzidisdf08c4b2013-05-30 18:53:21 +00001000 CDecl->setInvalidDecl();
Fariborz Jahanianb1224f62011-02-15 00:59:30 +00001001 } else {
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001002 CatIDecl->setImplementation(CDecl);
Fariborz Jahanianb1224f62011-02-15 00:59:30 +00001003 // Warn on implementating category of deprecated class under
1004 // -Wdeprecated-implementations flag.
Fariborz Jahanian5ac96d52011-02-15 17:49:58 +00001005 DiagnoseObjCImplementedDeprecations(*this,
1006 dyn_cast<NamedDecl>(IDecl),
1007 CDecl->getLocation(), 2);
Fariborz Jahanianb1224f62011-02-15 00:59:30 +00001008 }
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001009 }
Mike Stump1eb44332009-09-09 15:08:12 +00001010
Anders Carlsson15281452008-11-04 16:57:32 +00001011 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00001012 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattner4d391482007-12-12 07:09:47 +00001013}
1014
John McCalld226f652010-08-21 09:40:31 +00001015Decl *Sema::ActOnStartClassImplementation(
Chris Lattner4d391482007-12-12 07:09:47 +00001016 SourceLocation AtClassImplLoc,
1017 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump1eb44332009-09-09 15:08:12 +00001018 IdentifierInfo *SuperClassname,
Chris Lattner4d391482007-12-12 07:09:47 +00001019 SourceLocation SuperClassLoc) {
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001020 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattner4d391482007-12-12 07:09:47 +00001021 // Check for another declaration kind with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00001022 NamedDecl *PrevDecl
Douglas Gregorc0b39642010-04-15 23:40:53 +00001023 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1024 ForRedeclaration);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001025 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001026 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner5f4a6822008-11-23 23:12:31 +00001027 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001028 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Douglas Gregor0af55012011-12-16 03:12:41 +00001029 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1030 diag::warn_undef_interface);
Douglas Gregor95ff7422010-01-04 17:27:12 +00001031 } else {
Richard Smith2d670972013-08-17 00:46:16 +00001032 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor95ff7422010-01-04 17:27:12 +00001033 // typos in the class name.
Kaelyn Uhrain2f4d88f2012-01-13 01:32:50 +00001034 ObjCInterfaceValidatorCCC Validator;
Richard Smith2d670972013-08-17 00:46:16 +00001035 TypoCorrection Corrected =
1036 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001037 LookupOrdinaryName, TUScope, nullptr, Validator,
1038 CTK_NonError);
Richard Smith2d670972013-08-17 00:46:16 +00001039 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1040 // Suggest the (potentially) correct interface name. Don't provide a
1041 // code-modification hint or use the typo name for recovery, because
1042 // this is just a warning. The program may actually be correct.
1043 diagnoseTypo(Corrected,
1044 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1045 /*ErrorRecovery*/false);
Douglas Gregor95ff7422010-01-04 17:27:12 +00001046 } else {
1047 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1048 }
Chris Lattner4d391482007-12-12 07:09:47 +00001049 }
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Chris Lattner4d391482007-12-12 07:09:47 +00001051 // Check that super class name is valid class name
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001052 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattner4d391482007-12-12 07:09:47 +00001053 if (SuperClassname) {
1054 // Check if a different kind of symbol declared in this scope.
Douglas Gregorc83c6872010-04-15 22:33:43 +00001055 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1056 LookupOrdinaryName);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001057 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001058 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1059 << SuperClassname;
Chris Lattner5f4a6822008-11-23 23:12:31 +00001060 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner3c73c412008-11-19 08:23:25 +00001061 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001062 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidiscd707ab2012-03-13 01:09:36 +00001063 if (SDecl && !SDecl->hasDefinition())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001064 SDecl = nullptr;
Chris Lattner4d391482007-12-12 07:09:47 +00001065 if (!SDecl)
Chris Lattner3c73c412008-11-19 08:23:25 +00001066 Diag(SuperClassLoc, diag::err_undef_superclass)
1067 << SuperClassname << ClassName;
Douglas Gregor60ef3082011-12-15 00:29:59 +00001068 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattner4d391482007-12-12 07:09:47 +00001069 // This implementation and its interface do not have the same
1070 // super class.
Chris Lattner3c73c412008-11-19 08:23:25 +00001071 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattner08631c52008-11-23 21:45:46 +00001072 << SDecl->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001073 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4d391482007-12-12 07:09:47 +00001074 }
1075 }
1076 }
Mike Stump1eb44332009-09-09 15:08:12 +00001077
Chris Lattner4d391482007-12-12 07:09:47 +00001078 if (!IDecl) {
1079 // Legacy case of @implementation with no corresponding @interface.
1080 // Build, chain & install the interface decl into the identifier.
Daniel Dunbarf6414922008-08-20 18:02:42 +00001081
Mike Stump390b4cc2009-05-16 07:39:55 +00001082 // FIXME: Do we support attributes on the @implementation? If so we should
1083 // copy them over.
Mike Stump1eb44332009-09-09 15:08:12 +00001084 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001085 ClassName, /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregor0af55012011-12-16 03:12:41 +00001086 true);
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001087 IDecl->startDefinition();
Douglas Gregor05c272f2011-12-15 22:34:59 +00001088 if (SDecl) {
1089 IDecl->setSuperClass(SDecl);
1090 IDecl->setSuperClassLoc(SuperClassLoc);
1091 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1092 } else {
1093 IDecl->setEndOfDefinitionLoc(ClassLoc);
1094 }
1095
Douglas Gregor8b9fb302009-04-24 00:16:12 +00001096 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001097 } else {
1098 // Mark the interface as being completed, even if it was just as
1099 // @class ....;
1100 // declaration; the user cannot reopen it.
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00001101 if (!IDecl->hasDefinition())
1102 IDecl->startDefinition();
Chris Lattner4d391482007-12-12 07:09:47 +00001103 }
Mike Stump1eb44332009-09-09 15:08:12 +00001104
1105 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00001106 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidis634c5632013-05-03 18:05:44 +00001107 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001108
Anders Carlsson15281452008-11-04 16:57:32 +00001109 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00001110 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001111
Chris Lattner4d391482007-12-12 07:09:47 +00001112 // Check that there is no duplicate implementation of this class.
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001113 if (IDecl->getImplementation()) {
1114 // FIXME: Don't leak everything!
Chris Lattner3c73c412008-11-19 08:23:25 +00001115 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis87018772009-07-21 00:06:04 +00001116 Diag(IDecl->getImplementation()->getLocation(),
1117 diag::note_previous_definition);
Argyrios Kyrtzidisdf08c4b2013-05-30 18:53:21 +00001118 IMPDecl->setInvalidDecl();
Douglas Gregordeacbdc2010-08-11 12:19:30 +00001119 } else { // add it to the list.
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001120 IDecl->setImplementation(IMPDecl);
Douglas Gregor8fc463a2009-04-24 00:11:27 +00001121 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahanianb1224f62011-02-15 00:59:30 +00001122 // Warn on implementating deprecated class under
1123 // -Wdeprecated-implementations flag.
Fariborz Jahanian5ac96d52011-02-15 17:49:58 +00001124 DiagnoseObjCImplementedDeprecations(*this,
1125 dyn_cast<NamedDecl>(IDecl),
1126 IMPDecl->getLocation(), 1);
Argyrios Kyrtzidis8a1d7222009-07-21 00:05:53 +00001127 }
Argyrios Kyrtzidis3a387442011-10-06 23:23:20 +00001128 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattner4d391482007-12-12 07:09:47 +00001129}
1130
Argyrios Kyrtzidis644af7b2012-02-23 21:11:20 +00001131Sema::DeclGroupPtrTy
1132Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1133 SmallVector<Decl *, 64> DeclsInGroup;
1134 DeclsInGroup.reserve(Decls.size() + 1);
1135
1136 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1137 Decl *Dcl = Decls[i];
1138 if (!Dcl)
1139 continue;
1140 if (Dcl->getDeclContext()->isFileContext())
1141 Dcl->setTopLevelDeclInObjCContainer();
1142 DeclsInGroup.push_back(Dcl);
1143 }
1144
1145 DeclsInGroup.push_back(ObjCImpDecl);
1146
Rafael Espindola4549d7f2013-07-09 12:05:01 +00001147 return BuildDeclaratorGroup(DeclsInGroup, false);
Argyrios Kyrtzidis644af7b2012-02-23 21:11:20 +00001148}
1149
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001150void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1151 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattner4d391482007-12-12 07:09:47 +00001152 SourceLocation RBrace) {
1153 assert(ImpDecl && "missing implementation decl");
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001154 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattner4d391482007-12-12 07:09:47 +00001155 if (!IDecl)
1156 return;
James Dennett1dfbd922012-06-14 21:40:34 +00001157 /// Check case of non-existing \@interface decl.
1158 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattner4d391482007-12-12 07:09:47 +00001159 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroff33feeb02009-04-20 20:09:33 +00001160 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor05c272f2011-12-15 22:34:59 +00001161 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian3a21cd92010-02-17 17:00:07 +00001162 // Add ivar's to class's DeclContext.
1163 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanian2f14c4d2010-02-17 18:10:54 +00001164 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001165 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00001166 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian3a21cd92010-02-17 17:00:07 +00001167 }
1168
Chris Lattner4d391482007-12-12 07:09:47 +00001169 return;
1170 }
1171 // If implementation has empty ivar list, just return.
1172 if (numIvars == 0)
1173 return;
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Chris Lattner4d391482007-12-12 07:09:47 +00001175 assert(ivars && "missing @implementation ivars");
John McCall260611a2012-06-20 06:18:46 +00001176 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianbd94d442010-02-19 20:58:54 +00001177 if (ImpDecl->getSuperClass())
1178 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1179 for (unsigned i = 0; i < numIvars; i++) {
1180 ObjCIvarDecl* ImplIvar = ivars[i];
1181 if (const ObjCIvarDecl *ClsIvar =
1182 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1183 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1184 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1185 continue;
1186 }
Fariborz Jahanian3b20f582013-06-26 22:10:27 +00001187 // Check class extensions (unnamed categories) for duplicate ivars.
Stephen Hines651f13c2014-04-23 16:59:28 -07001188 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahanian3b20f582013-06-26 22:10:27 +00001189 if (const ObjCIvarDecl *ClsExtIvar =
1190 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1191 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1192 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1193 continue;
1194 }
1195 }
Fariborz Jahanianbd94d442010-02-19 20:58:54 +00001196 // Instance ivar to Implementation's DeclContext.
1197 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith1b7f9cb2012-03-13 03:12:56 +00001198 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanianbd94d442010-02-19 20:58:54 +00001199 ImpDecl->addDecl(ImplIvar);
1200 }
1201 return;
1202 }
Chris Lattner4d391482007-12-12 07:09:47 +00001203 // Check interface's Ivar list against those in the implementation.
1204 // names and types must match.
1205 //
Chris Lattner4d391482007-12-12 07:09:47 +00001206 unsigned j = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001207 ObjCInterfaceDecl::ivar_iterator
Chris Lattner4c525092007-12-12 17:58:05 +00001208 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1209 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001210 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie581deb32012-06-06 20:45:41 +00001211 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattner4d391482007-12-12 07:09:47 +00001212 assert (ImplIvar && "missing implementation ivar");
1213 assert (ClsIvar && "missing class ivar");
Mike Stump1eb44332009-09-09 15:08:12 +00001214
Steve Naroffca331292009-03-03 14:49:36 +00001215 // First, make sure the types match.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001216 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001217 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattner08631c52008-11-23 21:45:46 +00001218 << ImplIvar->getIdentifier()
1219 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001220 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001221 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1222 ImplIvar->getBitWidthValue(Context) !=
1223 ClsIvar->getBitWidthValue(Context)) {
1224 Diag(ImplIvar->getBitWidth()->getLocStart(),
1225 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1226 Diag(ClsIvar->getBitWidth()->getLocStart(),
1227 diag::note_previous_definition);
Mike Stump1eb44332009-09-09 15:08:12 +00001228 }
Steve Naroffca331292009-03-03 14:49:36 +00001229 // Make sure the names are identical.
1230 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001231 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattner08631c52008-11-23 21:45:46 +00001232 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner5f4a6822008-11-23 23:12:31 +00001233 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattner4d391482007-12-12 07:09:47 +00001234 }
1235 --numIvars;
Chris Lattner4d391482007-12-12 07:09:47 +00001236 }
Mike Stump1eb44332009-09-09 15:08:12 +00001237
Chris Lattner609e4c72007-12-12 18:11:49 +00001238 if (numIvars > 0)
Stephen Hines651f13c2014-04-23 16:59:28 -07001239 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner609e4c72007-12-12 18:11:49 +00001240 else if (IVI != IVE)
Stephen Hines651f13c2014-04-23 16:59:28 -07001241 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner4d391482007-12-12 07:09:47 +00001242}
1243
Stephen Hines651f13c2014-04-23 16:59:28 -07001244static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1245 ObjCMethodDecl *method,
1246 bool &IncompleteImpl,
1247 unsigned DiagID,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001248 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian327126e2011-06-24 20:31:37 +00001249 // No point warning no definition of method which is 'unavailable'.
Douglas Gregor86f6cf62012-12-11 18:53:07 +00001250 switch (method->getAvailability()) {
1251 case AR_Available:
1252 case AR_Deprecated:
1253 break;
1254
1255 // Don't warn about unavailable or not-yet-introduced methods.
1256 case AR_NotYetIntroduced:
1257 case AR_Unavailable:
Fariborz Jahanian327126e2011-06-24 20:31:37 +00001258 return;
Douglas Gregor86f6cf62012-12-11 18:53:07 +00001259 }
1260
Ted Kremenek8b43d2b2013-03-27 00:02:21 +00001261 // FIXME: For now ignore 'IncompleteImpl'.
1262 // Previously we grouped all unimplemented methods under a single
1263 // warning, but some users strongly voiced that they would prefer
1264 // separate warnings. We will give that approach a try, as that
1265 // matches what we do with protocols.
Stephen Hines651f13c2014-04-23 16:59:28 -07001266 {
1267 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1268 B << method;
1269 if (NeededFor)
1270 B << NeededFor;
1271 }
Ted Kremenek8b43d2b2013-03-27 00:02:21 +00001272
1273 // Issue a note to the original declaration.
1274 SourceLocation MethodLoc = method->getLocStart();
1275 if (MethodLoc.isValid())
Stephen Hines651f13c2014-04-23 16:59:28 -07001276 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff3c2eb662008-02-10 21:38:56 +00001277}
1278
David Chisnalle8a2d4c2010-10-25 17:23:52 +00001279/// Determines if type B can be substituted for type A. Returns true if we can
1280/// guarantee that anything that the user will do to an object of type A can
1281/// also be done to an object of type B. This is trivially true if the two
1282/// types are the same, or if B is a subclass of A. It becomes more complex
1283/// in cases where protocols are involved.
1284///
1285/// Object types in Objective-C describe the minimum requirements for an
1286/// object, rather than providing a complete description of a type. For
1287/// example, if A is a subclass of B, then B* may refer to an instance of A.
1288/// The principle of substitutability means that we may use an instance of A
1289/// anywhere that we may use an instance of B - it will implement all of the
1290/// ivars of B and all of the methods of B.
1291///
1292/// This substitutability is important when type checking methods, because
1293/// the implementation may have stricter type definitions than the interface.
1294/// The interface specifies minimum requirements, but the implementation may
1295/// have more accurate ones. For example, a method may privately accept
1296/// instances of B, but only publish that it accepts instances of A. Any
1297/// object passed to it will be type checked against B, and so will implicitly
1298/// by a valid A*. Similarly, a method may return a subclass of the class that
1299/// it is declared as returning.
1300///
1301/// This is most important when considering subclassing. A method in a
1302/// subclass must accept any object as an argument that its superclass's
1303/// implementation accepts. It may, however, accept a more general type
1304/// without breaking substitutability (i.e. you can still use the subclass
1305/// anywhere that you can use the superclass, but not vice versa). The
1306/// converse requirement applies to return types: the return type for a
1307/// subclass method must be a valid object of the kind that the superclass
1308/// advertises, but it may be specified more accurately. This avoids the need
1309/// for explicit down-casting by callers.
1310///
1311/// Note: This is a stricter requirement than for assignment.
John McCall10302c02010-10-28 02:34:38 +00001312static bool isObjCTypeSubstitutable(ASTContext &Context,
1313 const ObjCObjectPointerType *A,
1314 const ObjCObjectPointerType *B,
1315 bool rejectId) {
1316 // Reject a protocol-unqualified id.
1317 if (rejectId && B->isObjCIdType()) return false;
David Chisnalle8a2d4c2010-10-25 17:23:52 +00001318
1319 // If B is a qualified id, then A must also be a qualified id and it must
1320 // implement all of the protocols in B. It may not be a qualified class.
1321 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1322 // stricter definition so it is not substitutable for id<A>.
1323 if (B->isObjCQualifiedIdType()) {
1324 return A->isObjCQualifiedIdType() &&
John McCall10302c02010-10-28 02:34:38 +00001325 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1326 QualType(B,0),
1327 false);
David Chisnalle8a2d4c2010-10-25 17:23:52 +00001328 }
1329
1330 /*
1331 // id is a special type that bypasses type checking completely. We want a
1332 // warning when it is used in one place but not another.
1333 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1334
1335
1336 // If B is a qualified id, then A must also be a qualified id (which it isn't
1337 // if we've got this far)
1338 if (B->isObjCQualifiedIdType()) return false;
1339 */
1340
1341 // Now we know that A and B are (potentially-qualified) class types. The
1342 // normal rules for assignment apply.
John McCall10302c02010-10-28 02:34:38 +00001343 return Context.canAssignObjCInterfaces(A, B);
David Chisnalle8a2d4c2010-10-25 17:23:52 +00001344}
1345
John McCall10302c02010-10-28 02:34:38 +00001346static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1347 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1348}
1349
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001350static bool CheckMethodOverrideReturn(Sema &S,
John McCall10302c02010-10-28 02:34:38 +00001351 ObjCMethodDecl *MethodImpl,
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001352 ObjCMethodDecl *MethodDecl,
Fariborz Jahanianeee3ef12011-07-24 20:53:26 +00001353 bool IsProtocolMethodDecl,
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001354 bool IsOverridingMode,
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001355 bool Warn) {
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001356 if (IsProtocolMethodDecl &&
1357 (MethodDecl->getObjCDeclQualifier() !=
1358 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001359 if (Warn) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001360 S.Diag(MethodImpl->getLocation(),
1361 (IsOverridingMode
1362 ? diag::warn_conflicting_overriding_ret_type_modifiers
1363 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001364 << MethodImpl->getDeclName()
Stephen Hines651f13c2014-04-23 16:59:28 -07001365 << getTypeRange(MethodImpl->getReturnTypeSourceInfo());
1366 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1367 << getTypeRange(MethodDecl->getReturnTypeSourceInfo());
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001368 }
1369 else
1370 return false;
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001371 }
Stephen Hines651f13c2014-04-23 16:59:28 -07001372
1373 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1374 MethodDecl->getReturnType()))
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001375 return true;
1376 if (!Warn)
1377 return false;
John McCall10302c02010-10-28 02:34:38 +00001378
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001379 unsigned DiagID =
1380 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1381 : diag::warn_conflicting_ret_types;
John McCall10302c02010-10-28 02:34:38 +00001382
1383 // Mismatches between ObjC pointers go into a different warning
1384 // category, and sometimes they're even completely whitelisted.
1385 if (const ObjCObjectPointerType *ImplPtrTy =
Stephen Hines651f13c2014-04-23 16:59:28 -07001386 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall10302c02010-10-28 02:34:38 +00001387 if (const ObjCObjectPointerType *IfacePtrTy =
Stephen Hines651f13c2014-04-23 16:59:28 -07001388 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall10302c02010-10-28 02:34:38 +00001389 // Allow non-matching return types as long as they don't violate
1390 // the principle of substitutability. Specifically, we permit
1391 // return types that are subclasses of the declared return type,
1392 // or that are more-qualified versions of the declared type.
1393 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001394 return false;
John McCall10302c02010-10-28 02:34:38 +00001395
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001396 DiagID =
1397 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1398 : diag::warn_non_covariant_ret_types;
John McCall10302c02010-10-28 02:34:38 +00001399 }
1400 }
1401
1402 S.Diag(MethodImpl->getLocation(), DiagID)
Stephen Hines651f13c2014-04-23 16:59:28 -07001403 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1404 << MethodImpl->getReturnType()
1405 << getTypeRange(MethodImpl->getReturnTypeSourceInfo());
1406 S.Diag(MethodDecl->getLocation(), IsOverridingMode
1407 ? diag::note_previous_declaration
1408 : diag::note_previous_definition)
1409 << getTypeRange(MethodDecl->getReturnTypeSourceInfo());
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001410 return false;
John McCall10302c02010-10-28 02:34:38 +00001411}
1412
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001413static bool CheckMethodOverrideParam(Sema &S,
John McCall10302c02010-10-28 02:34:38 +00001414 ObjCMethodDecl *MethodImpl,
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001415 ObjCMethodDecl *MethodDecl,
John McCall10302c02010-10-28 02:34:38 +00001416 ParmVarDecl *ImplVar,
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001417 ParmVarDecl *IfaceVar,
Fariborz Jahanianeee3ef12011-07-24 20:53:26 +00001418 bool IsProtocolMethodDecl,
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001419 bool IsOverridingMode,
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001420 bool Warn) {
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001421 if (IsProtocolMethodDecl &&
1422 (ImplVar->getObjCDeclQualifier() !=
1423 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001424 if (Warn) {
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001425 if (IsOverridingMode)
1426 S.Diag(ImplVar->getLocation(),
1427 diag::warn_conflicting_overriding_param_modifiers)
1428 << getTypeRange(ImplVar->getTypeSourceInfo())
1429 << MethodImpl->getDeclName();
1430 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001431 diag::warn_conflicting_param_modifiers)
1432 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001433 << MethodImpl->getDeclName();
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001434 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1435 << getTypeRange(IfaceVar->getTypeSourceInfo());
1436 }
1437 else
1438 return false;
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001439 }
1440
John McCall10302c02010-10-28 02:34:38 +00001441 QualType ImplTy = ImplVar->getType();
1442 QualType IfaceTy = IfaceVar->getType();
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001443
John McCall10302c02010-10-28 02:34:38 +00001444 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001445 return true;
1446
1447 if (!Warn)
1448 return false;
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001449 unsigned DiagID =
1450 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1451 : diag::warn_conflicting_param_types;
John McCall10302c02010-10-28 02:34:38 +00001452
1453 // Mismatches between ObjC pointers go into a different warning
1454 // category, and sometimes they're even completely whitelisted.
1455 if (const ObjCObjectPointerType *ImplPtrTy =
1456 ImplTy->getAs<ObjCObjectPointerType>()) {
1457 if (const ObjCObjectPointerType *IfacePtrTy =
1458 IfaceTy->getAs<ObjCObjectPointerType>()) {
1459 // Allow non-matching argument types as long as they don't
1460 // violate the principle of substitutability. Specifically, the
1461 // implementation must accept any objects that the superclass
1462 // accepts, however it may also accept others.
1463 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001464 return false;
John McCall10302c02010-10-28 02:34:38 +00001465
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001466 DiagID =
1467 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1468 : diag::warn_non_contravariant_param_types;
John McCall10302c02010-10-28 02:34:38 +00001469 }
1470 }
1471
1472 S.Diag(ImplVar->getLocation(), DiagID)
1473 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001474 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1475 S.Diag(IfaceVar->getLocation(),
1476 (IsOverridingMode ? diag::note_previous_declaration
1477 : diag::note_previous_definition))
John McCall10302c02010-10-28 02:34:38 +00001478 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001479 return false;
John McCall10302c02010-10-28 02:34:38 +00001480}
John McCallf85e1932011-06-15 23:02:42 +00001481
1482/// In ARC, check whether the conventional meanings of the two methods
1483/// match. If they don't, it's a hard error.
1484static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1485 ObjCMethodDecl *decl) {
1486 ObjCMethodFamily implFamily = impl->getMethodFamily();
1487 ObjCMethodFamily declFamily = decl->getMethodFamily();
1488 if (implFamily == declFamily) return false;
1489
1490 // Since conventions are sorted by selector, the only possibility is
1491 // that the types differ enough to cause one selector or the other
1492 // to fall out of the family.
1493 assert(implFamily == OMF_None || declFamily == OMF_None);
1494
1495 // No further diagnostics required on invalid declarations.
1496 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1497
1498 const ObjCMethodDecl *unmatched = impl;
1499 ObjCMethodFamily family = declFamily;
1500 unsigned errorID = diag::err_arc_lost_method_convention;
1501 unsigned noteID = diag::note_arc_lost_method_convention;
1502 if (declFamily == OMF_None) {
1503 unmatched = decl;
1504 family = implFamily;
1505 errorID = diag::err_arc_gained_method_convention;
1506 noteID = diag::note_arc_gained_method_convention;
1507 }
1508
1509 // Indexes into a %select clause in the diagnostic.
1510 enum FamilySelector {
1511 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1512 };
1513 FamilySelector familySelector = FamilySelector();
1514
1515 switch (family) {
1516 case OMF_None: llvm_unreachable("logic error, no method convention");
1517 case OMF_retain:
1518 case OMF_release:
1519 case OMF_autorelease:
1520 case OMF_dealloc:
Nico Weber80cb6e62011-08-28 22:35:17 +00001521 case OMF_finalize:
John McCallf85e1932011-06-15 23:02:42 +00001522 case OMF_retainCount:
1523 case OMF_self:
Fariborz Jahanian9670e172011-07-05 22:38:59 +00001524 case OMF_performSelector:
John McCallf85e1932011-06-15 23:02:42 +00001525 // Mismatches for these methods don't change ownership
1526 // conventions, so we don't care.
1527 return false;
1528
1529 case OMF_init: familySelector = F_init; break;
1530 case OMF_alloc: familySelector = F_alloc; break;
1531 case OMF_copy: familySelector = F_copy; break;
1532 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1533 case OMF_new: familySelector = F_new; break;
1534 }
1535
1536 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1537 ReasonSelector reasonSelector;
1538
1539 // The only reason these methods don't fall within their families is
1540 // due to unusual result types.
Stephen Hines651f13c2014-04-23 16:59:28 -07001541 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCallf85e1932011-06-15 23:02:42 +00001542 reasonSelector = R_UnrelatedReturn;
1543 } else {
1544 reasonSelector = R_NonObjectReturn;
1545 }
1546
Joerg Sonnenberger73484542013-06-26 21:31:47 +00001547 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1548 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCallf85e1932011-06-15 23:02:42 +00001549
1550 return true;
1551}
John McCall10302c02010-10-28 02:34:38 +00001552
Fariborz Jahanian8daab972008-12-05 18:18:52 +00001553void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001554 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian36bc2c62011-10-10 17:53:29 +00001555 bool IsProtocolMethodDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001556 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00001557 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1558 return;
1559
Fariborz Jahanian21761c82011-02-21 23:49:15 +00001560 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian36bc2c62011-10-10 17:53:29 +00001561 IsProtocolMethodDecl, false,
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001562 true);
Mike Stump1eb44332009-09-09 15:08:12 +00001563
Chris Lattner3aff9192009-04-11 19:58:42 +00001564 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00001565 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1566 EF = MethodDecl->param_end();
1567 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001568 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian36bc2c62011-10-10 17:53:29 +00001569 IsProtocolMethodDecl, false, true);
Fariborz Jahanian21121902011-08-08 18:03:17 +00001570 }
Fariborz Jahanian730cfb12011-08-10 17:16:30 +00001571
Fariborz Jahanian21121902011-08-08 18:03:17 +00001572 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian36bc2c62011-10-10 17:53:29 +00001573 Diag(ImpMethodDecl->getLocation(),
1574 diag::warn_conflicting_variadic);
Fariborz Jahanian21121902011-08-08 18:03:17 +00001575 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian21121902011-08-08 18:03:17 +00001576 }
Fariborz Jahanian21121902011-08-08 18:03:17 +00001577}
1578
Fariborz Jahanian36bc2c62011-10-10 17:53:29 +00001579void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1580 ObjCMethodDecl *Overridden,
1581 bool IsProtocolMethodDecl) {
1582
1583 CheckMethodOverrideReturn(*this, Method, Overridden,
1584 IsProtocolMethodDecl, true,
1585 true);
1586
1587 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00001588 IF = Overridden->param_begin(), EM = Method->param_end(),
1589 EF = Overridden->param_end();
1590 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian36bc2c62011-10-10 17:53:29 +00001591 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1592 IsProtocolMethodDecl, true, true);
1593 }
1594
1595 if (Method->isVariadic() != Overridden->isVariadic()) {
1596 Diag(Method->getLocation(),
1597 diag::warn_conflicting_overriding_variadic);
1598 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1599 }
1600}
1601
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001602/// WarnExactTypedMethods - This routine issues a warning if method
1603/// implementation declaration matches exactly that of its declaration.
1604void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1605 ObjCMethodDecl *MethodDecl,
1606 bool IsProtocolMethodDecl) {
1607 // don't issue warning when protocol method is optional because primary
1608 // class is not required to implement it and it is safe for protocol
1609 // to implement it.
1610 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1611 return;
1612 // don't issue warning when primary class's method is
1613 // depecated/unavailable.
1614 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1615 MethodDecl->hasAttr<DeprecatedAttr>())
1616 return;
1617
1618 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1619 IsProtocolMethodDecl, false, false);
1620 if (match)
1621 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00001622 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1623 EF = MethodDecl->param_end();
1624 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001625 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1626 *IM, *IF,
1627 IsProtocolMethodDecl, false, false);
1628 if (!match)
1629 break;
1630 }
1631 if (match)
1632 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall7ca13ef2011-08-08 17:32:19 +00001633 if (match)
1634 match = !(MethodDecl->isClassMethod() &&
1635 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001636
1637 if (match) {
1638 Diag(ImpMethodDecl->getLocation(),
1639 diag::warn_category_method_impl_match);
Ted Kremenek3306ec12012-02-27 22:55:11 +00001640 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1641 << MethodDecl->getDeclName();
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001642 }
1643}
1644
Mike Stump390b4cc2009-05-16 07:39:55 +00001645/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1646/// improve the efficiency of selector lookups and type checking by associating
1647/// with each protocol / interface / category the flattened instance tables. If
1648/// we used an immutable set to keep the table then it wouldn't add significant
1649/// memory cost and it would be handy for lookups.
Daniel Dunbarb20ef3e2008-08-27 05:40:03 +00001650
Stephen Hines651f13c2014-04-23 16:59:28 -07001651typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
1652typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
1653
1654static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1655 ProtocolNameSet &PNS) {
1656 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1657 PNS.insert(PDecl->getIdentifier());
1658 for (const auto *PI : PDecl->protocols())
1659 findProtocolsWithExplicitImpls(PI, PNS);
1660}
1661
1662/// Recursively populates a set with all conformed protocols in a class
1663/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1664/// attribute.
1665static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1666 ProtocolNameSet &PNS) {
1667 if (!Super)
1668 return;
1669
1670 for (const auto *I : Super->all_referenced_protocols())
1671 findProtocolsWithExplicitImpls(I, PNS);
1672
1673 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
1674}
1675
Steve Naroffefe7f362008-02-08 22:06:17 +00001676/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattner4d391482007-12-12 07:09:47 +00001677/// Declared in protocol, and those referenced by it.
Stephen Hines651f13c2014-04-23 16:59:28 -07001678static void CheckProtocolMethodDefs(Sema &S,
1679 SourceLocation ImpLoc,
1680 ObjCProtocolDecl *PDecl,
1681 bool& IncompleteImpl,
1682 const Sema::SelectorSet &InsMap,
1683 const Sema::SelectorSet &ClsMap,
1684 ObjCContainerDecl *CDecl,
1685 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001686 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1687 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1688 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanianf2838592010-03-27 21:10:05 +00001689 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1690
Daniel Dunbar7ad1b1f2008-09-04 20:01:15 +00001691 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001692 ObjCInterfaceDecl *NSIDecl = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001693
1694 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1695 // then we should check if any class in the super class hierarchy also
1696 // conforms to this protocol, either directly or via protocol inheritance.
1697 // If so, we can skip checking this protocol completely because we
1698 // know that a parent class already satisfies this protocol.
1699 //
1700 // Note: we could generalize this logic for all protocols, and merely
1701 // add the limit on looking at the super class chain for just
1702 // specially marked protocols. This may be a good optimization. This
1703 // change is restricted to 'objc_protocol_requires_explicit_implementation'
1704 // protocols for now for controlled evaluation.
1705 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
1706 if (!ProtocolsExplictImpl) {
1707 ProtocolsExplictImpl.reset(new ProtocolNameSet);
1708 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1709 }
1710 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1711 ProtocolsExplictImpl->end())
1712 return;
1713
1714 // If no super class conforms to the protocol, we should not search
1715 // for methods in the super class to implicitly satisfy the protocol.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001716 Super = nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07001717 }
1718
1719 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001720 // check to see if class implements forwardInvocation method and objects
1721 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniancd187622009-05-22 17:12:32 +00001722 // from one object to another.
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // Under such conditions, which means that every method possible is
1724 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniancd187622009-05-22 17:12:32 +00001725 // found" warnings.
1726 // FIXME: Use a general GetUnarySelector method for this.
Stephen Hines651f13c2014-04-23 16:59:28 -07001727 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1728 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniancd187622009-05-22 17:12:32 +00001729 if (InsMap.count(fISelector))
1730 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1731 // need be implemented in the implementation.
Stephen Hines651f13c2014-04-23 16:59:28 -07001732 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniancd187622009-05-22 17:12:32 +00001733 }
Mike Stump1eb44332009-09-09 15:08:12 +00001734
Fariborz Jahanian32b94be2013-01-07 19:21:03 +00001735 // If this is a forward protocol declaration, get its definition.
1736 if (!PDecl->isThisDeclarationADefinition() &&
1737 PDecl->getDefinition())
1738 PDecl = PDecl->getDefinition();
1739
Daniel Dunbar7ad1b1f2008-09-04 20:01:15 +00001740 // If a method lookup fails locally we still need to look and see if
1741 // the method was implemented by a base class or an inherited
1742 // protocol. This lookup is slow, but occurs rarely in correct code
1743 // and otherwise would terminate in a warning.
1744
Chris Lattner4d391482007-12-12 07:09:47 +00001745 // check unimplemented instance methods.
Fariborz Jahaniancd187622009-05-22 17:12:32 +00001746 if (!NSIDecl)
Stephen Hines651f13c2014-04-23 16:59:28 -07001747 for (auto *method : PDecl->instance_methods()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001748 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rose1e4691b2012-10-10 16:42:25 +00001749 !method->isPropertyAccessor() &&
1750 !InsMap.count(method->getSelector()) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001751 (!Super || !Super->lookupMethod(method->getSelector(),
1752 true /* instance */,
1753 false /* shallowCategory */,
1754 true /* followsSuper */,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001755 nullptr /* category */))) {
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001756 // If a method is not implemented in the category implementation but
1757 // has been declared in its primary class, superclass,
1758 // or in one of their protocols, no need to issue the warning.
1759 // This is because method will be implemented in the primary class
1760 // or one of its super class implementation.
1761
Fariborz Jahaniancd187622009-05-22 17:12:32 +00001762 // Ugly, but necessary. Method declared in protcol might have
1763 // have been synthesized due to a property declared in the class which
1764 // uses the protocol.
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001765 if (ObjCMethodDecl *MethodInClass =
Stephen Hines651f13c2014-04-23 16:59:28 -07001766 IDecl->lookupMethod(method->getSelector(),
1767 true /* instance */,
1768 true /* shallowCategoryLookup */,
1769 false /* followSuper */))
Jordan Rose1e4691b2012-10-10 16:42:25 +00001770 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001771 continue;
1772 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Stephen Hines651f13c2014-04-23 16:59:28 -07001773 if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc)
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001774 != DiagnosticsEngine::Ignored) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001775 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
1776 PDecl);
Fariborz Jahanian8822f7c2010-03-27 19:02:17 +00001777 }
Fariborz Jahaniancd187622009-05-22 17:12:32 +00001778 }
1779 }
Chris Lattner4d391482007-12-12 07:09:47 +00001780 // check unimplemented class methods
Stephen Hines651f13c2014-04-23 16:59:28 -07001781 for (auto *method : PDecl->class_methods()) {
Daniel Dunbar7ad1b1f2008-09-04 20:01:15 +00001782 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1783 !ClsMap.count(method->getSelector()) &&
Stephen Hines651f13c2014-04-23 16:59:28 -07001784 (!Super || !Super->lookupMethod(method->getSelector(),
1785 false /* class method */,
1786 false /* shallowCategoryLookup */,
1787 true /* followSuper */,
Stephen Hines6bcf27b2014-05-29 04:14:42 -07001788 nullptr /* category */))) {
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001789 // See above comment for instance method lookups.
Stephen Hines651f13c2014-04-23 16:59:28 -07001790 if (C && IDecl->lookupMethod(method->getSelector(),
1791 false /* class */,
1792 true /* shallowCategoryLookup */,
1793 false /* followSuper */))
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001794 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001795
Fariborz Jahanian52146832010-03-31 18:23:33 +00001796 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Stephen Hines651f13c2014-04-23 16:59:28 -07001797 if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
David Blaikied6471f72011-09-25 23:23:43 +00001798 DiagnosticsEngine::Ignored) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001799 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanian52146832010-03-31 18:23:33 +00001800 }
Fariborz Jahanian8822f7c2010-03-27 19:02:17 +00001801 }
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001802 }
Chris Lattner780f3292008-07-21 21:32:27 +00001803 // Check on this protocols's referenced protocols, recursively.
Stephen Hines651f13c2014-04-23 16:59:28 -07001804 for (auto *PI : PDecl->protocols())
1805 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
1806 CDecl, ProtocolsExplictImpl);
Chris Lattner4d391482007-12-12 07:09:47 +00001807}
1808
Fariborz Jahanian1e159bc2011-07-16 00:08:33 +00001809/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001810/// or protocol against those declared in their implementations.
1811///
Benjamin Kramer811bfcd2012-05-27 13:28:52 +00001812void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1813 const SelectorSet &ClsMap,
1814 SelectorSet &InsMapSeen,
1815 SelectorSet &ClsMapSeen,
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001816 ObjCImplDecl* IMPDecl,
1817 ObjCContainerDecl* CDecl,
1818 bool &IncompleteImpl,
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001819 bool ImmediateClass,
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001820 bool WarnCategoryMethodImpl) {
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001821 // Check and see if instance methods in class interface have been
1822 // implemented in the implementation class. If so, their types match.
Stephen Hines651f13c2014-04-23 16:59:28 -07001823 for (auto *I : CDecl->instance_methods()) {
1824 if (!InsMapSeen.insert(I->getSelector()))
Benjamin Kramer7dcff5b2013-10-14 15:16:10 +00001825 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001826 if (!I->isPropertyAccessor() &&
1827 !InsMap.count(I->getSelector())) {
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001828 if (ImmediateClass)
Stephen Hines651f13c2014-04-23 16:59:28 -07001829 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek8b43d2b2013-03-27 00:02:21 +00001830 diag::warn_undef_method_impl);
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001831 continue;
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001832 } else {
Mike Stump1eb44332009-09-09 15:08:12 +00001833 ObjCMethodDecl *ImpMethodDecl =
Stephen Hines651f13c2014-04-23 16:59:28 -07001834 IMPDecl->getInstanceMethod(I->getSelector());
1835 assert(CDecl->getInstanceMethod(I->getSelector()) &&
Argyrios Kyrtzidis2334f3a2011-08-30 19:43:21 +00001836 "Expected to find the method through lookup as well");
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001837 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001838 if (ImpMethodDecl) {
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001839 if (!WarnCategoryMethodImpl)
Stephen Hines651f13c2014-04-23 16:59:28 -07001840 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001841 isa<ObjCProtocolDecl>(CDecl));
Stephen Hines651f13c2014-04-23 16:59:28 -07001842 else if (!I->isPropertyAccessor())
1843 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001844 }
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001845 }
1846 }
Mike Stump1eb44332009-09-09 15:08:12 +00001847
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001848 // Check and see if class methods in class interface have been
1849 // implemented in the implementation class. If so, their types match.
Stephen Hines651f13c2014-04-23 16:59:28 -07001850 for (auto *I : CDecl->class_methods()) {
1851 if (!ClsMapSeen.insert(I->getSelector()))
Benjamin Kramer7dcff5b2013-10-14 15:16:10 +00001852 continue;
Stephen Hines651f13c2014-04-23 16:59:28 -07001853 if (!ClsMap.count(I->getSelector())) {
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001854 if (ImmediateClass)
Stephen Hines651f13c2014-04-23 16:59:28 -07001855 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek8b43d2b2013-03-27 00:02:21 +00001856 diag::warn_undef_method_impl);
Mike Stumpac5fc7c2009-08-04 21:02:39 +00001857 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001858 ObjCMethodDecl *ImpMethodDecl =
Stephen Hines651f13c2014-04-23 16:59:28 -07001859 IMPDecl->getClassMethod(I->getSelector());
1860 assert(CDecl->getClassMethod(I->getSelector()) &&
Argyrios Kyrtzidis2334f3a2011-08-30 19:43:21 +00001861 "Expected to find the method through lookup as well");
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001862 if (!WarnCategoryMethodImpl)
Stephen Hines651f13c2014-04-23 16:59:28 -07001863 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001864 isa<ObjCProtocolDecl>(CDecl));
1865 else
Stephen Hines651f13c2014-04-23 16:59:28 -07001866 WarnExactTypedMethods(ImpMethodDecl, I,
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001867 isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001868 }
1869 }
Fariborz Jahanianf54e3ae2010-10-08 22:59:25 +00001870
Fariborz Jahanian41594c52013-08-14 23:58:55 +00001871 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1872 // Also, check for methods declared in protocols inherited by
1873 // this protocol.
Stephen Hines651f13c2014-04-23 16:59:28 -07001874 for (auto *PI : PD->protocols())
Fariborz Jahanian41594c52013-08-14 23:58:55 +00001875 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Stephen Hines651f13c2014-04-23 16:59:28 -07001876 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian41594c52013-08-14 23:58:55 +00001877 WarnCategoryMethodImpl);
1878 }
1879
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001880 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6a6bb282012-10-23 23:06:22 +00001881 // when checking that methods in implementation match their declaration,
1882 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1883 // extension; as well as those in categories.
Douglas Gregord3297242013-01-16 23:00:23 +00001884 if (!WarnCategoryMethodImpl) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001885 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6a6bb282012-10-23 23:06:22 +00001886 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Stephen Hines651f13c2014-04-23 16:59:28 -07001887 IMPDecl, Cat, IncompleteImpl, false,
Fariborz Jahanian6a6bb282012-10-23 23:06:22 +00001888 WarnCategoryMethodImpl);
Douglas Gregord3297242013-01-16 23:00:23 +00001889 } else {
Fariborz Jahanian6a6bb282012-10-23 23:06:22 +00001890 // Also methods in class extensions need be looked at next.
Stephen Hines651f13c2014-04-23 16:59:28 -07001891 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6a6bb282012-10-23 23:06:22 +00001892 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Stephen Hines651f13c2014-04-23 16:59:28 -07001893 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6a6bb282012-10-23 23:06:22 +00001894 WarnCategoryMethodImpl);
Douglas Gregord3297242013-01-16 23:00:23 +00001895 }
1896
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001897 // Check for any implementation of a methods declared in protocol.
Stephen Hines651f13c2014-04-23 16:59:28 -07001898 for (auto *PI : I->all_referenced_protocols())
Mike Stump1eb44332009-09-09 15:08:12 +00001899 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Stephen Hines651f13c2014-04-23 16:59:28 -07001900 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001901 WarnCategoryMethodImpl);
Stephen Hines651f13c2014-04-23 16:59:28 -07001902
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001903 // FIXME. For now, we are not checking for extact match of methods
1904 // in category implementation and its primary class's super class.
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001905 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001906 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump1eb44332009-09-09 15:08:12 +00001907 IMPDecl,
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001908 I->getSuperClass(), IncompleteImpl, false);
1909 }
1910}
1911
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001912/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1913/// category matches with those implemented in its primary class and
1914/// warns each time an exact match is found.
1915void Sema::CheckCategoryVsClassMethodMatches(
1916 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001917 // Get category's primary class.
1918 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1919 if (!CatDecl)
1920 return;
1921 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1922 if (!IDecl)
1923 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07001924 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1925 SelectorSet InsMap, ClsMap;
1926
1927 for (const auto *I : CatIMPDecl->instance_methods()) {
1928 Selector Sel = I->getSelector();
1929 // When checking for methods implemented in the category, skip over
1930 // those declared in category class's super class. This is because
1931 // the super class must implement the method.
1932 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1933 continue;
1934 InsMap.insert(Sel);
1935 }
1936
1937 for (const auto *I : CatIMPDecl->class_methods()) {
1938 Selector Sel = I->getSelector();
1939 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1940 continue;
1941 ClsMap.insert(Sel);
1942 }
1943 if (InsMap.empty() && ClsMap.empty())
1944 return;
1945
Benjamin Kramer811bfcd2012-05-27 13:28:52 +00001946 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001947 bool IncompleteImpl = false;
1948 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1949 CatIMPDecl, IDecl,
Fariborz Jahanianbb3d14e2012-02-09 21:30:24 +00001950 IncompleteImpl, false,
1951 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001952}
Fariborz Jahanianeee3ef12011-07-24 20:53:26 +00001953
Fariborz Jahanian17cb3262010-05-05 21:52:17 +00001954void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00001955 ObjCContainerDecl* CDecl,
Chris Lattnercddc8882009-03-01 00:56:52 +00001956 bool IncompleteImpl) {
Benjamin Kramer811bfcd2012-05-27 13:28:52 +00001957 SelectorSet InsMap;
Chris Lattner4d391482007-12-12 07:09:47 +00001958 // Check and see if instance methods in class interface have been
1959 // implemented in the implementation class.
Stephen Hines651f13c2014-04-23 16:59:28 -07001960 for (const auto *I : IMPDecl->instance_methods())
1961 InsMap.insert(I->getSelector());
Mike Stump1eb44332009-09-09 15:08:12 +00001962
Fariborz Jahanian12bac252009-04-14 23:15:21 +00001963 // Check and see if properties declared in the interface have either 1)
1964 // an implementation or 2) there is a @synthesize/@dynamic implementation
1965 // of the property in the @implementation.
Stephen Hines651f13c2014-04-23 16:59:28 -07001966 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1967 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1968 LangOpts.ObjCRuntime.isNonFragile() &&
1969 !IDecl->isObjCRequiresPropertyDefs();
1970 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1971 }
1972
Benjamin Kramer811bfcd2012-05-27 13:28:52 +00001973 SelectorSet ClsMap;
Stephen Hines651f13c2014-04-23 16:59:28 -07001974 for (const auto *I : IMPDecl->class_methods())
1975 ClsMap.insert(I->getSelector());
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001977 // Check for type conflict of methods declared in a class/protocol and
1978 // its implementation; if any.
Benjamin Kramer811bfcd2012-05-27 13:28:52 +00001979 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump1eb44332009-09-09 15:08:12 +00001980 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1981 IMPDecl, CDecl,
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001982 IncompleteImpl, true);
Fariborz Jahanian74133072011-08-03 18:21:12 +00001983
Fariborz Jahanianfefe91e2011-07-28 23:19:50 +00001984 // check all methods implemented in category against those declared
1985 // in its primary class.
1986 if (ObjCCategoryImplDecl *CatDecl =
1987 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1988 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump1eb44332009-09-09 15:08:12 +00001989
Chris Lattner4d391482007-12-12 07:09:47 +00001990 // Check the protocol list for unimplemented methods in the @implementation
1991 // class.
Fariborz Jahanianb33f3ad2009-05-01 20:07:12 +00001992 // Check and see if class methods in class interface have been
1993 // implemented in the implementation class.
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Stephen Hines651f13c2014-04-23 16:59:28 -07001995 LazyProtocolNameSet ExplicitImplProtocols;
1996
Chris Lattnercddc8882009-03-01 00:56:52 +00001997 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Stephen Hines651f13c2014-04-23 16:59:28 -07001998 for (auto *PI : I->all_referenced_protocols())
1999 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2000 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattnercddc8882009-03-01 00:56:52 +00002001 // Check class extensions (unnamed categories)
Stephen Hines651f13c2014-04-23 16:59:28 -07002002 for (auto *Ext : I->visible_extensions())
2003 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
Chris Lattnercddc8882009-03-01 00:56:52 +00002004 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanianb106fc62009-10-05 21:32:49 +00002005 // For extended class, unimplemented methods in its protocols will
2006 // be reported in the primary class.
Fariborz Jahanian25760612010-02-15 21:55:26 +00002007 if (!C->IsClassExtension()) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002008 for (auto *P : C->protocols())
2009 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2010 IncompleteImpl, InsMap, ClsMap, CDecl,
2011 ExplicitImplProtocols);
2012 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2013 /* SynthesizeProperties */ false);
Fariborz Jahanian3ad230e2010-01-20 19:36:21 +00002014 }
Chris Lattnercddc8882009-03-01 00:56:52 +00002015 } else
David Blaikieb219cfc2011-09-23 05:06:16 +00002016 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattner4d391482007-12-12 07:09:47 +00002017}
2018
Mike Stump1eb44332009-09-09 15:08:12 +00002019/// ActOnForwardClassDeclaration -
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00002020Sema::DeclGroupPtrTy
Chris Lattner4d391482007-12-12 07:09:47 +00002021Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattnerbdbde4d2009-02-16 19:25:52 +00002022 IdentifierInfo **IdentList,
Ted Kremenekc09cba62009-11-17 23:12:20 +00002023 SourceLocation *IdentLocs,
Chris Lattnerbdbde4d2009-02-16 19:25:52 +00002024 unsigned NumElts) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00002025 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattner4d391482007-12-12 07:09:47 +00002026 for (unsigned i = 0; i != NumElts; ++i) {
2027 // Check for another declaration kind with the same name.
John McCallf36e02d2009-10-09 21:13:30 +00002028 NamedDecl *PrevDecl
Douglas Gregorc83c6872010-04-15 22:33:43 +00002029 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Douglas Gregorc0b39642010-04-15 23:40:53 +00002030 LookupOrdinaryName, ForRedeclaration);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroffc7333882008-06-05 22:57:10 +00002032 // GCC apparently allows the following idiom:
2033 //
2034 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2035 // @class XCElementToggler;
2036 //
Fariborz Jahaniane42670b2012-01-24 00:40:15 +00002037 // Here we have chosen to ignore the forward class declaration
2038 // with a warning. Since this is the implied behavior.
Richard Smith162e1c12011-04-15 14:24:37 +00002039 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCallc12c5bb2010-05-15 11:32:37 +00002040 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002041 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner5f4a6822008-11-23 23:12:31 +00002042 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCallc12c5bb2010-05-15 11:32:37 +00002043 } else {
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002044 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahaniane42670b2012-01-24 00:40:15 +00002045 // to the underlying class. Just ignore the forward class with a warning
2046 // as this will force the intended behavior which is to lookup the typedef
2047 // name.
2048 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2049 Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
2050 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2051 continue;
2052 }
Fariborz Jahaniancae27c52009-05-07 21:49:26 +00002053 }
Chris Lattner4d391482007-12-12 07:09:47 +00002054 }
Douglas Gregor7723fec2011-12-15 20:29:51 +00002055
2056 // Create a declaration to describe this forward declaration.
Douglas Gregor0af55012011-12-16 03:12:41 +00002057 ObjCInterfaceDecl *PrevIDecl
2058 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidise7e8fca2013-06-18 21:26:33 +00002059
2060 IdentifierInfo *ClassName = IdentList[i];
2061 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2062 // A previous decl with a different name is because of
2063 // @compatibility_alias, for example:
2064 // \code
2065 // @class NewImage;
2066 // @compatibility_alias OldImage NewImage;
2067 // \endcode
2068 // A lookup for 'OldImage' will return the 'NewImage' decl.
2069 //
2070 // In such a case use the real declaration name, instead of the alias one,
2071 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2072 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2073 // has been aliased.
2074 ClassName = PrevIDecl->getIdentifier();
2075 }
2076
Douglas Gregor7723fec2011-12-15 20:29:51 +00002077 ObjCInterfaceDecl *IDecl
2078 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Argyrios Kyrtzidise7e8fca2013-06-18 21:26:33 +00002079 ClassName, PrevIDecl, IdentLocs[i]);
Douglas Gregor7723fec2011-12-15 20:29:51 +00002080 IDecl->setAtEndRange(IdentLocs[i]);
Douglas Gregor7723fec2011-12-15 20:29:51 +00002081
Douglas Gregor7723fec2011-12-15 20:29:51 +00002082 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor375bb142011-12-27 22:43:10 +00002083 CheckObjCDeclScope(IDecl);
2084 DeclsInGroup.push_back(IDecl);
Chris Lattner4d391482007-12-12 07:09:47 +00002085 }
Rafael Espindola4549d7f2013-07-09 12:05:01 +00002086
2087 return BuildDeclaratorGroup(DeclsInGroup, false);
Chris Lattner4d391482007-12-12 07:09:47 +00002088}
2089
John McCall0f4c4c42011-06-16 01:15:19 +00002090static bool tryMatchRecordTypes(ASTContext &Context,
2091 Sema::MethodMatchStrategy strategy,
2092 const Type *left, const Type *right);
2093
John McCallf85e1932011-06-15 23:02:42 +00002094static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2095 QualType leftQT, QualType rightQT) {
2096 const Type *left =
2097 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2098 const Type *right =
2099 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2100
2101 if (left == right) return true;
2102
2103 // If we're doing a strict match, the types have to match exactly.
2104 if (strategy == Sema::MMS_strict) return false;
2105
2106 if (left->isIncompleteType() || right->isIncompleteType()) return false;
2107
2108 // Otherwise, use this absurdly complicated algorithm to try to
2109 // validate the basic, low-level compatibility of the two types.
2110
2111 // As a minimum, require the sizes and alignments to match.
2112 if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
2113 return false;
2114
2115 // Consider all the kinds of non-dependent canonical types:
2116 // - functions and arrays aren't possible as return and parameter types
2117
2118 // - vector types of equal size can be arbitrarily mixed
2119 if (isa<VectorType>(left)) return isa<VectorType>(right);
2120 if (isa<VectorType>(right)) return false;
2121
2122 // - references should only match references of identical type
John McCall0f4c4c42011-06-16 01:15:19 +00002123 // - structs, unions, and Objective-C objects must match more-or-less
2124 // exactly
John McCallf85e1932011-06-15 23:02:42 +00002125 // - everything else should be a scalar
2126 if (!left->isScalarType() || !right->isScalarType())
John McCall0f4c4c42011-06-16 01:15:19 +00002127 return tryMatchRecordTypes(Context, strategy, left, right);
John McCallf85e1932011-06-15 23:02:42 +00002128
John McCall1d9b3b22011-09-09 05:25:32 +00002129 // Make scalars agree in kind, except count bools as chars, and group
2130 // all non-member pointers together.
John McCallf85e1932011-06-15 23:02:42 +00002131 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2132 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2133 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2134 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall1d9b3b22011-09-09 05:25:32 +00002135 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2136 leftSK = Type::STK_ObjCObjectPointer;
2137 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2138 rightSK = Type::STK_ObjCObjectPointer;
John McCallf85e1932011-06-15 23:02:42 +00002139
2140 // Note that data member pointers and function member pointers don't
2141 // intermix because of the size differences.
2142
2143 return (leftSK == rightSK);
2144}
Chris Lattner4d391482007-12-12 07:09:47 +00002145
John McCall0f4c4c42011-06-16 01:15:19 +00002146static bool tryMatchRecordTypes(ASTContext &Context,
2147 Sema::MethodMatchStrategy strategy,
2148 const Type *lt, const Type *rt) {
2149 assert(lt && rt && lt != rt);
2150
2151 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2152 RecordDecl *left = cast<RecordType>(lt)->getDecl();
2153 RecordDecl *right = cast<RecordType>(rt)->getDecl();
2154
2155 // Require union-hood to match.
2156 if (left->isUnion() != right->isUnion()) return false;
2157
2158 // Require an exact match if either is non-POD.
2159 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2160 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2161 return false;
2162
2163 // Require size and alignment to match.
2164 if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
2165
2166 // Require fields to match.
2167 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2168 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2169 for (; li != le && ri != re; ++li, ++ri) {
2170 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2171 return false;
2172 }
2173 return (li == le && ri == re);
2174}
2175
Chris Lattner4d391482007-12-12 07:09:47 +00002176/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2177/// returns true, or false, accordingly.
2178/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCallf85e1932011-06-15 23:02:42 +00002179bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2180 const ObjCMethodDecl *right,
2181 MethodMatchStrategy strategy) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002182 if (!matchTypes(Context, strategy, left->getReturnType(),
2183 right->getReturnType()))
John McCallf85e1932011-06-15 23:02:42 +00002184 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002185
Douglas Gregor7666b032013-02-07 19:13:24 +00002186 // If either is hidden, it is not considered to match.
2187 if (left->isHidden() || right->isHidden())
2188 return false;
2189
David Blaikie4e4d0842012-03-11 07:00:24 +00002190 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002191 (left->hasAttr<NSReturnsRetainedAttr>()
2192 != right->hasAttr<NSReturnsRetainedAttr>() ||
2193 left->hasAttr<NSConsumesSelfAttr>()
2194 != right->hasAttr<NSConsumesSelfAttr>()))
2195 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002197 ObjCMethodDecl::param_const_iterator
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002198 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2199 re = right->param_end();
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00002201 for (; li != le && ri != re; ++li, ++ri) {
John McCallf85e1932011-06-15 23:02:42 +00002202 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00002203 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCallf85e1932011-06-15 23:02:42 +00002204
2205 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2206 return false;
2207
David Blaikie4e4d0842012-03-11 07:00:24 +00002208 if (getLangOpts().ObjCAutoRefCount &&
John McCallf85e1932011-06-15 23:02:42 +00002209 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2210 return false;
Chris Lattner4d391482007-12-12 07:09:47 +00002211 }
2212 return true;
2213}
2214
Douglas Gregorff310c72012-05-01 23:37:00 +00002215void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002216 // Record at the head of the list whether there were 0, 1, or >= 2 methods
2217 // inside categories.
Argyrios Kyrtzidisab3d5092013-04-27 00:10:12 +00002218 if (ObjCCategoryDecl *
2219 CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2220 if (!CD->IsClassExtension() && List->getBits() < 2)
2221 List->setBits(List->getBits()+1);
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002222
Douglas Gregor44fae522012-01-25 00:19:56 +00002223 // If the list is empty, make it a singleton list.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002224 if (List->Method == nullptr) {
Douglas Gregor44fae522012-01-25 00:19:56 +00002225 List->Method = Method;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002226 List->setNext(nullptr);
Douglas Gregorff310c72012-05-01 23:37:00 +00002227 return;
Douglas Gregor44fae522012-01-25 00:19:56 +00002228 }
2229
2230 // We've seen a method with this name, see if we have already seen this type
2231 // signature.
2232 ObjCMethodList *Previous = List;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002233 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregorfc46be92013-06-21 00:20:25 +00002234 // If we are building a module, keep all of the methods.
2235 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2236 continue;
2237
Douglas Gregor5ac4b692012-01-25 00:49:42 +00002238 if (!MatchTwoMethodDeclarations(Method, List->Method))
Douglas Gregor44fae522012-01-25 00:19:56 +00002239 continue;
2240
2241 ObjCMethodDecl *PrevObjCMethod = List->Method;
2242
2243 // Propagate the 'defined' bit.
2244 if (Method->isDefined())
2245 PrevObjCMethod->setDefined(true);
2246
2247 // If a method is deprecated, push it in the global pool.
2248 // This is used for better diagnostics.
2249 if (Method->isDeprecated()) {
2250 if (!PrevObjCMethod->isDeprecated())
2251 List->Method = Method;
2252 }
2253 // If new method is unavailable, push it into global pool
2254 // unless previous one is deprecated.
2255 if (Method->isUnavailable()) {
2256 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2257 List->Method = Method;
2258 }
2259
Douglas Gregorff310c72012-05-01 23:37:00 +00002260 return;
Douglas Gregor44fae522012-01-25 00:19:56 +00002261 }
2262
2263 // We have a new signature for an existing method - add it.
2264 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregor5ac4b692012-01-25 00:49:42 +00002265 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002266 Previous->setNext(new (Mem) ObjCMethodList(Method, nullptr));
Douglas Gregor44fae522012-01-25 00:19:56 +00002267}
2268
Sebastian Redldb9d2142010-08-02 23:18:59 +00002269/// \brief Read the contents of the method pool for a given selector from
2270/// external storage.
Douglas Gregor5ac4b692012-01-25 00:49:42 +00002271void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002272 assert(ExternalSource && "We need an external AST source");
Douglas Gregor5ac4b692012-01-25 00:49:42 +00002273 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002274}
2275
Douglas Gregorff310c72012-05-01 23:37:00 +00002276void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redldb9d2142010-08-02 23:18:59 +00002277 bool instance) {
Argyrios Kyrtzidis9a0b6b42012-03-12 18:34:26 +00002278 // Ignore methods of invalid containers.
2279 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregorff310c72012-05-01 23:37:00 +00002280 return;
Argyrios Kyrtzidis9a0b6b42012-03-12 18:34:26 +00002281
Douglas Gregor0d266d62012-01-25 00:59:09 +00002282 if (ExternalSource)
2283 ReadMethodPool(Method->getSelector());
2284
Sebastian Redldb9d2142010-08-02 23:18:59 +00002285 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor0d266d62012-01-25 00:59:09 +00002286 if (Pos == MethodPool.end())
2287 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2288 GlobalMethods())).first;
Douglas Gregor44fae522012-01-25 00:19:56 +00002289
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00002290 Method->setDefined(impl);
Douglas Gregor44fae522012-01-25 00:19:56 +00002291
Sebastian Redldb9d2142010-08-02 23:18:59 +00002292 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregorff310c72012-05-01 23:37:00 +00002293 addMethodToGlobalList(&Entry, Method);
Chris Lattner4d391482007-12-12 07:09:47 +00002294}
2295
John McCallf85e1932011-06-15 23:02:42 +00002296/// Determines if this is an "acceptable" loose mismatch in the global
2297/// method pool. This exists mostly as a hack to get around certain
2298/// global mismatches which we can't afford to make warnings / errors.
2299/// Really, what we want is a way to take a method out of the global
2300/// method pool.
2301static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2302 ObjCMethodDecl *other) {
2303 if (!chosen->isInstanceMethod())
2304 return false;
2305
2306 Selector sel = chosen->getSelector();
2307 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2308 return false;
2309
2310 // Don't complain about mismatches for -length if the method we
2311 // chose has an integral result type.
Stephen Hines651f13c2014-04-23 16:59:28 -07002312 return (chosen->getReturnType()->isIntegerType());
John McCallf85e1932011-06-15 23:02:42 +00002313}
2314
Sebastian Redldb9d2142010-08-02 23:18:59 +00002315ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian6b308f62010-08-09 23:27:58 +00002316 bool receiverIdOrClass,
Sebastian Redldb9d2142010-08-02 23:18:59 +00002317 bool warn, bool instance) {
Douglas Gregor0d266d62012-01-25 00:59:09 +00002318 if (ExternalSource)
2319 ReadMethodPool(Sel);
2320
Sebastian Redldb9d2142010-08-02 23:18:59 +00002321 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor0d266d62012-01-25 00:59:09 +00002322 if (Pos == MethodPool.end())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002323 return nullptr;
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002324
Douglas Gregorf0e00042013-01-16 18:47:38 +00002325 // Gather the non-hidden methods.
Sebastian Redldb9d2142010-08-02 23:18:59 +00002326 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelme7205c02013-08-10 12:33:24 +00002327 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidis2e3d8c02013-04-17 00:08:58 +00002328 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Douglas Gregorf0e00042013-01-16 18:47:38 +00002329 if (M->Method && !M->Method->isHidden()) {
2330 // If we're not supposed to warn about mismatches, we're done.
2331 if (!warn)
2332 return M->Method;
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Douglas Gregorf0e00042013-01-16 18:47:38 +00002334 Methods.push_back(M->Method);
Sebastian Redldb9d2142010-08-02 23:18:59 +00002335 }
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002336 }
Douglas Gregorf0e00042013-01-16 18:47:38 +00002337
2338 // If there aren't any visible methods, we're done.
2339 // FIXME: Recover if there are any known-but-hidden methods?
2340 if (Methods.empty())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002341 return nullptr;
Douglas Gregorf0e00042013-01-16 18:47:38 +00002342
2343 if (Methods.size() == 1)
2344 return Methods[0];
2345
2346 // We found multiple methods, so we may have to complain.
2347 bool issueDiagnostic = false, issueError = false;
2348
2349 // We support a warning which complains about *any* difference in
2350 // method signature.
2351 bool strictSelectorMatch =
2352 (receiverIdOrClass && warn &&
2353 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
2354 R.getBegin())
2355 != DiagnosticsEngine::Ignored));
2356 if (strictSelectorMatch) {
2357 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2358 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2359 issueDiagnostic = true;
2360 break;
2361 }
2362 }
2363 }
2364
2365 // If we didn't see any strict differences, we won't see any loose
2366 // differences. In ARC, however, we also need to check for loose
2367 // mismatches, because most of them are errors.
2368 if (!strictSelectorMatch ||
2369 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2370 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2371 // This checks if the methods differ in type mismatch.
2372 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2373 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2374 issueDiagnostic = true;
2375 if (getLangOpts().ObjCAutoRefCount)
2376 issueError = true;
2377 break;
2378 }
2379 }
2380
2381 if (issueDiagnostic) {
2382 if (issueError)
2383 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2384 else if (strictSelectorMatch)
2385 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2386 else
2387 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2388
2389 Diag(Methods[0]->getLocStart(),
2390 issueError ? diag::note_possibility : diag::note_using)
2391 << Methods[0]->getSourceRange();
2392 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2393 Diag(Methods[I]->getLocStart(), diag::note_also_found)
2394 << Methods[I]->getSourceRange();
2395 }
2396 }
2397 return Methods[0];
Douglas Gregorf0aaf7a2009-04-24 21:10:55 +00002398}
2399
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00002400ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redldb9d2142010-08-02 23:18:59 +00002401 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2402 if (Pos == MethodPool.end())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002403 return nullptr;
Sebastian Redldb9d2142010-08-02 23:18:59 +00002404
2405 GlobalMethods &Methods = Pos->second;
Stephen Hines651f13c2014-04-23 16:59:28 -07002406 for (const ObjCMethodList *Method = &Methods.first; Method;
2407 Method = Method->getNext())
2408 if (Method->Method && Method->Method->isDefined())
2409 return Method->Method;
2410
2411 for (const ObjCMethodList *Method = &Methods.second; Method;
2412 Method = Method->getNext())
2413 if (Method->Method && Method->Method->isDefined())
2414 return Method->Method;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002415 return nullptr;
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00002416}
2417
Fariborz Jahanianf98c6882013-05-30 21:48:58 +00002418static void
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002419HelperSelectorsForTypoCorrection(
2420 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2421 StringRef Typo, const ObjCMethodDecl * Method) {
2422 const unsigned MaxEditDistance = 1;
2423 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieu4fe96442013-06-06 02:22:29 +00002424 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002425
2426 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2427 if (MinPossibleEditDistance > 0 &&
2428 Typo.size() / MinPossibleEditDistance < 1)
2429 return;
2430 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2431 if (EditDistance > MaxEditDistance)
2432 return;
2433 if (EditDistance == BestEditDistance)
2434 BestMethod.push_back(Method);
2435 else if (EditDistance < BestEditDistance) {
2436 BestMethod.clear();
2437 BestMethod.push_back(Method);
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002438 }
2439}
2440
Fariborz Jahaniand395e342013-06-17 17:10:54 +00002441static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2442 QualType ObjectType) {
2443 if (ObjectType.isNull())
2444 return true;
2445 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2446 return true;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002447 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
2448 nullptr;
Fariborz Jahaniand395e342013-06-17 17:10:54 +00002449}
2450
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002451const ObjCMethodDecl *
Fariborz Jahaniand395e342013-06-17 17:10:54 +00002452Sema::SelectorsForTypoCorrection(Selector Sel,
2453 QualType ObjectType) {
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002454 unsigned NumArgs = Sel.getNumArgs();
2455 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian419245e2013-06-18 15:31:36 +00002456 bool ObjectIsId = true, ObjectIsClass = true;
2457 if (ObjectType.isNull())
2458 ObjectIsId = ObjectIsClass = false;
2459 else if (!ObjectType->isObjCObjectPointerType())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002460 return nullptr;
Fariborz Jahanian419245e2013-06-18 15:31:36 +00002461 else if (const ObjCObjectPointerType *ObjCPtr =
2462 ObjectType->getAsObjCInterfacePointerType()) {
2463 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2464 ObjectIsId = ObjectIsClass = false;
2465 }
2466 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2467 ObjectIsClass = false;
2468 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2469 ObjectIsId = false;
2470 else
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002471 return nullptr;
2472
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002473 for (GlobalMethodPool::iterator b = MethodPool.begin(),
2474 e = MethodPool.end(); b != e; b++) {
2475 // instance methods
2476 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2477 if (M->Method &&
Fariborz Jahaniancd9c9b52013-06-18 17:10:58 +00002478 (M->Method->getSelector().getNumArgs() == NumArgs) &&
2479 (M->Method->getSelector() != Sel)) {
Fariborz Jahanian419245e2013-06-18 15:31:36 +00002480 if (ObjectIsId)
2481 Methods.push_back(M->Method);
2482 else if (!ObjectIsClass &&
2483 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2484 Methods.push_back(M->Method);
2485 }
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002486 // class methods
2487 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2488 if (M->Method &&
Fariborz Jahaniancd9c9b52013-06-18 17:10:58 +00002489 (M->Method->getSelector().getNumArgs() == NumArgs) &&
2490 (M->Method->getSelector() != Sel)) {
Fariborz Jahanian419245e2013-06-18 15:31:36 +00002491 if (ObjectIsClass)
2492 Methods.push_back(M->Method);
2493 else if (!ObjectIsId &&
2494 HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2495 Methods.push_back(M->Method);
2496 }
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002497 }
2498
2499 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2500 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2501 HelperSelectorsForTypoCorrection(SelectedMethods,
2502 Sel.getAsString(), Methods[i]);
2503 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002504 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian9464a082013-06-05 18:46:14 +00002505}
2506
Fariborz Jahanianf98c6882013-05-30 21:48:58 +00002507/// DiagnoseDuplicateIvars -
Fariborz Jahanianf914b972010-02-23 23:41:11 +00002508/// Check for duplicate ivars in the entire class at the start of
James Dennett1dfbd922012-06-14 21:40:34 +00002509/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanianf914b972010-02-23 23:41:11 +00002510/// add ivars to a class in random order which will not be known until
James Dennett1dfbd922012-06-14 21:40:34 +00002511/// class's \@implementation is seen.
Fariborz Jahanianf914b972010-02-23 23:41:11 +00002512void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2513 ObjCInterfaceDecl *SID) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002514 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanianf914b972010-02-23 23:41:11 +00002515 if (Ivar->isInvalidDecl())
2516 continue;
2517 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2518 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2519 if (prevIvar) {
2520 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2521 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2522 Ivar->setInvalidDecl();
2523 }
2524 }
2525 }
2526}
2527
Erik Verbruggend64251f2011-12-06 09:25:23 +00002528Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2529 switch (CurContext->getDeclKind()) {
2530 case Decl::ObjCInterface:
2531 return Sema::OCK_Interface;
2532 case Decl::ObjCProtocol:
2533 return Sema::OCK_Protocol;
2534 case Decl::ObjCCategory:
2535 if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2536 return Sema::OCK_ClassExtension;
2537 else
2538 return Sema::OCK_Category;
2539 case Decl::ObjCImplementation:
2540 return Sema::OCK_Implementation;
2541 case Decl::ObjCCategoryImpl:
2542 return Sema::OCK_CategoryImplementation;
2543
2544 default:
2545 return Sema::OCK_None;
2546 }
2547}
2548
Fariborz Jahaniana3c62462013-07-16 15:33:19 +00002549// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm0111e4d2013-07-17 21:14:35 +00002550Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahanian80f8aca2013-07-17 00:05:08 +00002551 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggend64251f2011-12-06 09:25:23 +00002552 if (getObjCContainerKind() == Sema::OCK_None)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002553 return nullptr;
Erik Verbruggend64251f2011-12-06 09:25:23 +00002554
2555 assert(AtEnd.isValid() && "Invalid location for '@end'");
2556
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00002557 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2558 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian63e963c2009-11-16 18:57:01 +00002559
Mike Stump1eb44332009-09-09 15:08:12 +00002560 bool isInterfaceDeclKind =
Chris Lattnerf8d17a52008-03-16 21:17:37 +00002561 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2562 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002563 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroff09c47192009-01-09 15:36:25 +00002564
Steve Naroff0701bbb2009-01-08 17:28:14 +00002565 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2566 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2567 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2568
Fariborz Jahaniana3c62462013-07-16 15:33:19 +00002569 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002570 ObjCMethodDecl *Method =
John McCalld226f652010-08-21 09:40:31 +00002571 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattner4d391482007-12-12 07:09:47 +00002572
2573 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002574 if (Method->isInstanceMethod()) {
Chris Lattner4d391482007-12-12 07:09:47 +00002575 /// Check for instance method of the same name with incompatible types
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002576 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump1eb44332009-09-09 15:08:12 +00002577 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattner4d391482007-12-12 07:09:47 +00002578 : false;
Mike Stump1eb44332009-09-09 15:08:12 +00002579 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman82b4e762008-12-16 20:15:50 +00002580 || (checkIdenticalMethods && match)) {
Chris Lattner5f4a6822008-11-23 23:12:31 +00002581 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattner077bf5e2008-11-24 03:33:13 +00002582 << Method->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002583 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregorbdb2d502010-12-21 17:34:17 +00002584 Method->setInvalidDecl();
Chris Lattner4d391482007-12-12 07:09:47 +00002585 } else {
Fariborz Jahanian72096462011-12-13 19:40:34 +00002586 if (PrevMethod) {
Argyrios Kyrtzidis3a919e72011-10-14 08:02:31 +00002587 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanian72096462011-12-13 19:40:34 +00002588 if (!Context.getSourceManager().isInSystemHeader(
2589 Method->getLocation()))
2590 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2591 << Method->getDeclName();
2592 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2593 }
Chris Lattner4d391482007-12-12 07:09:47 +00002594 InsMap[Method->getSelector()] = Method;
2595 /// The following allows us to typecheck messages to "id".
Douglas Gregorff310c72012-05-01 23:37:00 +00002596 AddInstanceMethodToGlobalPool(Method);
Chris Lattner4d391482007-12-12 07:09:47 +00002597 }
Mike Stumpac5fc7c2009-08-04 21:02:39 +00002598 } else {
Chris Lattner4d391482007-12-12 07:09:47 +00002599 /// Check for class method of the same name with incompatible types
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002600 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump1eb44332009-09-09 15:08:12 +00002601 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattner4d391482007-12-12 07:09:47 +00002602 : false;
Mike Stump1eb44332009-09-09 15:08:12 +00002603 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman82b4e762008-12-16 20:15:50 +00002604 || (checkIdenticalMethods && match)) {
Chris Lattner5f4a6822008-11-23 23:12:31 +00002605 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattner077bf5e2008-11-24 03:33:13 +00002606 << Method->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002607 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregorbdb2d502010-12-21 17:34:17 +00002608 Method->setInvalidDecl();
Chris Lattner4d391482007-12-12 07:09:47 +00002609 } else {
Fariborz Jahanian72096462011-12-13 19:40:34 +00002610 if (PrevMethod) {
Argyrios Kyrtzidis3a919e72011-10-14 08:02:31 +00002611 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanian72096462011-12-13 19:40:34 +00002612 if (!Context.getSourceManager().isInSystemHeader(
2613 Method->getLocation()))
2614 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2615 << Method->getDeclName();
2616 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2617 }
Chris Lattner4d391482007-12-12 07:09:47 +00002618 ClsMap[Method->getSelector()] = Method;
Douglas Gregorff310c72012-05-01 23:37:00 +00002619 AddFactoryMethodToGlobalPool(Method);
Chris Lattner4d391482007-12-12 07:09:47 +00002620 }
2621 }
2622 }
Douglas Gregorb892d702013-01-21 19:42:21 +00002623 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2624 // Nothing to do here.
Steve Naroff09c47192009-01-09 15:36:25 +00002625 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian77e14bd2008-12-06 19:59:02 +00002626 // Categories are used to extend the class by declaring new methods.
Mike Stump1eb44332009-09-09 15:08:12 +00002627 // By the same token, they are also used to add new properties. No
Fariborz Jahanian77e14bd2008-12-06 19:59:02 +00002628 // need to compare the added property to those in the class.
Daniel Dunbarb20ef3e2008-08-27 05:40:03 +00002629
Fariborz Jahanian88f5e9b2010-12-10 23:36:33 +00002630 if (C->IsClassExtension()) {
2631 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2632 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanian88f5e9b2010-12-10 23:36:33 +00002633 }
Chris Lattner4d391482007-12-12 07:09:47 +00002634 }
Steve Naroff09c47192009-01-09 15:36:25 +00002635 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian25760612010-02-15 21:55:26 +00002636 if (CDecl->getIdentifier())
2637 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2638 // user-defined setter/getter. It also synthesizes setter/getter methods
2639 // and adds them to the DeclContext and global method pools.
Stephen Hines651f13c2014-04-23 16:59:28 -07002640 for (auto *I : CDecl->properties())
2641 ProcessPropertyDecl(I, CDecl);
Ted Kremenek782f2f52010-01-07 01:20:12 +00002642 CDecl->setAtEndRange(AtEnd);
Steve Naroff09c47192009-01-09 15:36:25 +00002643 }
2644 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenek782f2f52010-01-07 01:20:12 +00002645 IC->setAtEndRange(AtEnd);
Fariborz Jahanian7ca8b062009-11-11 22:40:11 +00002646 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanianc78f6842010-12-11 18:39:37 +00002647 // Any property declared in a class extension might have user
2648 // declared setter or getter in current class extension or one
2649 // of the other class extensions. Mark them as synthesized as
2650 // property will be synthesized when property with same name is
2651 // seen in the @implementation.
Stephen Hines651f13c2014-04-23 16:59:28 -07002652 for (const auto *Ext : IDecl->visible_extensions()) {
2653 for (const auto *Property : Ext->properties()) {
Fariborz Jahanianc78f6842010-12-11 18:39:37 +00002654 // Skip over properties declared @dynamic
2655 if (const ObjCPropertyImplDecl *PIDecl
2656 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2657 if (PIDecl->getPropertyImplementation()
2658 == ObjCPropertyImplDecl::Dynamic)
2659 continue;
Douglas Gregord3297242013-01-16 23:00:23 +00002660
Stephen Hines651f13c2014-04-23 16:59:28 -07002661 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregord3297242013-01-16 23:00:23 +00002662 if (ObjCMethodDecl *GetterMethod
2663 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rose1e4691b2012-10-10 16:42:25 +00002664 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanianc78f6842010-12-11 18:39:37 +00002665 if (!Property->isReadOnly())
Douglas Gregord3297242013-01-16 23:00:23 +00002666 if (ObjCMethodDecl *SetterMethod
2667 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rose1e4691b2012-10-10 16:42:25 +00002668 SetterMethod->setPropertyAccessor(true);
Douglas Gregord3297242013-01-16 23:00:23 +00002669 }
Fariborz Jahanianc78f6842010-12-11 18:39:37 +00002670 }
2671 }
Fariborz Jahanian17cb3262010-05-05 21:52:17 +00002672 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian7ca8b062009-11-11 22:40:11 +00002673 AtomicPropertySetterGetterRules(IC, IDecl);
John McCallf85e1932011-06-15 23:02:42 +00002674 DiagnoseOwningPropertyGetterSynthesis(IC);
Stephen Hines651f13c2014-04-23 16:59:28 -07002675 DiagnoseUnusedBackingIvarInAccessor(S, IC);
2676 if (IDecl->hasDesignatedInitializers())
2677 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2678
Patrick Beardb2f68202012-04-06 18:12:22 +00002679 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002680 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardb2f68202012-04-06 18:12:22 +00002681 // This class has no superclass, so check that it has been marked with
2682 // __attribute((objc_root_class)).
2683 if (!HasRootClassAttr) {
2684 SourceLocation DeclLoc(IDecl->getLocation());
Stephen Hines6bcf27b2014-05-29 04:14:42 -07002685 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardb2f68202012-04-06 18:12:22 +00002686 Diag(DeclLoc, diag::warn_objc_root_class_missing)
2687 << IDecl->getIdentifier();
2688 // See if NSObject is in the current scope, and if it is, suggest
2689 // adding " : NSObject " to the class declaration.
2690 NamedDecl *IF = LookupSingleName(TUScope,
2691 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2692 DeclLoc, LookupOrdinaryName);
2693 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2694 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2695 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2696 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2697 } else {
2698 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2699 }
2700 }
2701 } else if (HasRootClassAttr) {
2702 // Complain that only root classes may have this attribute.
2703 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2704 }
2705
John McCall260611a2012-06-20 06:18:46 +00002706 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianf914b972010-02-23 23:41:11 +00002707 while (IDecl->getSuperClass()) {
2708 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2709 IDecl = IDecl->getSuperClass();
2710 }
Patrick Beardb2f68202012-04-06 18:12:22 +00002711 }
Fariborz Jahanian7ca8b062009-11-11 22:40:11 +00002712 }
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00002713 SetIvarInitializers(IC);
Mike Stump1eb44332009-09-09 15:08:12 +00002714 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroff09c47192009-01-09 15:36:25 +00002715 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenek782f2f52010-01-07 01:20:12 +00002716 CatImplClass->setAtEndRange(AtEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002717
Chris Lattner4d391482007-12-12 07:09:47 +00002718 // Find category interface decl and then check that all methods declared
Daniel Dunbarb20ef3e2008-08-27 05:40:03 +00002719 // in this interface are implemented in the category @implementation.
Chris Lattner97a58872009-02-16 18:32:47 +00002720 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregord3297242013-01-16 23:00:23 +00002721 if (ObjCCategoryDecl *Cat
2722 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2723 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattner4d391482007-12-12 07:09:47 +00002724 }
2725 }
2726 }
Chris Lattner682bf922009-03-29 16:50:03 +00002727 if (isInterfaceDeclKind) {
2728 // Reject invalid vardecls.
Fariborz Jahaniana3c62462013-07-16 15:33:19 +00002729 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov18062392013-08-27 13:15:56 +00002730 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner682bf922009-03-29 16:50:03 +00002731 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2732 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar5466c7b2009-04-14 02:25:56 +00002733 if (!VDecl->hasExternalStorage())
Steve Naroff87454162009-04-13 17:58:46 +00002734 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanianb31cb7f2009-03-21 18:06:45 +00002735 }
Chris Lattner682bf922009-03-29 16:50:03 +00002736 }
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002737 }
Fariborz Jahanian10af8792011-08-29 17:33:12 +00002738 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisb4a686d2011-10-17 19:48:13 +00002739
Fariborz Jahaniana3c62462013-07-16 15:33:19 +00002740 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov18062392013-08-27 13:15:56 +00002741 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidisc14a03d2011-11-23 20:27:36 +00002742 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2743 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisb4a686d2011-10-17 19:48:13 +00002744 Consumer.HandleTopLevelDeclInObjCContainer(DG);
2745 }
Erik Verbruggend64251f2011-12-06 09:25:23 +00002746
Dmitri Gribenkoabd56c82012-07-13 01:06:46 +00002747 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggend64251f2011-12-06 09:25:23 +00002748 return ClassDecl;
Chris Lattner4d391482007-12-12 07:09:47 +00002749}
2750
2751
2752/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2753/// objective-c's type qualifier from the parser version of the same info.
Mike Stump1eb44332009-09-09 15:08:12 +00002754static Decl::ObjCDeclQualifier
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002755CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCall09e2c522011-05-01 03:04:29 +00002756 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattner4d391482007-12-12 07:09:47 +00002757}
2758
Douglas Gregor926df6c2011-06-11 01:09:30 +00002759/// \brief Check whether the declared result type of the given Objective-C
2760/// method declaration is compatible with the method's class.
2761///
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00002762static Sema::ResultTypeCompatibilityKind
Douglas Gregor926df6c2011-06-11 01:09:30 +00002763CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2764 ObjCInterfaceDecl *CurrentClass) {
Stephen Hines651f13c2014-04-23 16:59:28 -07002765 QualType ResultType = Method->getReturnType();
2766
Douglas Gregor926df6c2011-06-11 01:09:30 +00002767 // If an Objective-C method inherits its related result type, then its
2768 // declared result type must be compatible with its own class type. The
2769 // declared result type is compatible if:
2770 if (const ObjCObjectPointerType *ResultObjectType
2771 = ResultType->getAs<ObjCObjectPointerType>()) {
2772 // - it is id or qualified id, or
2773 if (ResultObjectType->isObjCIdType() ||
2774 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00002775 return Sema::RTC_Compatible;
Douglas Gregor926df6c2011-06-11 01:09:30 +00002776
2777 if (CurrentClass) {
2778 if (ObjCInterfaceDecl *ResultClass
2779 = ResultObjectType->getInterfaceDecl()) {
2780 // - it is the same as the method's class type, or
Douglas Gregor60ef3082011-12-15 00:29:59 +00002781 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00002782 return Sema::RTC_Compatible;
Douglas Gregor926df6c2011-06-11 01:09:30 +00002783
2784 // - it is a superclass of the method's class type
2785 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00002786 return Sema::RTC_Compatible;
Douglas Gregor926df6c2011-06-11 01:09:30 +00002787 }
Douglas Gregore97179c2011-09-08 01:46:34 +00002788 } else {
2789 // Any Objective-C pointer type might be acceptable for a protocol
2790 // method; we just don't know.
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00002791 return Sema::RTC_Unknown;
Douglas Gregor926df6c2011-06-11 01:09:30 +00002792 }
2793 }
2794
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00002795 return Sema::RTC_Incompatible;
Douglas Gregor926df6c2011-06-11 01:09:30 +00002796}
2797
John McCall6c2c2502011-07-22 02:45:48 +00002798namespace {
2799/// A helper class for searching for methods which a particular method
2800/// overrides.
2801class OverrideSearch {
Daniel Dunbarb732fce2012-02-29 03:04:05 +00002802public:
John McCall6c2c2502011-07-22 02:45:48 +00002803 Sema &S;
2804 ObjCMethodDecl *Method;
Daniel Dunbarb732fce2012-02-29 03:04:05 +00002805 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCall6c2c2502011-07-22 02:45:48 +00002806 bool Recursive;
2807
2808public:
2809 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2810 Selector selector = method->getSelector();
2811
2812 // Bypass this search if we've never seen an instance/class method
2813 // with this selector before.
2814 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2815 if (it == S.MethodPool.end()) {
Axel Naumann0ec56b72012-10-18 19:05:02 +00002816 if (!S.getExternalSource()) return;
Douglas Gregor5ac4b692012-01-25 00:49:42 +00002817 S.ReadMethodPool(selector);
2818
2819 it = S.MethodPool.find(selector);
2820 if (it == S.MethodPool.end())
2821 return;
John McCall6c2c2502011-07-22 02:45:48 +00002822 }
2823 ObjCMethodList &list =
2824 method->isInstanceMethod() ? it->second.first : it->second.second;
2825 if (!list.Method) return;
2826
2827 ObjCContainerDecl *container
2828 = cast<ObjCContainerDecl>(method->getDeclContext());
2829
2830 // Prevent the search from reaching this container again. This is
2831 // important with categories, which override methods from the
2832 // interface and each other.
Douglas Gregorc9683342012-05-03 21:25:24 +00002833 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2834 searchFromContainer(container);
Douglas Gregordd872242012-05-17 22:39:14 +00002835 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2836 searchFromContainer(Interface);
Douglas Gregorc9683342012-05-03 21:25:24 +00002837 } else {
2838 searchFromContainer(container);
2839 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00002840 }
John McCall6c2c2502011-07-22 02:45:48 +00002841
Daniel Dunbarb732fce2012-02-29 03:04:05 +00002842 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
John McCall6c2c2502011-07-22 02:45:48 +00002843 iterator begin() const { return Overridden.begin(); }
2844 iterator end() const { return Overridden.end(); }
2845
2846private:
2847 void searchFromContainer(ObjCContainerDecl *container) {
2848 if (container->isInvalidDecl()) return;
2849
2850 switch (container->getDeclKind()) {
2851#define OBJCCONTAINER(type, base) \
2852 case Decl::type: \
2853 searchFrom(cast<type##Decl>(container)); \
2854 break;
2855#define ABSTRACT_DECL(expansion)
2856#define DECL(type, base) \
2857 case Decl::type:
2858#include "clang/AST/DeclNodes.inc"
2859 llvm_unreachable("not an ObjC container!");
2860 }
2861 }
2862
2863 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregor5e2a1ff2012-01-01 19:29:29 +00002864 if (!protocol->hasDefinition())
2865 return;
2866
John McCall6c2c2502011-07-22 02:45:48 +00002867 // A method in a protocol declaration overrides declarations from
2868 // referenced ("parent") protocols.
2869 search(protocol->getReferencedProtocols());
2870 }
2871
2872 void searchFrom(ObjCCategoryDecl *category) {
2873 // A method in a category declaration overrides declarations from
2874 // the main class and from protocols the category references.
Douglas Gregorc9683342012-05-03 21:25:24 +00002875 // The main class is handled in the constructor.
John McCall6c2c2502011-07-22 02:45:48 +00002876 search(category->getReferencedProtocols());
2877 }
2878
2879 void searchFrom(ObjCCategoryImplDecl *impl) {
2880 // A method in a category definition that has a category
2881 // declaration overrides declarations from the category
2882 // declaration.
2883 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2884 search(category);
Douglas Gregordd872242012-05-17 22:39:14 +00002885 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2886 search(Interface);
John McCall6c2c2502011-07-22 02:45:48 +00002887
2888 // Otherwise it overrides declarations from the class.
Douglas Gregordd872242012-05-17 22:39:14 +00002889 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2890 search(Interface);
John McCall6c2c2502011-07-22 02:45:48 +00002891 }
2892 }
2893
2894 void searchFrom(ObjCInterfaceDecl *iface) {
2895 // A method in a class declaration overrides declarations from
Douglas Gregor2e5c15b2011-12-15 05:27:12 +00002896 if (!iface->hasDefinition())
2897 return;
2898
John McCall6c2c2502011-07-22 02:45:48 +00002899 // - categories,
Stephen Hines651f13c2014-04-23 16:59:28 -07002900 for (auto *Cat : iface->known_categories())
2901 search(Cat);
John McCall6c2c2502011-07-22 02:45:48 +00002902
2903 // - the super class, and
2904 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2905 search(super);
2906
2907 // - any referenced protocols.
2908 search(iface->getReferencedProtocols());
2909 }
2910
2911 void searchFrom(ObjCImplementationDecl *impl) {
2912 // A method in a class implementation overrides declarations from
2913 // the class interface.
Douglas Gregordd872242012-05-17 22:39:14 +00002914 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2915 search(Interface);
John McCall6c2c2502011-07-22 02:45:48 +00002916 }
2917
2918
2919 void search(const ObjCProtocolList &protocols) {
2920 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2921 i != e; ++i)
2922 search(*i);
2923 }
2924
2925 void search(ObjCContainerDecl *container) {
John McCall6c2c2502011-07-22 02:45:48 +00002926 // Check for a method in this container which matches this selector.
2927 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidis04593d02013-03-29 21:51:48 +00002928 Method->isInstanceMethod(),
2929 /*AllowHidden=*/true);
John McCall6c2c2502011-07-22 02:45:48 +00002930
2931 // If we find one, record it and bail out.
2932 if (meth) {
2933 Overridden.insert(meth);
2934 return;
2935 }
2936
2937 // Otherwise, search for methods that a hypothetical method here
2938 // would have overridden.
2939
2940 // Note that we're now in a recursive case.
2941 Recursive = true;
2942
2943 searchFromContainer(container);
2944 }
2945};
Douglas Gregor926df6c2011-06-11 01:09:30 +00002946}
2947
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00002948void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
2949 ObjCInterfaceDecl *CurrentClass,
2950 ResultTypeCompatibilityKind RTC) {
2951 // Search for overridden methods and merge information down from them.
2952 OverrideSearch overrides(*this, ObjCMethod);
2953 // Keep track if the method overrides any method in the class's base classes,
2954 // its protocols, or its categories' protocols; we will keep that info
2955 // in the ObjCMethodDecl.
2956 // For this info, a method in an implementation is not considered as
2957 // overriding the same method in the interface or its categories.
2958 bool hasOverriddenMethodsInBaseOrProtocol = false;
2959 for (OverrideSearch::iterator
2960 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2961 ObjCMethodDecl *overridden = *i;
2962
Argyrios Kyrtzidise7a77722013-04-17 00:09:08 +00002963 if (!hasOverriddenMethodsInBaseOrProtocol) {
2964 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
2965 CurrentClass != overridden->getClassInterface() ||
2966 overridden->isOverriding()) {
2967 hasOverriddenMethodsInBaseOrProtocol = true;
2968
2969 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
2970 // OverrideSearch will return as "overridden" the same method in the
2971 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
2972 // check whether a category of a base class introduced a method with the
2973 // same selector, after the interface method declaration.
2974 // To avoid unnecessary lookups in the majority of cases, we use the
2975 // extra info bits in GlobalMethodPool to check whether there were any
2976 // category methods with this selector.
2977 GlobalMethodPool::iterator It =
2978 MethodPool.find(ObjCMethod->getSelector());
2979 if (It != MethodPool.end()) {
2980 ObjCMethodList &List =
2981 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
2982 unsigned CategCount = List.getBits();
2983 if (CategCount > 0) {
2984 // If the method is in a category we'll do lookup if there were at
2985 // least 2 category methods recorded, otherwise only one will do.
2986 if (CategCount > 1 ||
2987 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
2988 OverrideSearch overrides(*this, overridden);
2989 for (OverrideSearch::iterator
2990 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
2991 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidisab3d5092013-04-27 00:10:12 +00002992 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
2993 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidise7a77722013-04-17 00:09:08 +00002994 hasOverriddenMethodsInBaseOrProtocol = true;
2995 overridden->setOverriding(true);
2996 break;
2997 }
2998 }
2999 }
3000 }
3001 }
3002 }
3003 }
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00003004
3005 // Propagate down the 'related result type' bit from overridden methods.
3006 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3007 ObjCMethod->SetRelatedResultType();
3008
3009 // Then merge the declarations.
3010 mergeObjCMethodDecls(ObjCMethod, overridden);
3011
3012 if (ObjCMethod->isImplicit() && overridden->isImplicit())
3013 continue; // Conflicting properties are detected elsewhere.
3014
3015 // Check for overriding methods
3016 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3017 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3018 CheckConflictingOverridingMethod(ObjCMethod, overridden,
3019 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3020
3021 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanianc4133a42012-07-05 22:26:07 +00003022 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3023 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00003024 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3025 E = ObjCMethod->param_end();
Douglas Gregor0a4a23a2012-05-17 23:13:29 +00003026 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3027 PrevE = overridden->param_end();
3028 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00003029 assert(PrevI != overridden->param_end() && "Param mismatch");
3030 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3031 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3032 // If type of argument of method in this class does not match its
3033 // respective argument type in the super class method, issue warning;
3034 if (!Context.typesAreCompatible(T1, T2)) {
3035 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3036 << T1 << T2;
3037 Diag(overridden->getLocation(), diag::note_previous_declaration);
3038 break;
3039 }
3040 }
3041 }
3042 }
3043
3044 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3045}
3046
John McCalld226f652010-08-21 09:40:31 +00003047Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanian7f532532011-02-09 22:20:01 +00003048 Scope *S,
Chris Lattner4d391482007-12-12 07:09:47 +00003049 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00003050 tok::TokenKind MethodType,
John McCallb3d87482010-08-24 05:47:05 +00003051 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003052 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattner4d391482007-12-12 07:09:47 +00003053 Selector Sel,
3054 // optional arguments. The number of types/arguments is obtained
3055 // from the Sel.getNumArgs().
Chris Lattnere294d3f2009-04-11 18:57:04 +00003056 ObjCArgInfo *ArgInfo,
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00003057 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattner4d391482007-12-12 07:09:47 +00003058 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanian90ba78c2011-03-12 18:54:30 +00003059 bool isVariadic, bool MethodDefinition) {
Steve Naroffda323ad2008-02-29 21:48:07 +00003060 // Make sure we can establish a context for the method.
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00003061 if (!CurContext->isObjCContainer()) {
Steve Naroffda323ad2008-02-29 21:48:07 +00003062 Diag(MethodLoc, diag::error_missing_method_context);
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003063 return nullptr;
Steve Naroffda323ad2008-02-29 21:48:07 +00003064 }
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00003065 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3066 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattner4d391482007-12-12 07:09:47 +00003067 QualType resultDeclType;
Mike Stump1eb44332009-09-09 15:08:12 +00003068
Douglas Gregore97179c2011-09-08 01:46:34 +00003069 bool HasRelatedResultType = false;
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003070 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroffccef3712009-02-20 22:59:16 +00003071 if (ReturnType) {
Stephen Hines651f13c2014-04-23 16:59:28 -07003072 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump1eb44332009-09-09 15:08:12 +00003073
Eli Friedmanddb5a392013-06-14 21:14:10 +00003074 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003075 return nullptr;
Eli Friedmanddb5a392013-06-14 21:14:10 +00003076
Douglas Gregore97179c2011-09-08 01:46:34 +00003077 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
Fariborz Jahanianaab24a62011-07-21 17:00:47 +00003078 } else { // get the type for "id".
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003079 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianfeb4fa12011-07-21 17:38:14 +00003080 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00003081 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianaab24a62011-07-21 17:00:47 +00003082 }
Mike Stump1eb44332009-09-09 15:08:12 +00003083
Stephen Hines651f13c2014-04-23 16:59:28 -07003084 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3085 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3086 MethodType == tok::minus, isVariadic,
3087 /*isPropertyAccessor=*/false,
3088 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3089 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3090 : ObjCMethodDecl::Required,
3091 HasRelatedResultType);
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Chris Lattner5f9e2722011-07-23 10:55:15 +00003093 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump1eb44332009-09-09 15:08:12 +00003094
Chris Lattner7db638d2009-04-11 19:42:43 +00003095 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall58e46772009-10-23 21:48:59 +00003096 QualType ArgType;
John McCalla93c9342009-12-07 02:54:59 +00003097 TypeSourceInfo *DI;
Mike Stump1eb44332009-09-09 15:08:12 +00003098
David Blaikie7247c882013-05-15 07:37:26 +00003099 if (!ArgInfo[i].Type) {
John McCall58e46772009-10-23 21:48:59 +00003100 ArgType = Context.getObjCIdType();
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003101 DI = nullptr;
Chris Lattnere294d3f2009-04-11 18:57:04 +00003102 } else {
John McCall58e46772009-10-23 21:48:59 +00003103 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnere294d3f2009-04-11 18:57:04 +00003104 }
Mike Stump1eb44332009-09-09 15:08:12 +00003105
Fariborz Jahanian7f532532011-02-09 22:20:01 +00003106 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3107 LookupOrdinaryName, ForRedeclaration);
3108 LookupName(R, S);
3109 if (R.isSingleResult()) {
3110 NamedDecl *PrevDecl = R.getFoundDecl();
3111 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanian90ba78c2011-03-12 18:54:30 +00003112 Diag(ArgInfo[i].NameLoc,
3113 (MethodDefinition ? diag::warn_method_param_redefinition
3114 : diag::warn_method_param_declaration))
Fariborz Jahanian7f532532011-02-09 22:20:01 +00003115 << ArgInfo[i].Name;
3116 Diag(PrevDecl->getLocation(),
3117 diag::note_previous_declaration);
3118 }
3119 }
3120
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003121 SourceLocation StartLoc = DI
3122 ? DI->getTypeLoc().getBeginLoc()
3123 : ArgInfo[i].NameLoc;
3124
John McCall81ef3e62011-04-23 02:46:06 +00003125 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3126 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003127 ArgType, DI, SC_None);
Mike Stump1eb44332009-09-09 15:08:12 +00003128
John McCall70798862011-05-02 00:30:12 +00003129 Param->setObjCMethodScopeInfo(i);
3130
Chris Lattner0ed844b2008-04-04 06:12:32 +00003131 Param->setObjCDeclQualifier(
Chris Lattnere294d3f2009-04-11 18:57:04 +00003132 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump1eb44332009-09-09 15:08:12 +00003133
Chris Lattnerf97e8fa2009-04-11 19:34:56 +00003134 // Apply the attributes to the parameter.
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003135 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Mike Stump1eb44332009-09-09 15:08:12 +00003136
Fariborz Jahanian47b1d962012-01-14 18:44:35 +00003137 if (Param->hasAttr<BlocksAttr>()) {
3138 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3139 Param->setInvalidDecl();
3140 }
Fariborz Jahanian7f532532011-02-09 22:20:01 +00003141 S->AddDecl(Param);
3142 IdResolver.AddDecl(Param);
3143
Chris Lattner0ed844b2008-04-04 06:12:32 +00003144 Params.push_back(Param);
3145 }
Fariborz Jahanian7f532532011-02-09 22:20:01 +00003146
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00003147 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCalld226f652010-08-21 09:40:31 +00003148 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00003149 QualType ArgType = Param->getType();
3150 if (ArgType.isNull())
3151 ArgType = Context.getObjCIdType();
3152 else
3153 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor79e6bd32011-07-12 04:42:08 +00003154 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedmanddb5a392013-06-14 21:14:10 +00003155
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00003156 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian4f4fd922010-04-08 00:30:06 +00003157 Params.push_back(Param);
3158 }
3159
Argyrios Kyrtzidis491306a2011-10-03 06:37:04 +00003160 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003161 ObjCMethod->setObjCDeclQualifier(
3162 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbar35682492008-09-26 04:12:28 +00003163
3164 if (AttrList)
Douglas Gregor9cdda0c2009-06-17 21:51:59 +00003165 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Mike Stump1eb44332009-09-09 15:08:12 +00003166
Douglas Gregorbdb2d502010-12-21 17:34:17 +00003167 // Add the method now.
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003168 const ObjCMethodDecl *PrevMethod = nullptr;
John McCall6c2c2502011-07-22 02:45:48 +00003169 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattner4d391482007-12-12 07:09:47 +00003170 if (MethodType == tok::minus) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003171 PrevMethod = ImpDecl->getInstanceMethod(Sel);
3172 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattner4d391482007-12-12 07:09:47 +00003173 } else {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003174 PrevMethod = ImpDecl->getClassMethod(Sel);
3175 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattner4d391482007-12-12 07:09:47 +00003176 }
Douglas Gregor926df6c2011-06-11 01:09:30 +00003177
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003178 ObjCMethodDecl *IMD = nullptr;
Fariborz Jahanian7fda4002011-10-22 01:21:15 +00003179 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3180 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3181 ObjCMethod->isInstanceMethod());
Fariborz Jahanian38b3bd82013-07-09 22:02:20 +00003182 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3183 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3184 // merge the attribute into implementation.
Stephen Hines651f13c2014-04-23 16:59:28 -07003185 ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3186 ObjCMethod->getLocation()));
Fariborz Jahanian38b3bd82013-07-09 22:02:20 +00003187 }
Stephen Hines651f13c2014-04-23 16:59:28 -07003188 if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
3189 ObjCMethodFamily family =
3190 ObjCMethod->getSelector().getMethodFamily();
3191 if (family == OMF_dealloc && IMD && IMD->isOverriding())
3192 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
Ted Kremenek3306ec12012-02-27 22:55:11 +00003193 << ObjCMethod->getDeclName();
Fariborz Jahanianec236782011-12-06 00:02:41 +00003194 }
Douglas Gregorbdb2d502010-12-21 17:34:17 +00003195 } else {
3196 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattner4d391482007-12-12 07:09:47 +00003197 }
John McCall6c2c2502011-07-22 02:45:48 +00003198
Chris Lattner4d391482007-12-12 07:09:47 +00003199 if (PrevMethod) {
3200 // You can never have two method definitions with the same name.
Chris Lattner5f4a6822008-11-23 23:12:31 +00003201 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattner077bf5e2008-11-24 03:33:13 +00003202 << ObjCMethod->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003203 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanianfbff0c42013-05-13 17:27:00 +00003204 ObjCMethod->setInvalidDecl();
3205 return ObjCMethod;
Mike Stump1eb44332009-09-09 15:08:12 +00003206 }
John McCall54abf7d2009-11-04 02:18:39 +00003207
Douglas Gregor926df6c2011-06-11 01:09:30 +00003208 // If this Objective-C method does not have a related result type, but we
3209 // are allowed to infer related result types, try to do so based on the
3210 // method family.
3211 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3212 if (!CurrentClass) {
3213 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3214 CurrentClass = Cat->getClassInterface();
3215 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3216 CurrentClass = Impl->getClassInterface();
3217 else if (ObjCCategoryImplDecl *CatImpl
3218 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3219 CurrentClass = CatImpl->getClassInterface();
3220 }
John McCall6c2c2502011-07-22 02:45:48 +00003221
Douglas Gregore97179c2011-09-08 01:46:34 +00003222 ResultTypeCompatibilityKind RTC
3223 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCall6c2c2502011-07-22 02:45:48 +00003224
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00003225 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCall6c2c2502011-07-22 02:45:48 +00003226
John McCallf85e1932011-06-15 23:02:42 +00003227 bool ARCError = false;
David Blaikie4e4d0842012-03-11 07:00:24 +00003228 if (getLangOpts().ObjCAutoRefCount)
John McCallb8463812013-04-04 01:38:37 +00003229 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCallf85e1932011-06-15 23:02:42 +00003230
Douglas Gregore97179c2011-09-08 01:46:34 +00003231 // Infer the related result type when possible.
Argyrios Kyrtzidise15db6f2012-05-09 16:12:57 +00003232 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregore97179c2011-09-08 01:46:34 +00003233 !ObjCMethod->hasRelatedResultType() &&
3234 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor926df6c2011-06-11 01:09:30 +00003235 bool InferRelatedResultType = false;
3236 switch (ObjCMethod->getMethodFamily()) {
3237 case OMF_None:
3238 case OMF_copy:
3239 case OMF_dealloc:
Nico Weber80cb6e62011-08-28 22:35:17 +00003240 case OMF_finalize:
Douglas Gregor926df6c2011-06-11 01:09:30 +00003241 case OMF_mutableCopy:
3242 case OMF_release:
3243 case OMF_retainCount:
Fariborz Jahanian9670e172011-07-05 22:38:59 +00003244 case OMF_performSelector:
Douglas Gregor926df6c2011-06-11 01:09:30 +00003245 break;
3246
3247 case OMF_alloc:
3248 case OMF_new:
3249 InferRelatedResultType = ObjCMethod->isClassMethod();
3250 break;
3251
3252 case OMF_init:
3253 case OMF_autorelease:
3254 case OMF_retain:
3255 case OMF_self:
3256 InferRelatedResultType = ObjCMethod->isInstanceMethod();
3257 break;
3258 }
3259
John McCall6c2c2502011-07-22 02:45:48 +00003260 if (InferRelatedResultType)
Douglas Gregor926df6c2011-06-11 01:09:30 +00003261 ObjCMethod->SetRelatedResultType();
Douglas Gregor926df6c2011-06-11 01:09:30 +00003262 }
Dmitri Gribenkoa5ef44f2012-07-11 21:38:39 +00003263
3264 ActOnDocumentableDecl(ObjCMethod);
3265
John McCalld226f652010-08-21 09:40:31 +00003266 return ObjCMethod;
Chris Lattner4d391482007-12-12 07:09:47 +00003267}
3268
Chris Lattnercc98eac2008-12-17 07:13:27 +00003269bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanian58a76492011-08-22 18:34:22 +00003270 // Following is also an error. But it is caused by a missing @end
3271 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidisfce79eb2012-03-23 23:24:23 +00003272 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00003273 return false;
Argyrios Kyrtzidisfce79eb2012-03-23 23:24:23 +00003274
3275 // If we switched context to translation unit while we are still lexically in
3276 // an objc container, it means the parser missed emitting an error.
3277 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3278 return false;
Fariborz Jahaniana28948f2011-08-22 15:54:49 +00003279
Anders Carlsson15281452008-11-04 16:57:32 +00003280 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3281 D->setInvalidDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003282
Anders Carlsson15281452008-11-04 16:57:32 +00003283 return true;
3284}
Chris Lattnercc98eac2008-12-17 07:13:27 +00003285
James Dennett1dfbd922012-06-14 21:40:34 +00003286/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattnercc98eac2008-12-17 07:13:27 +00003287/// instance variables of ClassName into Decls.
John McCalld226f652010-08-21 09:40:31 +00003288void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattnercc98eac2008-12-17 07:13:27 +00003289 IdentifierInfo *ClassName,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003290 SmallVectorImpl<Decl*> &Decls) {
Chris Lattnercc98eac2008-12-17 07:13:27 +00003291 // Check that ClassName is a valid class
Douglas Gregorc83c6872010-04-15 22:33:43 +00003292 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003293 if (!Class) {
3294 Diag(DeclStart, diag::err_undef_interface) << ClassName;
3295 return;
3296 }
John McCall260611a2012-06-20 06:18:46 +00003297 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian0468fb92009-04-21 20:28:41 +00003298 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3299 return;
3300 }
Mike Stump1eb44332009-09-09 15:08:12 +00003301
Chris Lattnercc98eac2008-12-17 07:13:27 +00003302 // Collect the instance variables
Jordy Rosedb8264e2011-07-22 02:08:32 +00003303 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003304 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian41833352009-06-04 17:08:55 +00003305 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003306 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00003307 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCalld226f652010-08-21 09:40:31 +00003308 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003309 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3310 /*FIXME: StartL=*/ID->getLocation(),
3311 ID->getLocation(),
Fariborz Jahanian41833352009-06-04 17:08:55 +00003312 ID->getIdentifier(), ID->getType(),
3313 ID->getBitWidth());
John McCalld226f652010-08-21 09:40:31 +00003314 Decls.push_back(FD);
Fariborz Jahanian41833352009-06-04 17:08:55 +00003315 }
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Chris Lattnercc98eac2008-12-17 07:13:27 +00003317 // Introduce all of these fields into the appropriate scope.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003318 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattnercc98eac2008-12-17 07:13:27 +00003319 D != Decls.end(); ++D) {
John McCalld226f652010-08-21 09:40:31 +00003320 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikie4e4d0842012-03-11 07:00:24 +00003321 if (getLangOpts().CPlusPlus)
Chris Lattnercc98eac2008-12-17 07:13:27 +00003322 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCalld226f652010-08-21 09:40:31 +00003323 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003324 Record->addDecl(FD);
Chris Lattnercc98eac2008-12-17 07:13:27 +00003325 }
3326}
3327
Douglas Gregor160b5632010-04-26 17:32:49 +00003328/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003329VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3330 SourceLocation StartLoc,
3331 SourceLocation IdLoc,
3332 IdentifierInfo *Id,
Douglas Gregor160b5632010-04-26 17:32:49 +00003333 bool Invalid) {
3334 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3335 // duration shall not be qualified by an address-space qualifier."
3336 // Since all parameters have automatic store duration, they can not have
3337 // an address space.
3338 if (T.getAddressSpace() != 0) {
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003339 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregor160b5632010-04-26 17:32:49 +00003340 Invalid = true;
3341 }
3342
3343 // An @catch parameter must be an unqualified object pointer type;
3344 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3345 if (Invalid) {
3346 // Don't do any further checking.
Douglas Gregorbe270a02010-04-26 17:57:08 +00003347 } else if (T->isDependentType()) {
3348 // Okay: we don't know what this type will instantiate to.
Douglas Gregor160b5632010-04-26 17:32:49 +00003349 } else if (!T->isObjCObjectPointerType()) {
3350 Invalid = true;
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003351 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregor160b5632010-04-26 17:32:49 +00003352 } else if (T->isObjCQualifiedIdType()) {
3353 Invalid = true;
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003354 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregor160b5632010-04-26 17:32:49 +00003355 }
3356
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003357 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003358 T, TInfo, SC_None);
Douglas Gregor324b54d2010-05-03 18:51:14 +00003359 New->setExceptionVariable(true);
3360
Douglas Gregor9aab9c42011-12-10 01:22:52 +00003361 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikie4e4d0842012-03-11 07:00:24 +00003362 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor9aab9c42011-12-10 01:22:52 +00003363 Invalid = true;
3364
Douglas Gregor160b5632010-04-26 17:32:49 +00003365 if (Invalid)
3366 New->setInvalidDecl();
3367 return New;
3368}
3369
John McCalld226f652010-08-21 09:40:31 +00003370Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregor160b5632010-04-26 17:32:49 +00003371 const DeclSpec &DS = D.getDeclSpec();
3372
3373 // We allow the "register" storage class on exception variables because
3374 // GCC did, but we drop it completely. Any other storage class is an error.
3375 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3376 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3377 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithec642442013-04-12 22:46:28 +00003378 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregor160b5632010-04-26 17:32:49 +00003379 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithec642442013-04-12 22:46:28 +00003380 << DeclSpec::getSpecifierName(SCS);
3381 }
3382 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3383 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3384 diag::err_invalid_thread)
3385 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregor160b5632010-04-26 17:32:49 +00003386 D.getMutableDeclSpec().ClearStorageClassSpecs();
3387
Richard Smithc7f81162013-03-18 22:52:47 +00003388 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregor160b5632010-04-26 17:32:49 +00003389
3390 // Check that there are no default arguments inside the type of this
3391 // exception object (C++ only).
David Blaikie4e4d0842012-03-11 07:00:24 +00003392 if (getLangOpts().CPlusPlus)
Douglas Gregor160b5632010-04-26 17:32:49 +00003393 CheckExtraCXXDefaultArguments(D);
3394
Argyrios Kyrtzidis32153982011-06-28 03:01:15 +00003395 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCallbf1a0282010-06-04 23:28:52 +00003396 QualType ExceptionType = TInfo->getType();
Douglas Gregor160b5632010-04-26 17:32:49 +00003397
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003398 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3399 D.getSourceRange().getBegin(),
3400 D.getIdentifierLoc(),
3401 D.getIdentifier(),
Douglas Gregor160b5632010-04-26 17:32:49 +00003402 D.isInvalidType());
3403
3404 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3405 if (D.getCXXScopeSpec().isSet()) {
3406 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3407 << D.getCXXScopeSpec().getRange();
3408 New->setInvalidDecl();
3409 }
3410
3411 // Add the parameter declaration into this scope.
John McCalld226f652010-08-21 09:40:31 +00003412 S->AddDecl(New);
Douglas Gregor160b5632010-04-26 17:32:49 +00003413 if (D.getIdentifier())
3414 IdResolver.AddDecl(New);
3415
3416 ProcessDeclAttributes(S, New, D);
3417
3418 if (New->hasAttr<BlocksAttr>())
3419 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCalld226f652010-08-21 09:40:31 +00003420 return New;
Douglas Gregor4e6c0d12010-04-23 23:01:43 +00003421}
Fariborz Jahanian786cd152010-04-27 17:18:58 +00003422
3423/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00003424/// initialization.
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003425void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003426 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003427 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3428 Iv= Iv->getNextIvar()) {
Fariborz Jahanian786cd152010-04-27 17:18:58 +00003429 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor68dd3ee2010-05-20 02:24:22 +00003430 if (QT->isRecordType())
Fariborz Jahanian2c18bb72010-08-20 21:21:08 +00003431 Ivars.push_back(Iv);
Fariborz Jahanian786cd152010-04-27 17:18:58 +00003432 }
3433}
Fariborz Jahaniane4498c62010-04-28 16:11:27 +00003434
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00003435void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor5b9dc7c2011-07-28 14:54:22 +00003436 // Load referenced selectors from the external source.
3437 if (ExternalSource) {
3438 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3439 ExternalSource->ReadReferencedSelectors(Sels);
3440 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3441 ReferencedSelectors[Sels[I].first] = Sels[I].second;
3442 }
3443
Fariborz Jahanian8b789132011-02-04 23:19:27 +00003444 // Warning will be issued only when selector table is
3445 // generated (which means there is at lease one implementation
3446 // in the TU). This is to match gcc's behavior.
3447 if (ReferencedSelectors.empty() ||
3448 !Context.AnyObjCImplementation())
Fariborz Jahanian3fe10412010-07-22 18:24:20 +00003449 return;
3450 for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3451 ReferencedSelectors.begin(),
3452 E = ReferencedSelectors.end(); S != E; ++S) {
3453 Selector Sel = (*S).first;
3454 if (!LookupImplementedMethodInGlobalPool(Sel))
3455 Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
3456 }
3457 return;
3458}
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00003459
3460ObjCIvarDecl *
3461Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3462 const ObjCPropertyDecl *&PDecl) const {
Stephen Hines651f13c2014-04-23 16:59:28 -07003463 if (Method->isClassMethod())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003464 return nullptr;
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00003465 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3466 if (!IDecl)
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003467 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003468 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3469 /*shallowCategoryLookup=*/false,
3470 /*followSuper=*/false);
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00003471 if (!Method || !Method->isPropertyAccessor())
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003472 return nullptr;
Stephen Hines651f13c2014-04-23 16:59:28 -07003473 if ((PDecl = Method->findPropertyDecl()))
3474 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3475 // property backing ivar must belong to property's class
3476 // or be a private ivar in class's implementation.
3477 // FIXME. fix the const-ness issue.
3478 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3479 IV->getIdentifier());
3480 return IV;
3481 }
Stephen Hines6bcf27b2014-05-29 04:14:42 -07003482 return nullptr;
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00003483}
3484
Stephen Hines651f13c2014-04-23 16:59:28 -07003485namespace {
3486 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3487 /// accessor references the backing ivar.
3488 class UnusedBackingIvarChecker :
3489 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
3490 public:
3491 Sema &S;
3492 const ObjCMethodDecl *Method;
3493 const ObjCIvarDecl *IvarD;
3494 bool AccessedIvar;
3495 bool InvokedSelfMethod;
3496
3497 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3498 const ObjCIvarDecl *IvarD)
3499 : S(S), Method(Method), IvarD(IvarD),
3500 AccessedIvar(false), InvokedSelfMethod(false) {
3501 assert(IvarD);
3502 }
3503
3504 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3505 if (E->getDecl() == IvarD) {
3506 AccessedIvar = true;
3507 return false;
3508 }
3509 return true;
3510 }
3511
3512 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3513 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3514 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3515 InvokedSelfMethod = true;
3516 }
3517 return true;
3518 }
3519 };
3520}
3521
3522void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3523 const ObjCImplementationDecl *ImplD) {
3524 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00003525 return;
Stephen Hines651f13c2014-04-23 16:59:28 -07003526
3527 for (const auto *CurMethod : ImplD->instance_methods()) {
3528 unsigned DIAG = diag::warn_unused_property_backing_ivar;
3529 SourceLocation Loc = CurMethod->getLocation();
3530 if (Diags.getDiagnosticLevel(DIAG, Loc) == DiagnosticsEngine::Ignored)
3531 continue;
3532
3533 const ObjCPropertyDecl *PDecl;
3534 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3535 if (!IV)
3536 continue;
3537
3538 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3539 Checker.TraverseStmt(CurMethod->getBody());
3540 if (Checker.AccessedIvar)
3541 continue;
3542
3543 // Do not issue this warning if backing ivar is used somewhere and accessor
3544 // implementation makes a self call. This is to prevent false positive in
3545 // cases where the ivar is accessed by another method that the accessor
3546 // delegates to.
3547 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
3548 Diag(Loc, DIAG) << IV;
3549 Diag(PDecl->getLocation(), diag::note_property_declare);
3550 }
Fariborz Jahanian4e7f00c2013-10-25 21:44:50 +00003551 }
3552}