clang 19.0.0git
SemaDeclObjC.cpp
Go to the documentation of this file.
1//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for Objective C declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/Expr.h"
19#include "clang/AST/ExprObjC.h"
23#include "clang/Sema/DeclSpec.h"
26#include "clang/Sema/Lookup.h"
27#include "clang/Sema/Scope.h"
30#include "clang/Sema/SemaObjC.h"
31#include "llvm/ADT/DenseMap.h"
32#include "llvm/ADT/DenseSet.h"
33
34using namespace clang;
35
36/// Check whether the given method, which must be in the 'init'
37/// family, is a valid member of that family.
38///
39/// \param receiverTypeIfCall - if null, check this as if declaring it;
40/// if non-null, check this as if making a call to it with the given
41/// receiver type
42///
43/// \return true to indicate that there was an error and appropriate
44/// actions were taken
46 QualType receiverTypeIfCall) {
47 ASTContext &Context = getASTContext();
48 if (method->isInvalidDecl()) return true;
49
50 // This castAs is safe: methods that don't return an object
51 // pointer won't be inferred as inits and will reject an explicit
52 // objc_method_family(init).
53
54 // We ignore protocols here. Should we? What about Class?
55
56 const ObjCObjectType *result =
58
59 if (result->isObjCId()) {
60 return false;
61 } else if (result->isObjCClass()) {
62 // fall through: always an error
63 } else {
64 ObjCInterfaceDecl *resultClass = result->getInterface();
65 assert(resultClass && "unexpected object type!");
66
67 // It's okay for the result type to still be a forward declaration
68 // if we're checking an interface declaration.
69 if (!resultClass->hasDefinition()) {
70 if (receiverTypeIfCall.isNull() &&
71 !isa<ObjCImplementationDecl>(method->getDeclContext()))
72 return false;
73
74 // Otherwise, we try to compare class types.
75 } else {
76 // If this method was declared in a protocol, we can't check
77 // anything unless we have a receiver type that's an interface.
78 const ObjCInterfaceDecl *receiverClass = nullptr;
79 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
80 if (receiverTypeIfCall.isNull())
81 return false;
82
83 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
84 ->getInterfaceDecl();
85
86 // This can be null for calls to e.g. id<Foo>.
87 if (!receiverClass) return false;
88 } else {
89 receiverClass = method->getClassInterface();
90 assert(receiverClass && "method not associated with a class!");
91 }
92
93 // If either class is a subclass of the other, it's fine.
94 if (receiverClass->isSuperClassOf(resultClass) ||
95 resultClass->isSuperClassOf(receiverClass))
96 return false;
97 }
98 }
99
100 SourceLocation loc = method->getLocation();
101
102 // If we're in a system header, and this is not a call, just make
103 // the method unusable.
104 if (receiverTypeIfCall.isNull() &&
106 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
107 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
108 return true;
109 }
110
111 // Otherwise, it's an error.
112 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
113 method->setInvalidDecl();
114 return true;
115}
116
117/// Issue a warning if the parameter of the overridden method is non-escaping
118/// but the parameter of the overriding method is not.
119static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
120 Sema &S) {
121 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
122 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
123 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
124 return false;
125 }
126
127 return true;
128}
129
130/// Produce additional diagnostics if a category conforms to a protocol that
131/// defines a method taking a non-escaping parameter.
132static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
133 const ObjCCategoryDecl *CD,
134 const ObjCProtocolDecl *PD, Sema &S) {
135 if (!diagnoseNoescape(NewD, OldD, S))
136 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
137 << CD->IsClassExtension() << PD
138 << cast<ObjCMethodDecl>(NewD->getDeclContext());
139}
140
142 const ObjCMethodDecl *Overridden) {
143 ASTContext &Context = getASTContext();
144 if (Overridden->hasRelatedResultType() &&
145 !NewMethod->hasRelatedResultType()) {
146 // This can only happen when the method follows a naming convention that
147 // implies a related result type, and the original (overridden) method has
148 // a suitable return type, but the new (overriding) method does not have
149 // a suitable return type.
150 QualType ResultType = NewMethod->getReturnType();
151 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
152
153 // Figure out which class this method is part of, if any.
154 ObjCInterfaceDecl *CurrentClass
155 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
156 if (!CurrentClass) {
157 DeclContext *DC = NewMethod->getDeclContext();
158 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
159 CurrentClass = Cat->getClassInterface();
160 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
161 CurrentClass = Impl->getClassInterface();
162 else if (ObjCCategoryImplDecl *CatImpl
163 = dyn_cast<ObjCCategoryImplDecl>(DC))
164 CurrentClass = CatImpl->getClassInterface();
165 }
166
167 if (CurrentClass) {
168 Diag(NewMethod->getLocation(),
169 diag::warn_related_result_type_compatibility_class)
170 << Context.getObjCInterfaceType(CurrentClass)
171 << ResultType
172 << ResultTypeRange;
173 } else {
174 Diag(NewMethod->getLocation(),
175 diag::warn_related_result_type_compatibility_protocol)
176 << ResultType
177 << ResultTypeRange;
178 }
179
180 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
181 Diag(Overridden->getLocation(),
182 diag::note_related_result_type_family)
183 << /*overridden method*/ 0
184 << Family;
185 else
186 Diag(Overridden->getLocation(),
187 diag::note_related_result_type_overridden);
188 }
189
190 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
191 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
192 Diag(NewMethod->getLocation(),
193 getLangOpts().ObjCAutoRefCount
194 ? diag::err_nsreturns_retained_attribute_mismatch
195 : diag::warn_nsreturns_retained_attribute_mismatch)
196 << 1;
197 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
198 }
199 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
200 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
201 Diag(NewMethod->getLocation(),
202 getLangOpts().ObjCAutoRefCount
203 ? diag::err_nsreturns_retained_attribute_mismatch
204 : diag::warn_nsreturns_retained_attribute_mismatch)
205 << 0;
206 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
207 }
208
210 oe = Overridden->param_end();
211 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
212 ne = NewMethod->param_end();
213 ni != ne && oi != oe; ++ni, ++oi) {
214 const ParmVarDecl *oldDecl = (*oi);
215 ParmVarDecl *newDecl = (*ni);
216 if (newDecl->hasAttr<NSConsumedAttr>() !=
217 oldDecl->hasAttr<NSConsumedAttr>()) {
218 Diag(newDecl->getLocation(),
219 getLangOpts().ObjCAutoRefCount
220 ? diag::err_nsconsumed_attribute_mismatch
221 : diag::warn_nsconsumed_attribute_mismatch);
222 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
223 }
224
225 diagnoseNoescape(newDecl, oldDecl, SemaRef);
226 }
227}
228
229/// Check a method declaration for compatibility with the Objective-C
230/// ARC conventions.
232 ASTContext &Context = getASTContext();
233 ObjCMethodFamily family = method->getMethodFamily();
234 switch (family) {
235 case OMF_None:
236 case OMF_finalize:
237 case OMF_retain:
238 case OMF_release:
239 case OMF_autorelease:
240 case OMF_retainCount:
241 case OMF_self:
242 case OMF_initialize:
244 return false;
245
246 case OMF_dealloc:
247 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
248 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
249 if (ResultTypeRange.isInvalid())
250 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
251 << method->getReturnType()
252 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
253 else
254 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
255 << method->getReturnType()
256 << FixItHint::CreateReplacement(ResultTypeRange, "void");
257 return true;
258 }
259 return false;
260
261 case OMF_init:
262 // If the method doesn't obey the init rules, don't bother annotating it.
263 if (checkInitMethod(method, QualType()))
264 return true;
265
266 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
267
268 // Don't add a second copy of this attribute, but otherwise don't
269 // let it be suppressed.
270 if (method->hasAttr<NSReturnsRetainedAttr>())
271 return false;
272 break;
273
274 case OMF_alloc:
275 case OMF_copy:
276 case OMF_mutableCopy:
277 case OMF_new:
278 if (method->hasAttr<NSReturnsRetainedAttr>() ||
279 method->hasAttr<NSReturnsNotRetainedAttr>() ||
280 method->hasAttr<NSReturnsAutoreleasedAttr>())
281 return false;
282 break;
283 }
284
285 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
286 return false;
287}
288
290 SourceLocation ImplLoc) {
291 if (!ND)
292 return;
293 bool IsCategory = false;
294 StringRef RealizedPlatform;
295 AvailabilityResult Availability = ND->getAvailability(
296 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
297 &RealizedPlatform);
298 if (Availability != AR_Deprecated) {
299 if (isa<ObjCMethodDecl>(ND)) {
300 if (Availability != AR_Unavailable)
301 return;
302 if (RealizedPlatform.empty())
303 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
304 // Warn about implementing unavailable methods, unless the unavailable
305 // is for an app extension.
306 if (RealizedPlatform.ends_with("_app_extension"))
307 return;
308 S.Diag(ImplLoc, diag::warn_unavailable_def);
309 S.Diag(ND->getLocation(), diag::note_method_declared_at)
310 << ND->getDeclName();
311 return;
312 }
313 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
314 if (!CD->getClassInterface()->isDeprecated())
315 return;
316 ND = CD->getClassInterface();
317 IsCategory = true;
318 } else
319 return;
320 }
321 S.Diag(ImplLoc, diag::warn_deprecated_def)
322 << (isa<ObjCMethodDecl>(ND)
323 ? /*Method*/ 0
324 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
325 : /*Class*/ 1);
326 if (isa<ObjCMethodDecl>(ND))
327 S.Diag(ND->getLocation(), diag::note_method_declared_at)
328 << ND->getDeclName();
329 else
330 S.Diag(ND->getLocation(), diag::note_previous_decl)
331 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
332}
333
334/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
335/// pool.
337 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
338
339 // If we don't have a valid method decl, simply return.
340 if (!MDecl)
341 return;
342 if (MDecl->isInstanceMethod())
344 else
345 AddFactoryMethodToGlobalPool(MDecl, true);
346}
347
348/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
349/// has explicit ownership attribute; false otherwise.
350static bool
352 QualType T = Param->getType();
353
354 if (const PointerType *PT = T->getAs<PointerType>()) {
355 T = PT->getPointeeType();
356 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
357 T = RT->getPointeeType();
358 } else {
359 return true;
360 }
361
362 // If we have a lifetime qualifier, but it's local, we must have
363 // inferred it. So, it is implicit.
364 return !T.getLocalQualifiers().hasObjCLifetime();
365}
366
367/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
368/// and user declared, in the method definition's AST.
370 ASTContext &Context = getASTContext();
372 assert((SemaRef.getCurMethodDecl() == nullptr) && "Methodparsing confused");
373 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
374
376 SemaRef.ExprEvalContexts.back().Context);
377
378 // If we don't have a valid method decl, simply return.
379 if (!MDecl)
380 return;
381
382 QualType ResultType = MDecl->getReturnType();
383 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
384 !MDecl->isInvalidDecl() &&
385 SemaRef.RequireCompleteType(MDecl->getLocation(), ResultType,
386 diag::err_func_def_incomplete_result))
387 MDecl->setInvalidDecl();
388
389 // Allow all of Sema to see that we are entering a method definition.
390 SemaRef.PushDeclContext(FnBodyScope, MDecl);
392
393 // Create Decl objects for each parameter, entrring them in the scope for
394 // binding to their use.
395
396 // Insert the invisible arguments, self and _cmd!
397 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
398
399 SemaRef.PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
400 SemaRef.PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
401
402 // The ObjC parser requires parameter names so there's no need to check.
404 /*CheckParameterNames=*/false);
405
406 // Introduce all of the other parameters into this scope.
407 for (auto *Param : MDecl->parameters()) {
408 if (!Param->isInvalidDecl() && getLangOpts().ObjCAutoRefCount &&
410 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
411 Param->getType();
412
413 if (Param->getIdentifier())
414 SemaRef.PushOnScopeChains(Param, FnBodyScope);
415 }
416
417 // In ARC, disallow definition of retain/release/autorelease/retainCount
418 if (getLangOpts().ObjCAutoRefCount) {
419 switch (MDecl->getMethodFamily()) {
420 case OMF_retain:
421 case OMF_retainCount:
422 case OMF_release:
423 case OMF_autorelease:
424 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
425 << 0 << MDecl->getSelector();
426 break;
427
428 case OMF_None:
429 case OMF_dealloc:
430 case OMF_finalize:
431 case OMF_alloc:
432 case OMF_init:
433 case OMF_mutableCopy:
434 case OMF_copy:
435 case OMF_new:
436 case OMF_self:
437 case OMF_initialize:
439 break;
440 }
441 }
442
443 // Warn on deprecated methods under -Wdeprecated-implementations,
444 // and prepare for warning on missing super calls.
445 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
446 ObjCMethodDecl *IMD =
447 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
448
449 if (IMD) {
450 ObjCImplDecl *ImplDeclOfMethodDef =
451 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
452 ObjCContainerDecl *ContDeclOfMethodDecl =
453 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
454 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
455 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
456 ImplDeclOfMethodDecl = OID->getImplementation();
457 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
458 if (CD->IsClassExtension()) {
459 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
460 ImplDeclOfMethodDecl = OID->getImplementation();
461 } else
462 ImplDeclOfMethodDecl = CD->getImplementation();
463 }
464 // No need to issue deprecated warning if deprecated mehod in class/category
465 // is being implemented in its own implementation (no overriding is involved).
466 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
468 }
469
470 if (MDecl->getMethodFamily() == OMF_init) {
474 IC->getSuperClass() != nullptr;
475 } else if (IC->hasDesignatedInitializers()) {
478 }
479 }
480
481 // If this is "dealloc" or "finalize", set some bit here.
482 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
483 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
484 // Only do this if the current class actually has a superclass.
485 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
486 ObjCMethodFamily Family = MDecl->getMethodFamily();
487 if (Family == OMF_dealloc) {
488 if (!(getLangOpts().ObjCAutoRefCount ||
489 getLangOpts().getGC() == LangOptions::GCOnly))
491
492 } else if (Family == OMF_finalize) {
493 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
495
496 } else {
497 const ObjCMethodDecl *SuperMethod =
498 SuperClass->lookupMethod(MDecl->getSelector(),
499 MDecl->isInstanceMethod());
501 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
502 }
503 }
504 }
505
506 // Some function attributes (like OptimizeNoneAttr) need actions before
507 // parsing body started.
509}
510
511namespace {
512
513// Callback to only accept typo corrections that are Objective-C classes.
514// If an ObjCInterfaceDecl* is given to the constructor, then the validation
515// function will reject corrections to that class.
516class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
517 public:
518 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
519 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
520 : CurrentIDecl(IDecl) {}
521
522 bool ValidateCandidate(const TypoCorrection &candidate) override {
524 return ID && !declaresSameEntity(ID, CurrentIDecl);
525 }
526
527 std::unique_ptr<CorrectionCandidateCallback> clone() override {
528 return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
529 }
530
531 private:
532 ObjCInterfaceDecl *CurrentIDecl;
533};
534
535} // end anonymous namespace
536
537static void diagnoseUseOfProtocols(Sema &TheSema,
539 ObjCProtocolDecl *const *ProtoRefs,
540 unsigned NumProtoRefs,
541 const SourceLocation *ProtoLocs) {
542 assert(ProtoRefs);
543 // Diagnose availability in the context of the ObjC container.
544 Sema::ContextRAII SavedContext(TheSema, CD);
545 for (unsigned i = 0; i < NumProtoRefs; ++i) {
546 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
547 /*UnknownObjCClass=*/nullptr,
548 /*ObjCPropertyAccess=*/false,
549 /*AvoidPartialAvailabilityChecks=*/true);
550 }
551}
552
554 Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl,
555 IdentifierInfo *ClassName, SourceLocation ClassLoc,
556 IdentifierInfo *SuperName, SourceLocation SuperLoc,
557 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange) {
558 ASTContext &Context = getASTContext();
559 // Check if a different kind of symbol declared in this scope.
561 SemaRef.TUScope, SuperName, SuperLoc, Sema::LookupOrdinaryName);
562
563 if (!PrevDecl) {
564 // Try to correct for a typo in the superclass name without correcting
565 // to the class we're defining.
566 ObjCInterfaceValidatorCCC CCC(IDecl);
567 if (TypoCorrection Corrected = SemaRef.CorrectTypo(
568 DeclarationNameInfo(SuperName, SuperLoc), Sema::LookupOrdinaryName,
569 SemaRef.TUScope, nullptr, CCC, Sema::CTK_ErrorRecovery)) {
570 SemaRef.diagnoseTypo(Corrected,
571 SemaRef.PDiag(diag::err_undef_superclass_suggest)
572 << SuperName << ClassName);
573 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
574 }
575 }
576
577 if (declaresSameEntity(PrevDecl, IDecl)) {
578 Diag(SuperLoc, diag::err_recursive_superclass)
579 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
580 IDecl->setEndOfDefinitionLoc(ClassLoc);
581 } else {
582 ObjCInterfaceDecl *SuperClassDecl =
583 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
584 QualType SuperClassType;
585
586 // Diagnose classes that inherit from deprecated classes.
587 if (SuperClassDecl) {
588 (void)SemaRef.DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
589 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
590 }
591
592 if (PrevDecl && !SuperClassDecl) {
593 // The previous declaration was not a class decl. Check if we have a
594 // typedef. If we do, get the underlying class type.
595 if (const TypedefNameDecl *TDecl =
596 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
597 QualType T = TDecl->getUnderlyingType();
598 if (T->isObjCObjectType()) {
599 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
600 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
601 SuperClassType = Context.getTypeDeclType(TDecl);
602
603 // This handles the following case:
604 // @interface NewI @end
605 // typedef NewI DeprI __attribute__((deprecated("blah")))
606 // @interface SI : DeprI /* warn here */ @end
608 const_cast<TypedefNameDecl *>(TDecl), SuperLoc);
609 }
610 }
611 }
612
613 // This handles the following case:
614 //
615 // typedef int SuperClass;
616 // @interface MyClass : SuperClass {} @end
617 //
618 if (!SuperClassDecl) {
619 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
620 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
621 }
622 }
623
624 if (!isa_and_nonnull<TypedefNameDecl>(PrevDecl)) {
625 if (!SuperClassDecl)
626 Diag(SuperLoc, diag::err_undef_superclass)
627 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
629 SuperLoc, SuperClassType, diag::err_forward_superclass,
630 SuperClassDecl->getDeclName(), ClassName,
631 SourceRange(AtInterfaceLoc, ClassLoc))) {
632 SuperClassDecl = nullptr;
633 SuperClassType = QualType();
634 }
635 }
636
637 if (SuperClassType.isNull()) {
638 assert(!SuperClassDecl && "Failed to set SuperClassType?");
639 return;
640 }
641
642 // Handle type arguments on the superclass.
643 TypeSourceInfo *SuperClassTInfo = nullptr;
644 if (!SuperTypeArgs.empty()) {
646 S, SuperLoc, SemaRef.CreateParsedType(SuperClassType, nullptr),
647 SuperTypeArgsRange.getBegin(), SuperTypeArgs,
648 SuperTypeArgsRange.getEnd(), SourceLocation(), {}, {},
650 if (!fullSuperClassType.isUsable())
651 return;
652
653 SuperClassType =
654 SemaRef.GetTypeFromParser(fullSuperClassType.get(), &SuperClassTInfo);
655 }
656
657 if (!SuperClassTInfo) {
658 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
659 SuperLoc);
660 }
661
662 IDecl->setSuperClass(SuperClassTInfo);
663 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
664 }
665}
666
668 Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc,
669 unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc,
670 SourceLocation colonLoc, ParsedType parsedTypeBound) {
671 ASTContext &Context = getASTContext();
672 // If there was an explicitly-provided type bound, check it.
673 TypeSourceInfo *typeBoundInfo = nullptr;
674 if (parsedTypeBound) {
675 // The type bound can be any Objective-C pointer type.
676 QualType typeBound =
677 SemaRef.GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
678 if (typeBound->isObjCObjectPointerType()) {
679 // okay
680 } else if (typeBound->isObjCObjectType()) {
681 // The user forgot the * on an Objective-C pointer type, e.g.,
682 // "T : NSView".
683 SourceLocation starLoc =
685 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
686 diag::err_objc_type_param_bound_missing_pointer)
687 << typeBound << paramName
688 << FixItHint::CreateInsertion(starLoc, " *");
689
690 // Create a new type location builder so we can update the type
691 // location information we have.
692 TypeLocBuilder builder;
693 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
694
695 // Create the Objective-C pointer type.
696 typeBound = Context.getObjCObjectPointerType(typeBound);
698 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
699 newT.setStarLoc(starLoc);
700
701 // Form the new type source information.
702 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
703 } else {
704 // Not a valid type bound.
705 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
706 diag::err_objc_type_param_bound_nonobject)
707 << typeBound << paramName;
708
709 // Forget the bound; we'll default to id later.
710 typeBoundInfo = nullptr;
711 }
712
713 // Type bounds cannot have qualifiers (even indirectly) or explicit
714 // nullability.
715 if (typeBoundInfo) {
716 QualType typeBound = typeBoundInfo->getType();
717 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
718 if (qual || typeBound.hasQualifiers()) {
719 bool diagnosed = false;
720 SourceRange rangeToRemove;
721 if (qual) {
722 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
723 rangeToRemove = attr.getLocalSourceRange();
724 if (attr.getTypePtr()->getImmediateNullability()) {
725 Diag(attr.getBeginLoc(),
726 diag::err_objc_type_param_bound_explicit_nullability)
727 << paramName << typeBound
728 << FixItHint::CreateRemoval(rangeToRemove);
729 diagnosed = true;
730 }
731 }
732 }
733
734 if (!diagnosed) {
735 Diag(qual ? qual.getBeginLoc()
736 : typeBoundInfo->getTypeLoc().getBeginLoc(),
737 diag::err_objc_type_param_bound_qualified)
738 << paramName << typeBound
739 << typeBound.getQualifiers().getAsString()
740 << FixItHint::CreateRemoval(rangeToRemove);
741 }
742
743 // If the type bound has qualifiers other than CVR, we need to strip
744 // them or we'll probably assert later when trying to apply new
745 // qualifiers.
746 Qualifiers quals = typeBound.getQualifiers();
747 quals.removeCVRQualifiers();
748 if (!quals.empty()) {
749 typeBoundInfo =
750 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
751 }
752 }
753 }
754 }
755
756 // If there was no explicit type bound (or we removed it due to an error),
757 // use 'id' instead.
758 if (!typeBoundInfo) {
759 colonLoc = SourceLocation();
760 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
761 }
762
763 // Create the type parameter.
764 return ObjCTypeParamDecl::Create(Context, SemaRef.CurContext, variance,
765 varianceLoc, index, paramLoc, paramName,
766 colonLoc, typeBoundInfo);
767}
768
771 ArrayRef<Decl *> typeParamsIn,
772 SourceLocation rAngleLoc) {
773 ASTContext &Context = getASTContext();
774 // We know that the array only contains Objective-C type parameters.
776 typeParams(
777 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
778 typeParamsIn.size());
779
780 // Diagnose redeclarations of type parameters.
781 // We do this now because Objective-C type parameters aren't pushed into
782 // scope until later (after the instance variable block), but we want the
783 // diagnostics to occur right after we parse the type parameter list.
784 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
785 for (auto *typeParam : typeParams) {
786 auto known = knownParams.find(typeParam->getIdentifier());
787 if (known != knownParams.end()) {
788 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
789 << typeParam->getIdentifier()
790 << SourceRange(known->second->getLocation());
791
792 typeParam->setInvalidDecl();
793 } else {
794 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
795
796 // Push the type parameter into scope.
797 SemaRef.PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
798 }
799 }
800
801 // Create the parameter list.
802 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
803}
804
806 ObjCTypeParamList *typeParamList) {
807 for (auto *typeParam : *typeParamList) {
808 if (!typeParam->isInvalidDecl()) {
809 S->RemoveDecl(typeParam);
810 SemaRef.IdResolver.RemoveDecl(typeParam);
811 }
812 }
813}
814
815namespace {
816 /// The context in which an Objective-C type parameter list occurs, for use
817 /// in diagnostics.
818 enum class TypeParamListContext {
819 ForwardDeclaration,
821 Category,
822 Extension
823 };
824} // end anonymous namespace
825
826/// Check consistency between two Objective-C type parameter lists, e.g.,
827/// between a category/extension and an \@interface or between an \@class and an
828/// \@interface.
830 ObjCTypeParamList *prevTypeParams,
831 ObjCTypeParamList *newTypeParams,
832 TypeParamListContext newContext) {
833 // If the sizes don't match, complain about that.
834 if (prevTypeParams->size() != newTypeParams->size()) {
835 SourceLocation diagLoc;
836 if (newTypeParams->size() > prevTypeParams->size()) {
837 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
838 } else {
839 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
840 }
841
842 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
843 << static_cast<unsigned>(newContext)
844 << (newTypeParams->size() > prevTypeParams->size())
845 << prevTypeParams->size()
846 << newTypeParams->size();
847
848 return true;
849 }
850
851 // Match up the type parameters.
852 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
853 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
854 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
855
856 // Check for consistency of the variance.
857 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
858 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
859 newContext != TypeParamListContext::Definition) {
860 // When the new type parameter is invariant and is not part
861 // of the definition, just propagate the variance.
862 newTypeParam->setVariance(prevTypeParam->getVariance());
863 } else if (prevTypeParam->getVariance()
865 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
866 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
867 ->getDefinition() == prevTypeParam->getDeclContext())) {
868 // When the old parameter is invariant and was not part of the
869 // definition, just ignore the difference because it doesn't
870 // matter.
871 } else {
872 {
873 // Diagnose the conflict and update the second declaration.
874 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
875 if (diagLoc.isInvalid())
876 diagLoc = newTypeParam->getBeginLoc();
877
878 auto diag = S.Diag(diagLoc,
879 diag::err_objc_type_param_variance_conflict)
880 << static_cast<unsigned>(newTypeParam->getVariance())
881 << newTypeParam->getDeclName()
882 << static_cast<unsigned>(prevTypeParam->getVariance())
883 << prevTypeParam->getDeclName();
884 switch (prevTypeParam->getVariance()) {
886 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
887 break;
888
891 StringRef newVarianceStr
893 ? "__covariant"
894 : "__contravariant";
895 if (newTypeParam->getVariance()
897 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
898 (newVarianceStr + " ").str());
899 } else {
900 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
901 newVarianceStr);
902 }
903 }
904 }
905 }
906
907 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
908 << prevTypeParam->getDeclName();
909
910 // Override the variance.
911 newTypeParam->setVariance(prevTypeParam->getVariance());
912 }
913 }
914
915 // If the bound types match, there's nothing to do.
916 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
917 newTypeParam->getUnderlyingType()))
918 continue;
919
920 // If the new type parameter's bound was explicit, complain about it being
921 // different from the original.
922 if (newTypeParam->hasExplicitBound()) {
923 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
925 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
926 << newTypeParam->getUnderlyingType()
927 << newTypeParam->getDeclName()
928 << prevTypeParam->hasExplicitBound()
929 << prevTypeParam->getUnderlyingType()
930 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
931 << prevTypeParam->getDeclName()
933 newBoundRange,
934 prevTypeParam->getUnderlyingType().getAsString(
936
937 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
938 << prevTypeParam->getDeclName();
939
940 // Override the new type parameter's bound type with the previous type,
941 // so that it's consistent.
942 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
943 continue;
944 }
945
946 // The new type parameter got the implicit bound of 'id'. That's okay for
947 // categories and extensions (overwrite it later), but not for forward
948 // declarations and @interfaces, because those must be standalone.
949 if (newContext == TypeParamListContext::ForwardDeclaration ||
950 newContext == TypeParamListContext::Definition) {
951 // Diagnose this problem for forward declarations and definitions.
952 SourceLocation insertionLoc
953 = S.getLocForEndOfToken(newTypeParam->getLocation());
954 std::string newCode
955 = " : " + prevTypeParam->getUnderlyingType().getAsString(
957 S.Diag(newTypeParam->getLocation(),
958 diag::err_objc_type_param_bound_missing)
959 << prevTypeParam->getUnderlyingType()
960 << newTypeParam->getDeclName()
961 << (newContext == TypeParamListContext::ForwardDeclaration)
962 << FixItHint::CreateInsertion(insertionLoc, newCode);
963
964 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
965 << prevTypeParam->getDeclName();
966 }
967
968 // Update the new type parameter's bound to match the previous one.
969 S.Context.adjustObjCTypeParamBoundType(prevTypeParam, newTypeParam);
970 }
971
972 return false;
973}
974
976 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
977 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
978 IdentifierInfo *SuperName, SourceLocation SuperLoc,
979 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
980 Decl *const *ProtoRefs, unsigned NumProtoRefs,
981 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
982 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
983 assert(ClassName && "Missing class identifier");
984
985 ASTContext &Context = getASTContext();
986 // Check for another declaration kind with the same name.
988 SemaRef.TUScope, ClassName, ClassLoc, Sema::LookupOrdinaryName,
990
991 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
992 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
993 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
994 }
995
996 // Create a declaration to describe this @interface.
997 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
998
999 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
1000 // A previous decl with a different name is because of
1001 // @compatibility_alias, for example:
1002 // \code
1003 // @class NewImage;
1004 // @compatibility_alias OldImage NewImage;
1005 // \endcode
1006 // A lookup for 'OldImage' will return the 'NewImage' decl.
1007 //
1008 // In such a case use the real declaration name, instead of the alias one,
1009 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1010 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1011 // has been aliased.
1012 ClassName = PrevIDecl->getIdentifier();
1013 }
1014
1015 // If there was a forward declaration with type parameters, check
1016 // for consistency.
1017 if (PrevIDecl) {
1018 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1019 if (typeParamList) {
1020 // Both have type parameter lists; check for consistency.
1021 if (checkTypeParamListConsistency(SemaRef, prevTypeParamList,
1022 typeParamList,
1023 TypeParamListContext::Definition)) {
1024 typeParamList = nullptr;
1025 }
1026 } else {
1027 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1028 << ClassName;
1029 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1030 << ClassName;
1031
1032 // Clone the type parameter list.
1033 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1034 for (auto *typeParam : *prevTypeParamList) {
1035 clonedTypeParams.push_back(ObjCTypeParamDecl::Create(
1036 Context, SemaRef.CurContext, typeParam->getVariance(),
1037 SourceLocation(), typeParam->getIndex(), SourceLocation(),
1038 typeParam->getIdentifier(), SourceLocation(),
1040 typeParam->getUnderlyingType())));
1041 }
1042
1043 typeParamList = ObjCTypeParamList::create(Context,
1045 clonedTypeParams,
1046 SourceLocation());
1047 }
1048 }
1049 }
1050
1051 ObjCInterfaceDecl *IDecl =
1052 ObjCInterfaceDecl::Create(Context, SemaRef.CurContext, AtInterfaceLoc,
1053 ClassName, typeParamList, PrevIDecl, ClassLoc);
1054 if (PrevIDecl) {
1055 // Class already seen. Was it a definition?
1056 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1057 if (SkipBody && !SemaRef.hasVisibleDefinition(Def)) {
1058 SkipBody->CheckSameAsPrevious = true;
1059 SkipBody->New = IDecl;
1060 SkipBody->Previous = Def;
1061 } else {
1062 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1063 << PrevIDecl->getDeclName();
1064 Diag(Def->getLocation(), diag::note_previous_definition);
1065 IDecl->setInvalidDecl();
1066 }
1067 }
1068 }
1069
1072 SemaRef.ProcessAPINotes(IDecl);
1073
1074 // Merge attributes from previous declarations.
1075 if (PrevIDecl)
1076 SemaRef.mergeDeclAttributes(IDecl, PrevIDecl);
1077
1079
1080 // Start the definition of this class. If we're in a redefinition case, there
1081 // may already be a definition, so we'll end up adding to it.
1082 if (SkipBody && SkipBody->CheckSameAsPrevious)
1084 else if (!IDecl->hasDefinition())
1085 IDecl->startDefinition();
1086
1087 if (SuperName) {
1088 // Diagnose availability in the context of the @interface.
1089 Sema::ContextRAII SavedContext(SemaRef, IDecl);
1090
1091 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1092 ClassName, ClassLoc,
1093 SuperName, SuperLoc, SuperTypeArgs,
1094 SuperTypeArgsRange);
1095 } else { // we have a root class.
1096 IDecl->setEndOfDefinitionLoc(ClassLoc);
1097 }
1098
1099 // Check then save referenced protocols.
1100 if (NumProtoRefs) {
1101 diagnoseUseOfProtocols(SemaRef, IDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1102 NumProtoRefs, ProtoLocs);
1103 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1104 ProtoLocs, Context);
1105 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1106 }
1107
1108 CheckObjCDeclScope(IDecl);
1110 return IDecl;
1111}
1112
1113/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1114/// typedef'ed use for a qualified super class and adds them to the list
1115/// of the protocols.
1117 SmallVectorImpl<Decl *> &ProtocolRefs,
1118 SmallVectorImpl<SourceLocation> &ProtocolLocs, IdentifierInfo *SuperName,
1119 SourceLocation SuperLoc) {
1120 if (!SuperName)
1121 return;
1123 SemaRef.TUScope, SuperName, SuperLoc, Sema::LookupOrdinaryName);
1124 if (!IDecl)
1125 return;
1126
1127 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1128 QualType T = TDecl->getUnderlyingType();
1129 if (T->isObjCObjectType())
1130 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1131 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1132 // FIXME: Consider whether this should be an invalid loc since the loc
1133 // is not actually pointing to a protocol name reference but to the
1134 // typedef reference. Note that the base class name loc is also pointing
1135 // at the typedef.
1136 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1137 }
1138 }
1139}
1140
1141/// ActOnCompatibilityAlias - this action is called after complete parsing of
1142/// a \@compatibility_alias declaration. It sets up the alias relationships.
1144 IdentifierInfo *AliasName,
1145 SourceLocation AliasLocation,
1146 IdentifierInfo *ClassName,
1147 SourceLocation ClassLocation) {
1148 ASTContext &Context = getASTContext();
1149 // Look for previous declaration of alias name
1151 SemaRef.TUScope, AliasName, AliasLocation, Sema::LookupOrdinaryName,
1153 if (ADecl) {
1154 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1155 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1156 return nullptr;
1157 }
1158 // Check for class declaration
1160 SemaRef.TUScope, ClassName, ClassLocation, Sema::LookupOrdinaryName,
1162 if (const TypedefNameDecl *TDecl =
1163 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1164 QualType T = TDecl->getUnderlyingType();
1165 if (T->isObjCObjectType()) {
1166 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
1167 ClassName = IDecl->getIdentifier();
1168 CDeclU = SemaRef.LookupSingleName(
1169 SemaRef.TUScope, ClassName, ClassLocation, Sema::LookupOrdinaryName,
1171 }
1172 }
1173 }
1174 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1175 if (!CDecl) {
1176 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1177 if (CDeclU)
1178 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1179 return nullptr;
1180 }
1181
1182 // Everything checked out, instantiate a new alias declaration AST.
1184 Context, SemaRef.CurContext, AtLoc, AliasName, CDecl);
1185
1188
1189 return AliasDecl;
1190}
1191
1193 IdentifierInfo *PName, SourceLocation &Ploc, SourceLocation PrevLoc,
1194 const ObjCList<ObjCProtocolDecl> &PList) {
1195
1196 bool res = false;
1198 E = PList.end(); I != E; ++I) {
1199 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(), Ploc)) {
1200 if (PDecl->getIdentifier() == PName) {
1201 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1202 Diag(PrevLoc, diag::note_previous_definition);
1203 res = true;
1204 }
1205
1206 if (!PDecl->hasDefinition())
1207 continue;
1208
1210 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1211 res = true;
1212 }
1213 }
1214 return res;
1215}
1216
1218 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1219 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1220 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1221 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
1222 ASTContext &Context = getASTContext();
1223 bool err = false;
1224 // FIXME: Deal with AttrList.
1225 assert(ProtocolName && "Missing protocol identifier");
1226 ObjCProtocolDecl *PrevDecl = LookupProtocol(
1227 ProtocolName, ProtocolLoc, SemaRef.forRedeclarationInCurContext());
1228 ObjCProtocolDecl *PDecl = nullptr;
1229 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1230 // Create a new protocol that is completely distinct from previous
1231 // declarations, and do not make this protocol available for name lookup.
1232 // That way, we'll end up completely ignoring the duplicate.
1233 // FIXME: Can we turn this into an error?
1234 PDecl = ObjCProtocolDecl::Create(Context, SemaRef.CurContext, ProtocolName,
1235 ProtocolLoc, AtProtoInterfaceLoc,
1236 /*PrevDecl=*/Def);
1237
1238 if (SkipBody && !SemaRef.hasVisibleDefinition(Def)) {
1239 SkipBody->CheckSameAsPrevious = true;
1240 SkipBody->New = PDecl;
1241 SkipBody->Previous = Def;
1242 } else {
1243 // If we already have a definition, complain.
1244 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1245 Diag(Def->getLocation(), diag::note_previous_definition);
1246 }
1247
1248 // If we are using modules, add the decl to the context in order to
1249 // serialize something meaningful.
1250 if (getLangOpts().Modules)
1253 } else {
1254 if (PrevDecl) {
1255 // Check for circular dependencies among protocol declarations. This can
1256 // only happen if this protocol was forward-declared.
1258 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1260 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1261 }
1262
1263 // Create the new declaration.
1264 PDecl = ObjCProtocolDecl::Create(Context, SemaRef.CurContext, ProtocolName,
1265 ProtocolLoc, AtProtoInterfaceLoc,
1266 /*PrevDecl=*/PrevDecl);
1267
1269 PDecl->startDefinition();
1270 }
1271
1274 SemaRef.ProcessAPINotes(PDecl);
1275
1276 // Merge attributes from previous declarations.
1277 if (PrevDecl)
1278 SemaRef.mergeDeclAttributes(PDecl, PrevDecl);
1279
1280 if (!err && NumProtoRefs ) {
1281 /// Check then save referenced protocols.
1282 diagnoseUseOfProtocols(SemaRef, PDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1283 NumProtoRefs, ProtoLocs);
1284 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1285 ProtoLocs, Context);
1286 }
1287
1288 CheckObjCDeclScope(PDecl);
1290 return PDecl;
1291}
1292
1294 ObjCProtocolDecl *&UndefinedProtocol) {
1295 if (!PDecl->hasDefinition() ||
1297 UndefinedProtocol = PDecl;
1298 return true;
1299 }
1300
1301 for (auto *PI : PDecl->protocols())
1302 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1303 UndefinedProtocol = PI;
1304 return true;
1305 }
1306 return false;
1307}
1308
1309/// FindProtocolDeclaration - This routine looks up protocols and
1310/// issues an error if they are not declared. It returns list of
1311/// protocol declarations in its 'Protocols' argument.
1312void SemaObjC::FindProtocolDeclaration(bool WarnOnDeclarations,
1313 bool ForObjCContainer,
1314 ArrayRef<IdentifierLocPair> ProtocolId,
1315 SmallVectorImpl<Decl *> &Protocols) {
1316 for (const IdentifierLocPair &Pair : ProtocolId) {
1317 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1318 if (!PDecl) {
1320 TypoCorrection Corrected =
1321 SemaRef.CorrectTypo(DeclarationNameInfo(Pair.first, Pair.second),
1323 nullptr, CCC, Sema::CTK_ErrorRecovery);
1324 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1326 Corrected, SemaRef.PDiag(diag::err_undeclared_protocol_suggest)
1327 << Pair.first);
1328 }
1329
1330 if (!PDecl) {
1331 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1332 continue;
1333 }
1334 // If this is a forward protocol declaration, get its definition.
1335 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1336 PDecl = PDecl->getDefinition();
1337
1338 // For an objc container, delay protocol reference checking until after we
1339 // can set the objc decl as the availability context, otherwise check now.
1340 if (!ForObjCContainer) {
1341 (void)SemaRef.DiagnoseUseOfDecl(PDecl, Pair.second);
1342 }
1343
1344 // If this is a forward declaration and we are supposed to warn in this
1345 // case, do it.
1346 // FIXME: Recover nicely in the hidden case.
1347 ObjCProtocolDecl *UndefinedProtocol;
1348
1349 if (WarnOnDeclarations &&
1350 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1351 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1352 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1353 << UndefinedProtocol;
1354 }
1355 Protocols.push_back(PDecl);
1356 }
1357}
1358
1359namespace {
1360// Callback to only accept typo corrections that are either
1361// Objective-C protocols or valid Objective-C type arguments.
1362class ObjCTypeArgOrProtocolValidatorCCC final
1364 ASTContext &Context;
1365 Sema::LookupNameKind LookupKind;
1366 public:
1367 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1368 Sema::LookupNameKind lookupKind)
1369 : Context(context), LookupKind(lookupKind) { }
1370
1371 bool ValidateCandidate(const TypoCorrection &candidate) override {
1372 // If we're allowed to find protocols and we have a protocol, accept it.
1373 if (LookupKind != Sema::LookupOrdinaryName) {
1374 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1375 return true;
1376 }
1377
1378 // If we're allowed to find type names and we have one, accept it.
1379 if (LookupKind != Sema::LookupObjCProtocolName) {
1380 // If we have a type declaration, we might accept this result.
1381 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1382 // If we found a tag declaration outside of C++, skip it. This
1383 // can happy because we look for any name when there is no
1384 // bias to protocol or type names.
1385 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1386 return false;
1387
1388 // Make sure the type is something we would accept as a type
1389 // argument.
1390 auto type = Context.getTypeDeclType(typeDecl);
1391 if (type->isObjCObjectPointerType() ||
1392 type->isBlockPointerType() ||
1393 type->isDependentType() ||
1394 type->isObjCObjectType())
1395 return true;
1396
1397 return false;
1398 }
1399
1400 // If we have an Objective-C class type, accept it; there will
1401 // be another fix to add the '*'.
1402 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1403 return true;
1404
1405 return false;
1406 }
1407
1408 return false;
1409 }
1410
1411 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1412 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1413 }
1414};
1415} // end anonymous namespace
1416
1418 SourceLocation ProtocolLoc,
1419 IdentifierInfo *TypeArgId,
1420 SourceLocation TypeArgLoc,
1421 bool SelectProtocolFirst) {
1422 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1423 << SelectProtocolFirst << TypeArgId << ProtocolId
1424 << SourceRange(ProtocolLoc);
1425}
1426
1428 Scope *S, ParsedType baseType, SourceLocation lAngleLoc,
1429 ArrayRef<IdentifierInfo *> identifiers,
1430 ArrayRef<SourceLocation> identifierLocs, SourceLocation rAngleLoc,
1431 SourceLocation &typeArgsLAngleLoc, SmallVectorImpl<ParsedType> &typeArgs,
1432 SourceLocation &typeArgsRAngleLoc, SourceLocation &protocolLAngleLoc,
1433 SmallVectorImpl<Decl *> &protocols, SourceLocation &protocolRAngleLoc,
1434 bool warnOnIncompleteProtocols) {
1435 ASTContext &Context = getASTContext();
1436 // Local function that updates the declaration specifiers with
1437 // protocol information.
1438 unsigned numProtocolsResolved = 0;
1439 auto resolvedAsProtocols = [&] {
1440 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1441
1442 // Determine whether the base type is a parameterized class, in
1443 // which case we want to warn about typos such as
1444 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1445 ObjCInterfaceDecl *baseClass = nullptr;
1446 QualType base = SemaRef.GetTypeFromParser(baseType, nullptr);
1447 bool allAreTypeNames = false;
1448 SourceLocation firstClassNameLoc;
1449 if (!base.isNull()) {
1450 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1451 baseClass = objcObjectType->getInterface();
1452 if (baseClass) {
1453 if (auto typeParams = baseClass->getTypeParamList()) {
1454 if (typeParams->size() == numProtocolsResolved) {
1455 // Note that we should be looking for type names, too.
1456 allAreTypeNames = true;
1457 }
1458 }
1459 }
1460 }
1461 }
1462
1463 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1464 ObjCProtocolDecl *&proto
1465 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1466 // For an objc container, delay protocol reference checking until after we
1467 // can set the objc decl as the availability context, otherwise check now.
1468 if (!warnOnIncompleteProtocols) {
1469 (void)SemaRef.DiagnoseUseOfDecl(proto, identifierLocs[i]);
1470 }
1471
1472 // If this is a forward protocol declaration, get its definition.
1473 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1474 proto = proto->getDefinition();
1475
1476 // If this is a forward declaration and we are supposed to warn in this
1477 // case, do it.
1478 // FIXME: Recover nicely in the hidden case.
1479 ObjCProtocolDecl *forwardDecl = nullptr;
1480 if (warnOnIncompleteProtocols &&
1481 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1482 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1483 << proto->getDeclName();
1484 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1485 << forwardDecl;
1486 }
1487
1488 // If everything this far has been a type name (and we care
1489 // about such things), check whether this name refers to a type
1490 // as well.
1491 if (allAreTypeNames) {
1492 if (auto *decl =
1493 SemaRef.LookupSingleName(S, identifiers[i], identifierLocs[i],
1495 if (isa<ObjCInterfaceDecl>(decl)) {
1496 if (firstClassNameLoc.isInvalid())
1497 firstClassNameLoc = identifierLocs[i];
1498 } else if (!isa<TypeDecl>(decl)) {
1499 // Not a type.
1500 allAreTypeNames = false;
1501 }
1502 } else {
1503 allAreTypeNames = false;
1504 }
1505 }
1506 }
1507
1508 // All of the protocols listed also have type names, and at least
1509 // one is an Objective-C class name. Check whether all of the
1510 // protocol conformances are declared by the base class itself, in
1511 // which case we warn.
1512 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1514 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1515 bool allProtocolsDeclared = true;
1516 for (auto *proto : protocols) {
1517 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1518 allProtocolsDeclared = false;
1519 break;
1520 }
1521 }
1522
1523 if (allProtocolsDeclared) {
1524 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1525 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1527 SemaRef.getLocForEndOfToken(firstClassNameLoc), " *");
1528 }
1529 }
1530
1531 protocolLAngleLoc = lAngleLoc;
1532 protocolRAngleLoc = rAngleLoc;
1533 assert(protocols.size() == identifierLocs.size());
1534 };
1535
1536 // Attempt to resolve all of the identifiers as protocols.
1537 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1538 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1539 protocols.push_back(proto);
1540 if (proto)
1541 ++numProtocolsResolved;
1542 }
1543
1544 // If all of the names were protocols, these were protocol qualifiers.
1545 if (numProtocolsResolved == identifiers.size())
1546 return resolvedAsProtocols();
1547
1548 // Attempt to resolve all of the identifiers as type names or
1549 // Objective-C class names. The latter is technically ill-formed,
1550 // but is probably something like \c NSArray<NSView *> missing the
1551 // \c*.
1552 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1554 unsigned numTypeDeclsResolved = 0;
1555 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1557 S, identifiers[i], identifierLocs[i], Sema::LookupOrdinaryName);
1558 if (!decl) {
1559 typeDecls.push_back(TypeOrClassDecl());
1560 continue;
1561 }
1562
1563 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1564 typeDecls.push_back(typeDecl);
1565 ++numTypeDeclsResolved;
1566 continue;
1567 }
1568
1569 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1570 typeDecls.push_back(objcClass);
1571 ++numTypeDeclsResolved;
1572 continue;
1573 }
1574
1575 typeDecls.push_back(TypeOrClassDecl());
1576 }
1577
1578 AttributeFactory attrFactory;
1579
1580 // Local function that forms a reference to the given type or
1581 // Objective-C class declaration.
1582 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1583 -> TypeResult {
1584 // Form declaration specifiers. They simply refer to the type.
1585 DeclSpec DS(attrFactory);
1586 const char* prevSpec; // unused
1587 unsigned diagID; // unused
1588 QualType type;
1589 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1590 type = Context.getTypeDeclType(actualTypeDecl);
1591 else
1592 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1593 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1594 ParsedType parsedType = SemaRef.CreateParsedType(type, parsedTSInfo);
1595 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1596 parsedType, Context.getPrintingPolicy());
1597 // Use the identifier location for the type source range.
1598 DS.SetRangeStart(loc);
1599 DS.SetRangeEnd(loc);
1600
1601 // Form the declarator.
1603
1604 // If we have a typedef of an Objective-C class type that is missing a '*',
1605 // add the '*'.
1606 if (type->getAs<ObjCInterfaceType>()) {
1608 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1613 SourceLocation()),
1614 starLoc);
1615
1616 // Diagnose the missing '*'.
1617 Diag(loc, diag::err_objc_type_arg_missing_star)
1618 << type
1619 << FixItHint::CreateInsertion(starLoc, " *");
1620 }
1621
1622 // Convert this to a type.
1623 return SemaRef.ActOnTypeName(D);
1624 };
1625
1626 // Local function that updates the declaration specifiers with
1627 // type argument information.
1628 auto resolvedAsTypeDecls = [&] {
1629 // We did not resolve these as protocols.
1630 protocols.clear();
1631
1632 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1633 // Map type declarations to type arguments.
1634 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1635 // Map type reference to a type.
1636 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1637 if (!type.isUsable()) {
1638 typeArgs.clear();
1639 return;
1640 }
1641
1642 typeArgs.push_back(type.get());
1643 }
1644
1645 typeArgsLAngleLoc = lAngleLoc;
1646 typeArgsRAngleLoc = rAngleLoc;
1647 };
1648
1649 // If all of the identifiers can be resolved as type names or
1650 // Objective-C class names, we have type arguments.
1651 if (numTypeDeclsResolved == identifiers.size())
1652 return resolvedAsTypeDecls();
1653
1654 // Error recovery: some names weren't found, or we have a mix of
1655 // type and protocol names. Go resolve all of the unresolved names
1656 // and complain if we can't find a consistent answer.
1658 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1659 // If we already have a protocol or type. Check whether it is the
1660 // right thing.
1661 if (protocols[i] || typeDecls[i]) {
1662 // If we haven't figured out whether we want types or protocols
1663 // yet, try to figure it out from this name.
1664 if (lookupKind == Sema::LookupAnyName) {
1665 // If this name refers to both a protocol and a type (e.g., \c
1666 // NSObject), don't conclude anything yet.
1667 if (protocols[i] && typeDecls[i])
1668 continue;
1669
1670 // Otherwise, let this name decide whether we'll be correcting
1671 // toward types or protocols.
1672 lookupKind = protocols[i] ? Sema::LookupObjCProtocolName
1674 continue;
1675 }
1676
1677 // If we want protocols and we have a protocol, there's nothing
1678 // more to do.
1679 if (lookupKind == Sema::LookupObjCProtocolName && protocols[i])
1680 continue;
1681
1682 // If we want types and we have a type declaration, there's
1683 // nothing more to do.
1684 if (lookupKind == Sema::LookupOrdinaryName && typeDecls[i])
1685 continue;
1686
1687 // We have a conflict: some names refer to protocols and others
1688 // refer to types.
1689 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1690 identifiers[i], identifierLocs[i],
1691 protocols[i] != nullptr);
1692
1693 protocols.clear();
1694 typeArgs.clear();
1695 return;
1696 }
1697
1698 // Perform typo correction on the name.
1699 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1701 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1702 nullptr, CCC, Sema::CTK_ErrorRecovery);
1703 if (corrected) {
1704 // Did we find a protocol?
1705 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1707 corrected, SemaRef.PDiag(diag::err_undeclared_protocol_suggest)
1708 << identifiers[i]);
1709 lookupKind = Sema::LookupObjCProtocolName;
1710 protocols[i] = proto;
1711 ++numProtocolsResolved;
1712 continue;
1713 }
1714
1715 // Did we find a type?
1716 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1717 SemaRef.diagnoseTypo(corrected,
1718 SemaRef.PDiag(diag::err_unknown_typename_suggest)
1719 << identifiers[i]);
1720 lookupKind = Sema::LookupOrdinaryName;
1721 typeDecls[i] = typeDecl;
1722 ++numTypeDeclsResolved;
1723 continue;
1724 }
1725
1726 // Did we find an Objective-C class?
1727 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1729 corrected,
1730 SemaRef.PDiag(diag::err_unknown_type_or_class_name_suggest)
1731 << identifiers[i] << true);
1732 lookupKind = Sema::LookupOrdinaryName;
1733 typeDecls[i] = objcClass;
1734 ++numTypeDeclsResolved;
1735 continue;
1736 }
1737 }
1738
1739 // We couldn't find anything.
1740 Diag(identifierLocs[i],
1741 (lookupKind == Sema::LookupAnyName ? diag::err_objc_type_arg_missing
1742 : lookupKind == Sema::LookupObjCProtocolName
1743 ? diag::err_undeclared_protocol
1744 : diag::err_unknown_typename))
1745 << identifiers[i];
1746 protocols.clear();
1747 typeArgs.clear();
1748 return;
1749 }
1750
1751 // If all of the names were (corrected to) protocols, these were
1752 // protocol qualifiers.
1753 if (numProtocolsResolved == identifiers.size())
1754 return resolvedAsProtocols();
1755
1756 // Otherwise, all of the names were (corrected to) types.
1757 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1758 return resolvedAsTypeDecls();
1759}
1760
1761/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1762/// a class method in its extension.
1763///
1765 ObjCInterfaceDecl *ID) {
1766 if (!ID)
1767 return; // Possibly due to previous error
1768
1769 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1770 for (auto *MD : ID->methods())
1771 MethodMap[MD->getSelector()] = MD;
1772
1773 if (MethodMap.empty())
1774 return;
1775 for (const auto *Method : CAT->methods()) {
1776 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1777 if (PrevMethod &&
1778 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1779 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1780 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1781 << Method->getDeclName();
1782 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1783 }
1784 }
1785}
1786
1787/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1789 SourceLocation AtProtocolLoc, ArrayRef<IdentifierLocPair> IdentList,
1790 const ParsedAttributesView &attrList) {
1791 ASTContext &Context = getASTContext();
1792 SmallVector<Decl *, 8> DeclsInGroup;
1793 for (const IdentifierLocPair &IdentPair : IdentList) {
1794 IdentifierInfo *Ident = IdentPair.first;
1795 ObjCProtocolDecl *PrevDecl = LookupProtocol(
1796 Ident, IdentPair.second, SemaRef.forRedeclarationInCurContext());
1797 ObjCProtocolDecl *PDecl =
1799 IdentPair.second, AtProtocolLoc, PrevDecl);
1800
1802 CheckObjCDeclScope(PDecl);
1803
1806
1807 if (PrevDecl)
1808 SemaRef.mergeDeclAttributes(PDecl, PrevDecl);
1809
1810 DeclsInGroup.push_back(PDecl);
1811 }
1812
1813 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
1814}
1815
1817 SourceLocation AtInterfaceLoc, const IdentifierInfo *ClassName,
1818 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1819 const IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1820 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1821 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1822 const ParsedAttributesView &AttrList) {
1823 ASTContext &Context = getASTContext();
1824 ObjCCategoryDecl *CDecl;
1825 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1826
1827 /// Check that class of this category is already completely declared.
1828
1829 if (!IDecl ||
1830 SemaRef.RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1831 diag::err_category_forward_interface,
1832 CategoryName == nullptr)) {
1833 // Create an invalid ObjCCategoryDecl to serve as context for
1834 // the enclosing method declarations. We mark the decl invalid
1835 // to make it clear that this isn't a valid AST.
1837 AtInterfaceLoc, ClassLoc, CategoryLoc,
1838 CategoryName, IDecl, typeParamList);
1839 CDecl->setInvalidDecl();
1840 SemaRef.CurContext->addDecl(CDecl);
1841
1842 if (!IDecl)
1843 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1845 return CDecl;
1846 }
1847
1848 if (!CategoryName && IDecl->getImplementation()) {
1849 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1851 diag::note_implementation_declared);
1852 }
1853
1854 if (CategoryName) {
1855 /// Check for duplicate interface declaration for this category
1857 = IDecl->FindCategoryDeclaration(CategoryName)) {
1858 // Class extensions can be declared multiple times, categories cannot.
1859 Diag(CategoryLoc, diag::warn_dup_category_def)
1860 << ClassName << CategoryName;
1861 Diag(Previous->getLocation(), diag::note_previous_definition);
1862 }
1863 }
1864
1865 // If we have a type parameter list, check it.
1866 if (typeParamList) {
1867 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1869 SemaRef, prevTypeParamList, typeParamList,
1870 CategoryName ? TypeParamListContext::Category
1871 : TypeParamListContext::Extension))
1872 typeParamList = nullptr;
1873 } else {
1874 Diag(typeParamList->getLAngleLoc(),
1875 diag::err_objc_parameterized_category_nonclass)
1876 << (CategoryName != nullptr)
1877 << ClassName
1878 << typeParamList->getSourceRange();
1879
1880 typeParamList = nullptr;
1881 }
1882 }
1883
1884 CDecl = ObjCCategoryDecl::Create(Context, SemaRef.CurContext, AtInterfaceLoc,
1885 ClassLoc, CategoryLoc, CategoryName, IDecl,
1886 typeParamList);
1887 // FIXME: PushOnScopeChains?
1888 SemaRef.CurContext->addDecl(CDecl);
1889
1890 // Process the attributes before looking at protocols to ensure that the
1891 // availability attribute is attached to the category to provide availability
1892 // checking for protocol uses.
1895
1896 if (NumProtoRefs) {
1897 diagnoseUseOfProtocols(SemaRef, CDecl, (ObjCProtocolDecl *const *)ProtoRefs,
1898 NumProtoRefs, ProtoLocs);
1899 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1900 ProtoLocs, Context);
1901 // Protocols in the class extension belong to the class.
1902 if (CDecl->IsClassExtension())
1903 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1904 NumProtoRefs, Context);
1905 }
1906
1907 CheckObjCDeclScope(CDecl);
1909 return CDecl;
1910}
1911
1912/// ActOnStartCategoryImplementation - Perform semantic checks on the
1913/// category implementation declaration and build an ObjCCategoryImplDecl
1914/// object.
1916 SourceLocation AtCatImplLoc, const IdentifierInfo *ClassName,
1917 SourceLocation ClassLoc, const IdentifierInfo *CatName,
1918 SourceLocation CatLoc, const ParsedAttributesView &Attrs) {
1919 ASTContext &Context = getASTContext();
1920 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1921 ObjCCategoryDecl *CatIDecl = nullptr;
1922 if (IDecl && IDecl->hasDefinition()) {
1923 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1924 if (!CatIDecl) {
1925 // Category @implementation with no corresponding @interface.
1926 // Create and install one.
1927 CatIDecl =
1928 ObjCCategoryDecl::Create(Context, SemaRef.CurContext, AtCatImplLoc,
1929 ClassLoc, CatLoc, CatName, IDecl,
1930 /*typeParamList=*/nullptr);
1931 CatIDecl->setImplicit();
1932 }
1933 }
1934
1935 ObjCCategoryImplDecl *CDecl =
1936 ObjCCategoryImplDecl::Create(Context, SemaRef.CurContext, CatName, IDecl,
1937 ClassLoc, AtCatImplLoc, CatLoc);
1938 /// Check that class of this category is already completely declared.
1939 if (!IDecl) {
1940 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1941 CDecl->setInvalidDecl();
1942 } else if (SemaRef.RequireCompleteType(ClassLoc,
1943 Context.getObjCInterfaceType(IDecl),
1944 diag::err_undef_interface)) {
1945 CDecl->setInvalidDecl();
1946 }
1947
1950
1951 // FIXME: PushOnScopeChains?
1952 SemaRef.CurContext->addDecl(CDecl);
1953
1954 // If the interface has the objc_runtime_visible attribute, we
1955 // cannot implement a category for it.
1956 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1957 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1958 << IDecl->getDeclName();
1959 }
1960
1961 /// Check that CatName, category name, is not used in another implementation.
1962 if (CatIDecl) {
1963 if (CatIDecl->getImplementation()) {
1964 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1965 << CatName;
1966 Diag(CatIDecl->getImplementation()->getLocation(),
1967 diag::note_previous_definition);
1968 CDecl->setInvalidDecl();
1969 } else {
1970 CatIDecl->setImplementation(CDecl);
1971 // Warn on implementating category of deprecated class under
1972 // -Wdeprecated-implementations flag.
1974 CDecl->getLocation());
1975 }
1976 }
1977
1978 CheckObjCDeclScope(CDecl);
1980 return CDecl;
1981}
1982
1984 SourceLocation AtClassImplLoc, const IdentifierInfo *ClassName,
1985 SourceLocation ClassLoc, const IdentifierInfo *SuperClassname,
1986 SourceLocation SuperClassLoc, const ParsedAttributesView &Attrs) {
1987 ASTContext &Context = getASTContext();
1988 ObjCInterfaceDecl *IDecl = nullptr;
1989 // Check for another declaration kind with the same name.
1991 SemaRef.TUScope, ClassName, ClassLoc, Sema::LookupOrdinaryName,
1993 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1994 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1995 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1996 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1997 // FIXME: This will produce an error if the definition of the interface has
1998 // been imported from a module but is not visible.
1999 SemaRef.RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
2000 diag::warn_undef_interface);
2001 } else {
2002 // We did not find anything with the name ClassName; try to correct for
2003 // typos in the class name.
2004 ObjCInterfaceValidatorCCC CCC{};
2006 DeclarationNameInfo(ClassName, ClassLoc), Sema::LookupOrdinaryName,
2007 SemaRef.TUScope, nullptr, CCC, Sema::CTK_NonError);
2008 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2009 // Suggest the (potentially) correct interface name. Don't provide a
2010 // code-modification hint or use the typo name for recovery, because
2011 // this is just a warning. The program may actually be correct.
2012 SemaRef.diagnoseTypo(Corrected,
2013 SemaRef.PDiag(diag::warn_undef_interface_suggest)
2014 << ClassName,
2015 /*ErrorRecovery*/ false);
2016 } else {
2017 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
2018 }
2019 }
2020
2021 // Check that super class name is valid class name
2022 ObjCInterfaceDecl *SDecl = nullptr;
2023 if (SuperClassname) {
2024 // Check if a different kind of symbol declared in this scope.
2025 PrevDecl =
2026 SemaRef.LookupSingleName(SemaRef.TUScope, SuperClassname, SuperClassLoc,
2028 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2029 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2030 << SuperClassname;
2031 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2032 } else {
2033 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2034 if (SDecl && !SDecl->hasDefinition())
2035 SDecl = nullptr;
2036 if (!SDecl)
2037 Diag(SuperClassLoc, diag::err_undef_superclass)
2038 << SuperClassname << ClassName;
2039 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2040 // This implementation and its interface do not have the same
2041 // super class.
2042 Diag(SuperClassLoc, diag::err_conflicting_super_class)
2043 << SDecl->getDeclName();
2044 Diag(SDecl->getLocation(), diag::note_previous_definition);
2045 }
2046 }
2047 }
2048
2049 if (!IDecl) {
2050 // Legacy case of @implementation with no corresponding @interface.
2051 // Build, chain & install the interface decl into the identifier.
2052
2053 // FIXME: Do we support attributes on the @implementation? If so we should
2054 // copy them over.
2055 IDecl =
2056 ObjCInterfaceDecl::Create(Context, SemaRef.CurContext, AtClassImplLoc,
2057 ClassName, /*typeParamList=*/nullptr,
2058 /*PrevDecl=*/nullptr, ClassLoc, true);
2060 IDecl->startDefinition();
2061 if (SDecl) {
2063 Context.getObjCInterfaceType(SDecl),
2064 SuperClassLoc));
2065 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2066 } else {
2067 IDecl->setEndOfDefinitionLoc(ClassLoc);
2068 }
2069
2071 } else {
2072 // Mark the interface as being completed, even if it was just as
2073 // @class ....;
2074 // declaration; the user cannot reopen it.
2075 if (!IDecl->hasDefinition())
2076 IDecl->startDefinition();
2077 }
2078
2079 ObjCImplementationDecl *IMPDecl =
2080 ObjCImplementationDecl::Create(Context, SemaRef.CurContext, IDecl, SDecl,
2081 ClassLoc, AtClassImplLoc, SuperClassLoc);
2082
2085
2086 if (CheckObjCDeclScope(IMPDecl)) {
2088 return IMPDecl;
2089 }
2090
2091 // Check that there is no duplicate implementation of this class.
2092 if (IDecl->getImplementation()) {
2093 // FIXME: Don't leak everything!
2094 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2096 diag::note_previous_definition);
2097 IMPDecl->setInvalidDecl();
2098 } else { // add it to the list.
2099 IDecl->setImplementation(IMPDecl);
2101 // Warn on implementating deprecated class under
2102 // -Wdeprecated-implementations flag.
2104 }
2105
2106 // If the superclass has the objc_runtime_visible attribute, we
2107 // cannot implement a subclass of it.
2108 if (IDecl->getSuperClass() &&
2109 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2110 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2111 << IDecl->getDeclName()
2112 << IDecl->getSuperClass()->getDeclName();
2113 }
2114
2116 return IMPDecl;
2117}
2118
2121 ArrayRef<Decl *> Decls) {
2122 SmallVector<Decl *, 64> DeclsInGroup;
2123 DeclsInGroup.reserve(Decls.size() + 1);
2124
2125 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2126 Decl *Dcl = Decls[i];
2127 if (!Dcl)
2128 continue;
2129 if (Dcl->getDeclContext()->isFileContext())
2131 DeclsInGroup.push_back(Dcl);
2132 }
2133
2134 DeclsInGroup.push_back(ObjCImpDecl);
2135
2136 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
2137}
2138
2140 ObjCIvarDecl **ivars, unsigned numIvars,
2141 SourceLocation RBrace) {
2142 assert(ImpDecl && "missing implementation decl");
2143 ASTContext &Context = getASTContext();
2144 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2145 if (!IDecl)
2146 return;
2147 /// Check case of non-existing \@interface decl.
2148 /// (legacy objective-c \@implementation decl without an \@interface decl).
2149 /// Add implementations's ivar to the synthesize class's ivar list.
2150 if (IDecl->isImplicitInterfaceDecl()) {
2151 IDecl->setEndOfDefinitionLoc(RBrace);
2152 // Add ivar's to class's DeclContext.
2153 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2154 ivars[i]->setLexicalDeclContext(ImpDecl);
2155 // In a 'fragile' runtime the ivar was added to the implicit
2156 // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is
2157 // only in the ObjCImplementationDecl. In the non-fragile case the ivar
2158 // therefore also needs to be propagated to the ObjCInterfaceDecl.
2160 IDecl->makeDeclVisibleInContext(ivars[i]);
2161 ImpDecl->addDecl(ivars[i]);
2162 }
2163
2164 return;
2165 }
2166 // If implementation has empty ivar list, just return.
2167 if (numIvars == 0)
2168 return;
2169
2170 assert(ivars && "missing @implementation ivars");
2172 if (ImpDecl->getSuperClass())
2173 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2174 for (unsigned i = 0; i < numIvars; i++) {
2175 ObjCIvarDecl* ImplIvar = ivars[i];
2176 if (const ObjCIvarDecl *ClsIvar =
2177 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2178 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2179 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2180 continue;
2181 }
2182 // Check class extensions (unnamed categories) for duplicate ivars.
2183 for (const auto *CDecl : IDecl->visible_extensions()) {
2184 if (const ObjCIvarDecl *ClsExtIvar =
2185 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2186 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2187 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2188 continue;
2189 }
2190 }
2191 // Instance ivar to Implementation's DeclContext.
2192 ImplIvar->setLexicalDeclContext(ImpDecl);
2193 IDecl->makeDeclVisibleInContext(ImplIvar);
2194 ImpDecl->addDecl(ImplIvar);
2195 }
2196 return;
2197 }
2198 // Check interface's Ivar list against those in the implementation.
2199 // names and types must match.
2200 //
2201 unsigned j = 0;
2203 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2204 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2205 ObjCIvarDecl* ImplIvar = ivars[j++];
2206 ObjCIvarDecl* ClsIvar = *IVI;
2207 assert (ImplIvar && "missing implementation ivar");
2208 assert (ClsIvar && "missing class ivar");
2209
2210 // First, make sure the types match.
2211 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2212 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2213 << ImplIvar->getIdentifier()
2214 << ImplIvar->getType() << ClsIvar->getType();
2215 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2216 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2217 ImplIvar->getBitWidthValue(Context) !=
2218 ClsIvar->getBitWidthValue(Context)) {
2219 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2220 diag::err_conflicting_ivar_bitwidth)
2221 << ImplIvar->getIdentifier();
2222 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2223 diag::note_previous_definition);
2224 }
2225 // Make sure the names are identical.
2226 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2227 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2228 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2229 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2230 }
2231 --numIvars;
2232 }
2233
2234 if (numIvars > 0)
2235 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2236 else if (IVI != IVE)
2237 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2238}
2239
2241 // No point warning no definition of method which is 'unavailable'.
2242 return M->getAvailability() != AR_Unavailable;
2243}
2244
2246 ObjCMethodDecl *method, bool &IncompleteImpl,
2247 unsigned DiagID,
2248 NamedDecl *NeededFor = nullptr) {
2249 if (!shouldWarnUndefinedMethod(method))
2250 return;
2251
2252 // FIXME: For now ignore 'IncompleteImpl'.
2253 // Previously we grouped all unimplemented methods under a single
2254 // warning, but some users strongly voiced that they would prefer
2255 // separate warnings. We will give that approach a try, as that
2256 // matches what we do with protocols.
2257 {
2259 S.Diag(Impl->getLocation(), DiagID);
2260 B << method;
2261 if (NeededFor)
2262 B << NeededFor;
2263
2264 // Add an empty definition at the end of the @implementation.
2265 std::string FixItStr;
2266 llvm::raw_string_ostream Out(FixItStr);
2267 method->print(Out, Impl->getASTContext().getPrintingPolicy());
2268 Out << " {\n}\n\n";
2269
2271 B << FixItHint::CreateInsertion(Loc, FixItStr);
2272 }
2273
2274 // Issue a note to the original declaration.
2275 SourceLocation MethodLoc = method->getBeginLoc();
2276 if (MethodLoc.isValid())
2277 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2278}
2279
2280/// Determines if type B can be substituted for type A. Returns true if we can
2281/// guarantee that anything that the user will do to an object of type A can
2282/// also be done to an object of type B. This is trivially true if the two
2283/// types are the same, or if B is a subclass of A. It becomes more complex
2284/// in cases where protocols are involved.
2285///
2286/// Object types in Objective-C describe the minimum requirements for an
2287/// object, rather than providing a complete description of a type. For
2288/// example, if A is a subclass of B, then B* may refer to an instance of A.
2289/// The principle of substitutability means that we may use an instance of A
2290/// anywhere that we may use an instance of B - it will implement all of the
2291/// ivars of B and all of the methods of B.
2292///
2293/// This substitutability is important when type checking methods, because
2294/// the implementation may have stricter type definitions than the interface.
2295/// The interface specifies minimum requirements, but the implementation may
2296/// have more accurate ones. For example, a method may privately accept
2297/// instances of B, but only publish that it accepts instances of A. Any
2298/// object passed to it will be type checked against B, and so will implicitly
2299/// by a valid A*. Similarly, a method may return a subclass of the class that
2300/// it is declared as returning.
2301///
2302/// This is most important when considering subclassing. A method in a
2303/// subclass must accept any object as an argument that its superclass's
2304/// implementation accepts. It may, however, accept a more general type
2305/// without breaking substitutability (i.e. you can still use the subclass
2306/// anywhere that you can use the superclass, but not vice versa). The
2307/// converse requirement applies to return types: the return type for a
2308/// subclass method must be a valid object of the kind that the superclass
2309/// advertises, but it may be specified more accurately. This avoids the need
2310/// for explicit down-casting by callers.
2311///
2312/// Note: This is a stricter requirement than for assignment.
2314 const ObjCObjectPointerType *A,
2315 const ObjCObjectPointerType *B,
2316 bool rejectId) {
2317 // Reject a protocol-unqualified id.
2318 if (rejectId && B->isObjCIdType()) return false;
2319
2320 // If B is a qualified id, then A must also be a qualified id and it must
2321 // implement all of the protocols in B. It may not be a qualified class.
2322 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2323 // stricter definition so it is not substitutable for id<A>.
2324 if (B->isObjCQualifiedIdType()) {
2325 return A->isObjCQualifiedIdType() &&
2326 Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2327 }
2328
2329 /*
2330 // id is a special type that bypasses type checking completely. We want a
2331 // warning when it is used in one place but not another.
2332 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2333
2334
2335 // If B is a qualified id, then A must also be a qualified id (which it isn't
2336 // if we've got this far)
2337 if (B->isObjCQualifiedIdType()) return false;
2338 */
2339
2340 // Now we know that A and B are (potentially-qualified) class types. The
2341 // normal rules for assignment apply.
2342 return Context.canAssignObjCInterfaces(A, B);
2343}
2344
2346 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2347}
2348
2349/// Determine whether two set of Objective-C declaration qualifiers conflict.
2352 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2353 (y & ~Decl::OBJC_TQ_CSNullability);
2354}
2355
2357 ObjCMethodDecl *MethodImpl,
2358 ObjCMethodDecl *MethodDecl,
2359 bool IsProtocolMethodDecl,
2360 bool IsOverridingMode,
2361 bool Warn) {
2362 if (IsProtocolMethodDecl &&
2364 MethodImpl->getObjCDeclQualifier())) {
2365 if (Warn) {
2366 S.Diag(MethodImpl->getLocation(),
2367 (IsOverridingMode
2368 ? diag::warn_conflicting_overriding_ret_type_modifiers
2369 : diag::warn_conflicting_ret_type_modifiers))
2370 << MethodImpl->getDeclName()
2371 << MethodImpl->getReturnTypeSourceRange();
2372 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2373 << MethodDecl->getReturnTypeSourceRange();
2374 }
2375 else
2376 return false;
2377 }
2378 if (Warn && IsOverridingMode &&
2379 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2381 MethodDecl->getReturnType(),
2382 false)) {
2383 auto nullabilityMethodImpl = *MethodImpl->getReturnType()->getNullability();
2384 auto nullabilityMethodDecl = *MethodDecl->getReturnType()->getNullability();
2385 S.Diag(MethodImpl->getLocation(),
2386 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2387 << DiagNullabilityKind(nullabilityMethodImpl,
2388 ((MethodImpl->getObjCDeclQualifier() &
2390 << DiagNullabilityKind(nullabilityMethodDecl,
2391 ((MethodDecl->getObjCDeclQualifier() &
2393 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2394 }
2395
2396 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2397 MethodDecl->getReturnType()))
2398 return true;
2399 if (!Warn)
2400 return false;
2401
2402 unsigned DiagID =
2403 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2404 : diag::warn_conflicting_ret_types;
2405
2406 // Mismatches between ObjC pointers go into a different warning
2407 // category, and sometimes they're even completely explicitly allowed.
2408 if (const ObjCObjectPointerType *ImplPtrTy =
2409 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2410 if (const ObjCObjectPointerType *IfacePtrTy =
2411 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2412 // Allow non-matching return types as long as they don't violate
2413 // the principle of substitutability. Specifically, we permit
2414 // return types that are subclasses of the declared return type,
2415 // or that are more-qualified versions of the declared type.
2416 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2417 return false;
2418
2419 DiagID =
2420 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2421 : diag::warn_non_covariant_ret_types;
2422 }
2423 }
2424
2425 S.Diag(MethodImpl->getLocation(), DiagID)
2426 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2427 << MethodImpl->getReturnType()
2428 << MethodImpl->getReturnTypeSourceRange();
2429 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2430 ? diag::note_previous_declaration
2431 : diag::note_previous_definition)
2432 << MethodDecl->getReturnTypeSourceRange();
2433 return false;
2434}
2435
2437 ObjCMethodDecl *MethodImpl,
2438 ObjCMethodDecl *MethodDecl,
2439 ParmVarDecl *ImplVar,
2440 ParmVarDecl *IfaceVar,
2441 bool IsProtocolMethodDecl,
2442 bool IsOverridingMode,
2443 bool Warn) {
2444 if (IsProtocolMethodDecl &&
2446 IfaceVar->getObjCDeclQualifier())) {
2447 if (Warn) {
2448 if (IsOverridingMode)
2449 S.Diag(ImplVar->getLocation(),
2450 diag::warn_conflicting_overriding_param_modifiers)
2451 << getTypeRange(ImplVar->getTypeSourceInfo())
2452 << MethodImpl->getDeclName();
2453 else S.Diag(ImplVar->getLocation(),
2454 diag::warn_conflicting_param_modifiers)
2455 << getTypeRange(ImplVar->getTypeSourceInfo())
2456 << MethodImpl->getDeclName();
2457 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2458 << getTypeRange(IfaceVar->getTypeSourceInfo());
2459 }
2460 else
2461 return false;
2462 }
2463
2464 QualType ImplTy = ImplVar->getType();
2465 QualType IfaceTy = IfaceVar->getType();
2466 if (Warn && IsOverridingMode &&
2467 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2468 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2469 S.Diag(ImplVar->getLocation(),
2470 diag::warn_conflicting_nullability_attr_overriding_param_types)
2471 << DiagNullabilityKind(*ImplTy->getNullability(),
2472 ((ImplVar->getObjCDeclQualifier() &
2474 << DiagNullabilityKind(*IfaceTy->getNullability(),
2475 ((IfaceVar->getObjCDeclQualifier() &
2477 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2478 }
2479 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2480 return true;
2481
2482 if (!Warn)
2483 return false;
2484 unsigned DiagID =
2485 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2486 : diag::warn_conflicting_param_types;
2487
2488 // Mismatches between ObjC pointers go into a different warning
2489 // category, and sometimes they're even completely explicitly allowed..
2490 if (const ObjCObjectPointerType *ImplPtrTy =
2491 ImplTy->getAs<ObjCObjectPointerType>()) {
2492 if (const ObjCObjectPointerType *IfacePtrTy =
2493 IfaceTy->getAs<ObjCObjectPointerType>()) {
2494 // Allow non-matching argument types as long as they don't
2495 // violate the principle of substitutability. Specifically, the
2496 // implementation must accept any objects that the superclass
2497 // accepts, however it may also accept others.
2498 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2499 return false;
2500
2501 DiagID =
2502 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2503 : diag::warn_non_contravariant_param_types;
2504 }
2505 }
2506
2507 S.Diag(ImplVar->getLocation(), DiagID)
2508 << getTypeRange(ImplVar->getTypeSourceInfo())
2509 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2510 S.Diag(IfaceVar->getLocation(),
2511 (IsOverridingMode ? diag::note_previous_declaration
2512 : diag::note_previous_definition))
2513 << getTypeRange(IfaceVar->getTypeSourceInfo());
2514 return false;
2515}
2516
2517/// In ARC, check whether the conventional meanings of the two methods
2518/// match. If they don't, it's a hard error.
2521 ObjCMethodFamily implFamily = impl->getMethodFamily();
2522 ObjCMethodFamily declFamily = decl->getMethodFamily();
2523 if (implFamily == declFamily) return false;
2524
2525 // Since conventions are sorted by selector, the only possibility is
2526 // that the types differ enough to cause one selector or the other
2527 // to fall out of the family.
2528 assert(implFamily == OMF_None || declFamily == OMF_None);
2529
2530 // No further diagnostics required on invalid declarations.
2531 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2532
2533 const ObjCMethodDecl *unmatched = impl;
2534 ObjCMethodFamily family = declFamily;
2535 unsigned errorID = diag::err_arc_lost_method_convention;
2536 unsigned noteID = diag::note_arc_lost_method_convention;
2537 if (declFamily == OMF_None) {
2538 unmatched = decl;
2539 family = implFamily;
2540 errorID = diag::err_arc_gained_method_convention;
2541 noteID = diag::note_arc_gained_method_convention;
2542 }
2543
2544 // Indexes into a %select clause in the diagnostic.
2545 enum FamilySelector {
2546 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2547 };
2548 FamilySelector familySelector = FamilySelector();
2549
2550 switch (family) {
2551 case OMF_None: llvm_unreachable("logic error, no method convention");
2552 case OMF_retain:
2553 case OMF_release:
2554 case OMF_autorelease:
2555 case OMF_dealloc:
2556 case OMF_finalize:
2557 case OMF_retainCount:
2558 case OMF_self:
2559 case OMF_initialize:
2561 // Mismatches for these methods don't change ownership
2562 // conventions, so we don't care.
2563 return false;
2564
2565 case OMF_init: familySelector = F_init; break;
2566 case OMF_alloc: familySelector = F_alloc; break;
2567 case OMF_copy: familySelector = F_copy; break;
2568 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2569 case OMF_new: familySelector = F_new; break;
2570 }
2571
2572 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2573 ReasonSelector reasonSelector;
2574
2575 // The only reason these methods don't fall within their families is
2576 // due to unusual result types.
2577 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2578 reasonSelector = R_UnrelatedReturn;
2579 } else {
2580 reasonSelector = R_NonObjectReturn;
2581 }
2582
2583 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2584 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2585
2586 return true;
2587}
2588
2590 ObjCMethodDecl *MethodDecl,
2591 bool IsProtocolMethodDecl) {
2592 if (getLangOpts().ObjCAutoRefCount &&
2593 checkMethodFamilyMismatch(SemaRef, ImpMethodDecl, MethodDecl))
2594 return;
2595
2596 CheckMethodOverrideReturn(SemaRef, ImpMethodDecl, MethodDecl,
2597 IsProtocolMethodDecl, false, true);
2598
2599 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2600 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2601 EF = MethodDecl->param_end();
2602 IM != EM && IF != EF; ++IM, ++IF) {
2603 CheckMethodOverrideParam(SemaRef, ImpMethodDecl, MethodDecl, *IM, *IF,
2604 IsProtocolMethodDecl, false, true);
2605 }
2606
2607 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2608 Diag(ImpMethodDecl->getLocation(),
2609 diag::warn_conflicting_variadic);
2610 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2611 }
2612}
2613
2615 ObjCMethodDecl *Overridden,
2616 bool IsProtocolMethodDecl) {
2617
2618 CheckMethodOverrideReturn(SemaRef, Method, Overridden, IsProtocolMethodDecl,
2619 true, true);
2620
2621 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2622 IF = Overridden->param_begin(), EM = Method->param_end(),
2623 EF = Overridden->param_end();
2624 IM != EM && IF != EF; ++IM, ++IF) {
2625 CheckMethodOverrideParam(SemaRef, Method, Overridden, *IM, *IF,
2626 IsProtocolMethodDecl, true, true);
2627 }
2628
2629 if (Method->isVariadic() != Overridden->isVariadic()) {
2630 Diag(Method->getLocation(),
2631 diag::warn_conflicting_overriding_variadic);
2632 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2633 }
2634}
2635
2636/// WarnExactTypedMethods - This routine issues a warning if method
2637/// implementation declaration matches exactly that of its declaration.
2639 ObjCMethodDecl *MethodDecl,
2640 bool IsProtocolMethodDecl) {
2641 ASTContext &Context = getASTContext();
2642 // don't issue warning when protocol method is optional because primary
2643 // class is not required to implement it and it is safe for protocol
2644 // to implement it.
2645 if (MethodDecl->getImplementationControl() ==
2647 return;
2648 // don't issue warning when primary class's method is
2649 // deprecated/unavailable.
2650 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2651 MethodDecl->hasAttr<DeprecatedAttr>())
2652 return;
2653
2654 bool match = CheckMethodOverrideReturn(SemaRef, ImpMethodDecl, MethodDecl,
2655 IsProtocolMethodDecl, false, false);
2656 if (match)
2657 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2658 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2659 EF = MethodDecl->param_end();
2660 IM != EM && IF != EF; ++IM, ++IF) {
2661 match = CheckMethodOverrideParam(SemaRef, ImpMethodDecl, MethodDecl, *IM,
2662 *IF, IsProtocolMethodDecl, false, false);
2663 if (!match)
2664 break;
2665 }
2666 if (match)
2667 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2668 if (match)
2669 match = !(MethodDecl->isClassMethod() &&
2670 MethodDecl->getSelector() == GetNullarySelector("load", Context));
2671
2672 if (match) {
2673 Diag(ImpMethodDecl->getLocation(),
2674 diag::warn_category_method_impl_match);
2675 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2676 << MethodDecl->getDeclName();
2677 }
2678}
2679
2680/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2681/// improve the efficiency of selector lookups and type checking by associating
2682/// with each protocol / interface / category the flattened instance tables. If
2683/// we used an immutable set to keep the table then it wouldn't add significant
2684/// memory cost and it would be handy for lookups.
2685
2687typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2688
2690 ProtocolNameSet &PNS) {
2691 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2692 PNS.insert(PDecl->getIdentifier());
2693 for (const auto *PI : PDecl->protocols())
2695}
2696
2697/// Recursively populates a set with all conformed protocols in a class
2698/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2699/// attribute.
2701 ProtocolNameSet &PNS) {
2702 if (!Super)
2703 return;
2704
2705 for (const auto *I : Super->all_referenced_protocols())
2707
2709}
2710
2711/// CheckProtocolMethodDefs - This routine checks unimplemented methods
2712/// Declared in protocol, and those referenced by it.
2714 Sema &S, ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool &IncompleteImpl,
2715 const SemaObjC::SelectorSet &InsMap, const SemaObjC::SelectorSet &ClsMap,
2716 ObjCContainerDecl *CDecl, LazyProtocolNameSet &ProtocolsExplictImpl) {
2717 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2718 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2719 : dyn_cast<ObjCInterfaceDecl>(CDecl);
2720 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2721
2722 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2723 ObjCInterfaceDecl *NSIDecl = nullptr;
2724
2725 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2726 // then we should check if any class in the super class hierarchy also
2727 // conforms to this protocol, either directly or via protocol inheritance.
2728 // If so, we can skip checking this protocol completely because we
2729 // know that a parent class already satisfies this protocol.
2730 //
2731 // Note: we could generalize this logic for all protocols, and merely
2732 // add the limit on looking at the super class chain for just
2733 // specially marked protocols. This may be a good optimization. This
2734 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2735 // protocols for now for controlled evaluation.
2736 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2737 if (!ProtocolsExplictImpl) {
2738 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2739 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2740 }
2741 if (ProtocolsExplictImpl->contains(PDecl->getIdentifier()))
2742 return;
2743
2744 // If no super class conforms to the protocol, we should not search
2745 // for methods in the super class to implicitly satisfy the protocol.
2746 Super = nullptr;
2747 }
2748
2750 // check to see if class implements forwardInvocation method and objects
2751 // of this class are derived from 'NSProxy' so that to forward requests
2752 // from one object to another.
2753 // Under such conditions, which means that every method possible is
2754 // implemented in the class, we should not issue "Method definition not
2755 // found" warnings.
2756 // FIXME: Use a general GetUnarySelector method for this.
2757 const IdentifierInfo *II = &S.Context.Idents.get("forwardInvocation");
2758 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2759 if (InsMap.count(fISelector))
2760 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2761 // need be implemented in the implementation.
2762 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2763 }
2764
2765 // If this is a forward protocol declaration, get its definition.
2766 if (!PDecl->isThisDeclarationADefinition() &&
2767 PDecl->getDefinition())
2768 PDecl = PDecl->getDefinition();
2769
2770 // If a method lookup fails locally we still need to look and see if
2771 // the method was implemented by a base class or an inherited
2772 // protocol. This lookup is slow, but occurs rarely in correct code
2773 // and otherwise would terminate in a warning.
2774
2775 // check unimplemented instance methods.
2776 if (!NSIDecl)
2777 for (auto *method : PDecl->instance_methods()) {
2778 if (method->getImplementationControl() !=
2780 !method->isPropertyAccessor() &&
2781 !InsMap.count(method->getSelector()) &&
2782 (!Super || !Super->lookupMethod(
2783 method->getSelector(), true /* instance */,
2784 false /* shallowCategory */, true /* followsSuper */,
2785 nullptr /* category */))) {
2786 // If a method is not implemented in the category implementation but
2787 // has been declared in its primary class, superclass,
2788 // or in one of their protocols, no need to issue the warning.
2789 // This is because method will be implemented in the primary class
2790 // or one of its super class implementation.
2791
2792 // Ugly, but necessary. Method declared in protocol might have
2793 // have been synthesized due to a property declared in the class which
2794 // uses the protocol.
2795 if (ObjCMethodDecl *MethodInClass = IDecl->lookupMethod(
2796 method->getSelector(), true /* instance */,
2797 true /* shallowCategoryLookup */, false /* followSuper */))
2798 if (C || MethodInClass->isPropertyAccessor())
2799 continue;
2800 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2801 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2802 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2803 }
2804 }
2805 }
2806 // check unimplemented class methods
2807 for (auto *method : PDecl->class_methods()) {
2808 if (method->getImplementationControl() !=
2810 !ClsMap.count(method->getSelector()) &&
2811 (!Super || !Super->lookupMethod(
2812 method->getSelector(), false /* class method */,
2813 false /* shallowCategoryLookup */,
2814 true /* followSuper */, nullptr /* category */))) {
2815 // See above comment for instance method lookups.
2816 if (C && IDecl->lookupMethod(method->getSelector(),
2817 false /* class */,
2818 true /* shallowCategoryLookup */,
2819 false /* followSuper */))
2820 continue;
2821
2822 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2823 if (!S.Diags.isIgnored(DIAG, Impl->getLocation())) {
2824 WarnUndefinedMethod(S, Impl, method, IncompleteImpl, DIAG, PDecl);
2825 }
2826 }
2827 }
2828 // Check on this protocols's referenced protocols, recursively.
2829 for (auto *PI : PDecl->protocols())
2830 CheckProtocolMethodDefs(S, Impl, PI, IncompleteImpl, InsMap, ClsMap, CDecl,
2831 ProtocolsExplictImpl);
2832}
2833
2834/// MatchAllMethodDeclarations - Check methods declared in interface
2835/// or protocol against those declared in their implementations.
2836///
2838 const SelectorSet &InsMap, const SelectorSet &ClsMap,
2839 SelectorSet &InsMapSeen, SelectorSet &ClsMapSeen, ObjCImplDecl *IMPDecl,
2840 ObjCContainerDecl *CDecl, bool &IncompleteImpl, bool ImmediateClass,
2841 bool WarnCategoryMethodImpl) {
2842 // Check and see if instance methods in class interface have been
2843 // implemented in the implementation class. If so, their types match.
2844 for (auto *I : CDecl->instance_methods()) {
2845 if (!InsMapSeen.insert(I->getSelector()).second)
2846 continue;
2847 if (!I->isPropertyAccessor() &&
2848 !InsMap.count(I->getSelector())) {
2849 if (ImmediateClass)
2850 WarnUndefinedMethod(SemaRef, IMPDecl, I, IncompleteImpl,
2851 diag::warn_undef_method_impl);
2852 continue;
2853 } else {
2854 ObjCMethodDecl *ImpMethodDecl =
2855 IMPDecl->getInstanceMethod(I->getSelector());
2856 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2857 "Expected to find the method through lookup as well");
2858 // ImpMethodDecl may be null as in a @dynamic property.
2859 if (ImpMethodDecl) {
2860 // Skip property accessor function stubs.
2861 if (ImpMethodDecl->isSynthesizedAccessorStub())
2862 continue;
2863 if (!WarnCategoryMethodImpl)
2864 WarnConflictingTypedMethods(ImpMethodDecl, I,
2865 isa<ObjCProtocolDecl>(CDecl));
2866 else if (!I->isPropertyAccessor())
2867 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2868 }
2869 }
2870 }
2871
2872 // Check and see if class methods in class interface have been
2873 // implemented in the implementation class. If so, their types match.
2874 for (auto *I : CDecl->class_methods()) {
2875 if (!ClsMapSeen.insert(I->getSelector()).second)
2876 continue;
2877 if (!I->isPropertyAccessor() &&
2878 !ClsMap.count(I->getSelector())) {
2879 if (ImmediateClass)
2880 WarnUndefinedMethod(SemaRef, IMPDecl, I, IncompleteImpl,
2881 diag::warn_undef_method_impl);
2882 } else {
2883 ObjCMethodDecl *ImpMethodDecl =
2884 IMPDecl->getClassMethod(I->getSelector());
2885 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2886 "Expected to find the method through lookup as well");
2887 // ImpMethodDecl may be null as in a @dynamic property.
2888 if (ImpMethodDecl) {
2889 // Skip property accessor function stubs.
2890 if (ImpMethodDecl->isSynthesizedAccessorStub())
2891 continue;
2892 if (!WarnCategoryMethodImpl)
2893 WarnConflictingTypedMethods(ImpMethodDecl, I,
2894 isa<ObjCProtocolDecl>(CDecl));
2895 else if (!I->isPropertyAccessor())
2896 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2897 }
2898 }
2899 }
2900
2901 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2902 // Also, check for methods declared in protocols inherited by
2903 // this protocol.
2904 for (auto *PI : PD->protocols())
2905 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2906 IMPDecl, PI, IncompleteImpl, false,
2907 WarnCategoryMethodImpl);
2908 }
2909
2910 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2911 // when checking that methods in implementation match their declaration,
2912 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2913 // extension; as well as those in categories.
2914 if (!WarnCategoryMethodImpl) {
2915 for (auto *Cat : I->visible_categories())
2916 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2917 IMPDecl, Cat, IncompleteImpl,
2918 ImmediateClass && Cat->IsClassExtension(),
2919 WarnCategoryMethodImpl);
2920 } else {
2921 // Also methods in class extensions need be looked at next.
2922 for (auto *Ext : I->visible_extensions())
2923 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2924 IMPDecl, Ext, IncompleteImpl, false,
2925 WarnCategoryMethodImpl);
2926 }
2927
2928 // Check for any implementation of a methods declared in protocol.
2929 for (auto *PI : I->all_referenced_protocols())
2930 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2931 IMPDecl, PI, IncompleteImpl, false,
2932 WarnCategoryMethodImpl);
2933
2934 // FIXME. For now, we are not checking for exact match of methods
2935 // in category implementation and its primary class's super class.
2936 if (!WarnCategoryMethodImpl && I->getSuperClass())
2937 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2938 IMPDecl,
2939 I->getSuperClass(), IncompleteImpl, false);
2940 }
2941}
2942
2943/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2944/// category matches with those implemented in its primary class and
2945/// warns each time an exact match is found.
2947 ObjCCategoryImplDecl *CatIMPDecl) {
2948 // Get category's primary class.
2949 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2950 if (!CatDecl)
2951 return;
2952 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2953 if (!IDecl)
2954 return;
2955 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2956 SelectorSet InsMap, ClsMap;
2957
2958 for (const auto *I : CatIMPDecl->instance_methods()) {
2959 Selector Sel = I->getSelector();
2960 // When checking for methods implemented in the category, skip over
2961 // those declared in category class's super class. This is because
2962 // the super class must implement the method.
2963 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2964 continue;
2965 InsMap.insert(Sel);
2966 }
2967
2968 for (const auto *I : CatIMPDecl->class_methods()) {
2969 Selector Sel = I->getSelector();
2970 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2971 continue;
2972 ClsMap.insert(Sel);
2973 }
2974 if (InsMap.empty() && ClsMap.empty())
2975 return;
2976
2977 SelectorSet InsMapSeen, ClsMapSeen;
2978 bool IncompleteImpl = false;
2979 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2980 CatIMPDecl, IDecl,
2981 IncompleteImpl, false,
2982 true /*WarnCategoryMethodImpl*/);
2983}
2984
2986 ObjCContainerDecl *CDecl,
2987 bool IncompleteImpl) {
2988 SelectorSet InsMap;
2989 // Check and see if instance methods in class interface have been
2990 // implemented in the implementation class.
2991 for (const auto *I : IMPDecl->instance_methods())
2992 InsMap.insert(I->getSelector());
2993
2994 // Add the selectors for getters/setters of @dynamic properties.
2995 for (const auto *PImpl : IMPDecl->property_impls()) {
2996 // We only care about @dynamic implementations.
2997 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2998 continue;
2999
3000 const auto *P = PImpl->getPropertyDecl();
3001 if (!P) continue;
3002
3003 InsMap.insert(P->getGetterName());
3004 if (!P->getSetterName().isNull())
3005 InsMap.insert(P->getSetterName());
3006 }
3007
3008 // Check and see if properties declared in the interface have either 1)
3009 // an implementation or 2) there is a @synthesize/@dynamic implementation
3010 // of the property in the @implementation.
3011 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
3012 bool SynthesizeProperties = getLangOpts().ObjCDefaultSynthProperties &&
3014 !IDecl->isObjCRequiresPropertyDefs();
3015 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
3016 }
3017
3018 // Diagnose null-resettable synthesized setters.
3020
3021 SelectorSet ClsMap;
3022 for (const auto *I : IMPDecl->class_methods())
3023 ClsMap.insert(I->getSelector());
3024
3025 // Check for type conflict of methods declared in a class/protocol and
3026 // its implementation; if any.
3027 SelectorSet InsMapSeen, ClsMapSeen;
3028 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3029 IMPDecl, CDecl,
3030 IncompleteImpl, true);
3031
3032 // check all methods implemented in category against those declared
3033 // in its primary class.
3034 if (ObjCCategoryImplDecl *CatDecl =
3035 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3037
3038 // Check the protocol list for unimplemented methods in the @implementation
3039 // class.
3040 // Check and see if class methods in class interface have been
3041 // implemented in the implementation class.
3042
3043 LazyProtocolNameSet ExplicitImplProtocols;
3044
3045 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3046 for (auto *PI : I->all_referenced_protocols())
3047 CheckProtocolMethodDefs(SemaRef, IMPDecl, PI, IncompleteImpl, InsMap,
3048 ClsMap, I, ExplicitImplProtocols);
3049 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3050 // For extended class, unimplemented methods in its protocols will
3051 // be reported in the primary class.
3052 if (!C->IsClassExtension()) {
3053 for (auto *P : C->protocols())
3054 CheckProtocolMethodDefs(SemaRef, IMPDecl, P, IncompleteImpl, InsMap,
3055 ClsMap, CDecl, ExplicitImplProtocols);
3056 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3057 /*SynthesizeProperties=*/false);
3058 }
3059 } else
3060 llvm_unreachable("invalid ObjCContainerDecl type.");
3061}
3062
3064 SourceLocation AtClassLoc, IdentifierInfo **IdentList,
3065 SourceLocation *IdentLocs, ArrayRef<ObjCTypeParamList *> TypeParamLists,
3066 unsigned NumElts) {
3067 ASTContext &Context = getASTContext();
3068 SmallVector<Decl *, 8> DeclsInGroup;
3069 for (unsigned i = 0; i != NumElts; ++i) {
3070 // Check for another declaration kind with the same name.
3072 SemaRef.TUScope, IdentList[i], IdentLocs[i], Sema::LookupOrdinaryName,
3074 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3075 // GCC apparently allows the following idiom:
3076 //
3077 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3078 // @class XCElementToggler;
3079 //
3080 // Here we have chosen to ignore the forward class declaration
3081 // with a warning. Since this is the implied behavior.
3082 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3083 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3084 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3085 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3086 } else {
3087 // a forward class declaration matching a typedef name of a class refers
3088 // to the underlying class. Just ignore the forward class with a warning
3089 // as this will force the intended behavior which is to lookup the
3090 // typedef name.
3091 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3092 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3093 << IdentList[i];
3094 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3095 continue;
3096 }
3097 }
3098 }
3099
3100 // Create a declaration to describe this forward declaration.
3101 ObjCInterfaceDecl *PrevIDecl
3102 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3103
3104 IdentifierInfo *ClassName = IdentList[i];
3105 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3106 // A previous decl with a different name is because of
3107 // @compatibility_alias, for example:
3108 // \code
3109 // @class NewImage;
3110 // @compatibility_alias OldImage NewImage;
3111 // \endcode
3112 // A lookup for 'OldImage' will return the 'NewImage' decl.
3113 //
3114 // In such a case use the real declaration name, instead of the alias one,
3115 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3116 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3117 // has been aliased.
3118 ClassName = PrevIDecl->getIdentifier();
3119 }
3120
3121 // If this forward declaration has type parameters, compare them with the
3122 // type parameters of the previous declaration.
3123 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3124 if (PrevIDecl && TypeParams) {
3125 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3126 // Check for consistency with the previous declaration.
3128 SemaRef, PrevTypeParams, TypeParams,
3129 TypeParamListContext::ForwardDeclaration)) {
3130 TypeParams = nullptr;
3131 }
3132 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3133 // The @interface does not have type parameters. Complain.
3134 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3135 << ClassName
3136 << TypeParams->getSourceRange();
3137 Diag(Def->getLocation(), diag::note_defined_here)
3138 << ClassName;
3139
3140 TypeParams = nullptr;
3141 }
3142 }
3143
3145 Context, SemaRef.CurContext, AtClassLoc, ClassName, TypeParams,
3146 PrevIDecl, IdentLocs[i]);
3147 IDecl->setAtEndRange(IdentLocs[i]);
3148
3149 if (PrevIDecl)
3150 SemaRef.mergeDeclAttributes(IDecl, PrevIDecl);
3151
3153 CheckObjCDeclScope(IDecl);
3154 DeclsInGroup.push_back(IDecl);
3155 }
3156
3157 return SemaRef.BuildDeclaratorGroup(DeclsInGroup);
3158}
3159
3160static bool tryMatchRecordTypes(ASTContext &Context,
3162 const Type *left, const Type *right);
3163
3164static bool matchTypes(ASTContext &Context,
3165 SemaObjC::MethodMatchStrategy strategy, QualType leftQT,
3166 QualType rightQT) {
3167 const Type *left =
3169 const Type *right =
3170 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3171
3172 if (left == right) return true;
3173
3174 // If we're doing a strict match, the types have to match exactly.
3175 if (strategy == SemaObjC::MMS_strict)
3176 return false;
3177
3178 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3179
3180 // Otherwise, use this absurdly complicated algorithm to try to
3181 // validate the basic, low-level compatibility of the two types.
3182
3183 // As a minimum, require the sizes and alignments to match.
3184 TypeInfo LeftTI = Context.getTypeInfo(left);
3185 TypeInfo RightTI = Context.getTypeInfo(right);
3186 if (LeftTI.Width != RightTI.Width)
3187 return false;
3188
3189 if (LeftTI.Align != RightTI.Align)
3190 return false;
3191
3192 // Consider all the kinds of non-dependent canonical types:
3193 // - functions and arrays aren't possible as return and parameter types
3194
3195 // - vector types of equal size can be arbitrarily mixed
3196 if (isa<VectorType>(left)) return isa<VectorType>(right);
3197 if (isa<VectorType>(right)) return false;
3198
3199 // - references should only match references of identical type
3200 // - structs, unions, and Objective-C objects must match more-or-less
3201 // exactly
3202 // - everything else should be a scalar
3203 if (!left->isScalarType() || !right->isScalarType())
3204 return tryMatchRecordTypes(Context, strategy, left, right);
3205
3206 // Make scalars agree in kind, except count bools as chars, and group
3207 // all non-member pointers together.
3208 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3209 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3210 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3211 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3212 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3214 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3216
3217 // Note that data member pointers and function member pointers don't
3218 // intermix because of the size differences.
3219
3220 return (leftSK == rightSK);
3221}
3222
3223static bool tryMatchRecordTypes(ASTContext &Context,
3225 const Type *lt, const Type *rt) {
3226 assert(lt && rt && lt != rt);
3227
3228 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3229 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3230 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3231
3232 // Require union-hood to match.
3233 if (left->isUnion() != right->isUnion()) return false;
3234
3235 // Require an exact match if either is non-POD.
3236 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3237 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3238 return false;
3239
3240 // Require size and alignment to match.
3241 TypeInfo LeftTI = Context.getTypeInfo(lt);
3242 TypeInfo RightTI = Context.getTypeInfo(rt);
3243 if (LeftTI.Width != RightTI.Width)
3244 return false;
3245
3246 if (LeftTI.Align != RightTI.Align)
3247 return false;
3248
3249 // Require fields to match.
3250 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3251 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3252 for (; li != le && ri != re; ++li, ++ri) {
3253 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3254 return false;
3255 }
3256 return (li == le && ri == re);
3257}
3258
3259/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3260/// returns true, or false, accordingly.
3261/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3263 const ObjCMethodDecl *right,
3264 MethodMatchStrategy strategy) {
3265 ASTContext &Context = getASTContext();
3266 if (!matchTypes(Context, strategy, left->getReturnType(),
3267 right->getReturnType()))
3268 return false;
3269
3270 // If either is hidden, it is not considered to match.
3271 if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible())
3272 return false;
3273
3274 if (left->isDirectMethod() != right->isDirectMethod())
3275 return false;
3276
3277 if (getLangOpts().ObjCAutoRefCount &&
3278 (left->hasAttr<NSReturnsRetainedAttr>()
3279 != right->hasAttr<NSReturnsRetainedAttr>() ||
3280 left->hasAttr<NSConsumesSelfAttr>()
3281 != right->hasAttr<NSConsumesSelfAttr>()))
3282 return false;
3283
3285 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3286 re = right->param_end();
3287
3288 for (; li != le && ri != re; ++li, ++ri) {
3289 assert(ri != right->param_end() && "Param mismatch");
3290 const ParmVarDecl *lparm = *li, *rparm = *ri;
3291
3292 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3293 return false;
3294
3295 if (getLangOpts().ObjCAutoRefCount &&
3296 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3297 return false;
3298 }
3299 return true;
3300}
3301
3303 ObjCMethodDecl *MethodInList) {
3304 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3305 auto *MethodInListProtocol =
3306 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3307 // If this method belongs to a protocol but the method in list does not, or
3308 // vice versa, we say the context is not the same.
3309 if ((MethodProtocol && !MethodInListProtocol) ||
3310 (!MethodProtocol && MethodInListProtocol))
3311 return false;
3312
3313 if (MethodProtocol && MethodInListProtocol)
3314 return true;
3315
3316 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3317 ObjCInterfaceDecl *MethodInListInterface =
3318 MethodInList->getClassInterface();
3319 return MethodInterface == MethodInListInterface;
3320}
3321
3323 ObjCMethodDecl *Method) {
3324 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3325 // inside categories.
3326 if (ObjCCategoryDecl *CD =
3327 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3328 if (!CD->IsClassExtension() && List->getBits() < 2)
3329 List->setBits(List->getBits() + 1);
3330
3331 // If the list is empty, make it a singleton list.
3332 if (List->getMethod() == nullptr) {
3333 List->setMethod(Method);
3334 List->setNext(nullptr);
3335 return;
3336 }
3337
3338 // We've seen a method with this name, see if we have already seen this type
3339 // signature.
3340 ObjCMethodList *Previous = List;
3341 ObjCMethodList *ListWithSameDeclaration = nullptr;
3342 for (; List; Previous = List, List = List->getNext()) {
3343 // If we are building a module, keep all of the methods.
3344 if (getLangOpts().isCompilingModule())
3345 continue;
3346
3347 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3348 List->getMethod());
3349 // Looking for method with a type bound requires the correct context exists.
3350 // We need to insert a method into the list if the context is different.
3351 // If the method's declaration matches the list
3352 // a> the method belongs to a different context: we need to insert it, in
3353 // order to emit the availability message, we need to prioritize over
3354 // availability among the methods with the same declaration.
3355 // b> the method belongs to the same context: there is no need to insert a
3356 // new entry.
3357 // If the method's declaration does not match the list, we insert it to the
3358 // end.
3359 if (!SameDeclaration ||
3360 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3361 // Even if two method types do not match, we would like to say
3362 // there is more than one declaration so unavailability/deprecated
3363 // warning is not too noisy.
3364 if (!Method->isDefined())
3365 List->setHasMoreThanOneDecl(true);
3366
3367 // For methods with the same declaration, the one that is deprecated
3368 // should be put in the front for better diagnostics.
3369 if (Method->isDeprecated() && SameDeclaration &&
3370 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3371 ListWithSameDeclaration = List;
3372
3373 if (Method->isUnavailable() && SameDeclaration &&
3374 !ListWithSameDeclaration &&
3375 List->getMethod()->getAvailability() < AR_Deprecated)
3376 ListWithSameDeclaration = List;
3377 continue;
3378 }
3379
3380 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3381
3382 // Propagate the 'defined' bit.
3383 if (Method->isDefined())
3384 PrevObjCMethod->setDefined(true);
3385 else {
3386 // Objective-C doesn't allow an @interface for a class after its
3387 // @implementation. So if Method is not defined and there already is
3388 // an entry for this type signature, Method has to be for a different
3389 // class than PrevObjCMethod.
3390 List->setHasMoreThanOneDecl(true);
3391 }
3392
3393 // If a method is deprecated, push it in the global pool.
3394 // This is used for better diagnostics.
3395 if (Method->isDeprecated()) {
3396 if (!PrevObjCMethod->isDeprecated())
3397 List->setMethod(Method);
3398 }
3399 // If the new method is unavailable, push it into global pool
3400 // unless previous one is deprecated.
3401 if (Method->isUnavailable()) {
3402 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3403 List->setMethod(Method);
3404 }
3405
3406 return;
3407 }
3408
3409 // We have a new signature for an existing method - add it.
3410 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3412
3413 // We insert it right before ListWithSameDeclaration.
3414 if (ListWithSameDeclaration) {
3415 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3416 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3417 ListWithSameDeclaration->setMethod(Method);
3418 ListWithSameDeclaration->setNext(List);
3419 return;
3420 }
3421
3422 Previous->setNext(new (Mem) ObjCMethodList(Method));
3423}
3424
3425/// Read the contents of the method pool for a given selector from
3426/// external storage.
3428 assert(SemaRef.ExternalSource && "We need an external AST source");
3429 SemaRef.ExternalSource->ReadMethodPool(Sel);
3430}
3431
3434 return;
3435 SemaRef.ExternalSource->updateOutOfDateSelector(Sel);
3436}
3437
3438void SemaObjC::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3439 bool instance) {
3440 // Ignore methods of invalid containers.
3441 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3442 return;
3443
3445 ReadMethodPool(Method->getSelector());
3446
3448 if (Pos == MethodPool.end())
3449 Pos = MethodPool
3450 .insert(std::make_pair(Method->getSelector(),
3452 .first;
3453
3454 Method->setDefined(impl);
3455
3456 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3457 addMethodToGlobalList(&Entry, Method);
3458}
3459
3460/// Determines if this is an "acceptable" loose mismatch in the global
3461/// method pool. This exists mostly as a hack to get around certain
3462/// global mismatches which we can't afford to make warnings / errors.
3463/// Really, what we want is a way to take a method out of the global
3464/// method pool.
3466 ObjCMethodDecl *other) {
3467 if (!chosen->isInstanceMethod())
3468 return false;
3469
3470 if (chosen->isDirectMethod() != other->isDirectMethod())
3471 return false;
3472
3473 Selector sel = chosen->getSelector();
3474 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3475 return false;
3476
3477 // Don't complain about mismatches for -length if the method we
3478 // chose has an integral result type.
3479 return (chosen->getReturnType()->isIntegerType());
3480}
3481
3482/// Return true if the given method is wthin the type bound.
3484 const ObjCObjectType *TypeBound) {
3485 if (!TypeBound)
3486 return true;
3487
3488 if (TypeBound->isObjCId())
3489 // FIXME: should we handle the case of bounding to id<A, B> differently?
3490 return true;
3491
3492 auto *BoundInterface = TypeBound->getInterface();
3493 assert(BoundInterface && "unexpected object type!");
3494
3495 // Check if the Method belongs to a protocol. We should allow any method
3496 // defined in any protocol, because any subclass could adopt the protocol.
3497 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3498 if (MethodProtocol) {
3499 return true;
3500 }
3501
3502 // If the Method belongs to a class, check if it belongs to the class
3503 // hierarchy of the class bound.
3504 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3505 // We allow methods declared within classes that are part of the hierarchy
3506 // of the class bound (superclass of, subclass of, or the same as the class
3507 // bound).
3508 return MethodInterface == BoundInterface ||
3509 MethodInterface->isSuperClassOf(BoundInterface) ||
3510 BoundInterface->isSuperClassOf(MethodInterface);
3511 }
3512 llvm_unreachable("unknown method context");
3513}
3514
3515/// We first select the type of the method: Instance or Factory, then collect
3516/// all methods with that type.
3519 bool InstanceFirst, bool CheckTheOther, const ObjCObjectType *TypeBound) {
3521 ReadMethodPool(Sel);
3522
3524 if (Pos == MethodPool.end())
3525 return false;
3526
3527 // Gather the non-hidden methods.
3528 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3529 Pos->second.second;
3530 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3531 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3532 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3533 Methods.push_back(M->getMethod());
3534 }
3535
3536 // Return if we find any method with the desired kind.
3537 if (!Methods.empty())
3538 return Methods.size() > 1;
3539
3540 if (!CheckTheOther)
3541 return false;
3542
3543 // Gather the other kind.
3544 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3545 Pos->second.first;
3546 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3547 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3548 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3549 Methods.push_back(M->getMethod());
3550 }
3551
3552 return Methods.size() > 1;
3553}
3554
3556 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3557 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3558 // Diagnose finding more than one method in global pool.
3559 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3560 FilteredMethods.push_back(BestMethod);
3561
3562 for (auto *M : Methods)
3563 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3564 FilteredMethods.push_back(M);
3565
3566 if (FilteredMethods.size() > 1)
3567 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3568 receiverIdOrClass);
3569
3571 // Test for no method in the pool which should not trigger any warning by
3572 // caller.
3573 if (Pos == MethodPool.end())
3574 return true;
3575 ObjCMethodList &MethList =
3576 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3577 return MethList.hasMoreThanOneDecl();
3578}
3579
3580ObjCMethodDecl *SemaObjC::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3581 bool receiverIdOrClass,
3582 bool instance) {
3584 ReadMethodPool(Sel);
3585
3587 if (Pos == MethodPool.end())
3588 return nullptr;
3589
3590 // Gather the non-hidden methods.
3591 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3593 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3594 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible())
3595 return M->getMethod();
3596 }
3597 return nullptr;
3598}
3599
3602 bool receiverIdOrClass) {
3603 // We found multiple methods, so we may have to complain.
3604 bool issueDiagnostic = false, issueError = false;
3605
3606 // We support a warning which complains about *any* difference in
3607 // method signature.
3608 bool strictSelectorMatch =
3609 receiverIdOrClass &&
3610 !getDiagnostics().isIgnored(diag::warn_strict_multiple_method_decl,
3611 R.getBegin());
3612 if (strictSelectorMatch) {
3613 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3614 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3615 issueDiagnostic = true;
3616 break;
3617 }
3618 }
3619 }
3620
3621 // If we didn't see any strict differences, we won't see any loose
3622 // differences. In ARC, however, we also need to check for loose
3623 // mismatches, because most of them are errors.
3624 if (!strictSelectorMatch ||
3625 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3626 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3627 // This checks if the methods differ in type mismatch.
3628 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3629 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3630 issueDiagnostic = true;
3631 if (getLangOpts().ObjCAutoRefCount)
3632 issueError = true;
3633 break;
3634 }
3635 }
3636
3637 if (issueDiagnostic) {
3638 if (issueError)
3639 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3640 else if (strictSelectorMatch)
3641 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3642 else
3643 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3644
3645 Diag(Methods[0]->getBeginLoc(),
3646 issueError ? diag::note_possibility : diag::note_using)
3647 << Methods[0]->getSourceRange();
3648 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3649 Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3650 << Methods[I]->getSourceRange();
3651 }
3652 }
3653}
3654
3657 if (Pos == MethodPool.end())
3658 return nullptr;
3659
3660 GlobalMethodPool::Lists &Methods = Pos->second;
3661 for (const ObjCMethodList *Method = &Methods.first; Method;
3662 Method = Method->getNext())
3663 if (Method->getMethod() &&
3664 (Method->getMethod()->isDefined() ||
3665 Method->getMethod()->isPropertyAccessor()))
3666 return Method->getMethod();
3667
3668 for (const ObjCMethodList *Method = &Methods.second; Method;
3669 Method = Method->getNext())
3670 if (Method->getMethod() &&
3671 (Method->getMethod()->isDefined() ||
3672 Method->getMethod()->isPropertyAccessor()))
3673 return Method->getMethod();
3674 return nullptr;
3675}
3676
3677static void
3680 StringRef Typo, const ObjCMethodDecl * Method) {
3681 const unsigned MaxEditDistance = 1;
3682 unsigned BestEditDistance = MaxEditDistance + 1;
3683 std::string MethodName = Method->getSelector().getAsString();
3684
3685 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3686 if (MinPossibleEditDistance > 0 &&
3687 Typo.size() / MinPossibleEditDistance < 1)
3688 return;
3689 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3690 if (EditDistance > MaxEditDistance)
3691 return;
3692 if (EditDistance == BestEditDistance)
3693 BestMethod.push_back(Method);
3694 else if (EditDistance < BestEditDistance) {
3695 BestMethod.clear();
3696 BestMethod.push_back(Method);
3697 }
3698}
3699
3701 QualType ObjectType) {
3702 if (ObjectType.isNull())
3703 return true;
3704 if (S.ObjC().LookupMethodInObjectType(Sel, ObjectType,
3705 true /*Instance method*/))
3706 return true;
3707 return S.ObjC().LookupMethodInObjectType(Sel, ObjectType,
3708 false /*Class method*/) != nullptr;
3709}
3710
3711const ObjCMethodDecl *
3713 unsigned NumArgs = Sel.getNumArgs();
3715 bool ObjectIsId = true, ObjectIsClass = true;
3716 if (ObjectType.isNull())
3717 ObjectIsId = ObjectIsClass = false;
3718 else if (!ObjectType->isObjCObjectPointerType())
3719 return nullptr;
3720 else if (const ObjCObjectPointerType *ObjCPtr =
3721 ObjectType->getAsObjCInterfacePointerType()) {
3722 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3723 ObjectIsId = ObjectIsClass = false;
3724 }
3725 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3726 ObjectIsClass = false;
3727 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3728 ObjectIsId = false;
3729 else
3730 return nullptr;
3731
3733 e = MethodPool.end(); b != e; b++) {
3734 // instance methods
3735 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3736 if (M->getMethod() &&
3737 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3738 (M->getMethod()->getSelector() != Sel)) {
3739 if (ObjectIsId)
3740 Methods.push_back(M->getMethod());
3741 else if (!ObjectIsClass &&
3743 SemaRef, M->getMethod()->getSelector(), ObjectType))
3744 Methods.push_back(M->getMethod());
3745 }
3746 // class methods
3747 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3748 if (M->getMethod() &&
3749 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3750 (M->getMethod()->getSelector() != Sel)) {
3751 if (ObjectIsClass)
3752 Methods.push_back(M->getMethod());
3753 else if (!ObjectIsId &&
3755 SemaRef, M->getMethod()->getSelector(), ObjectType))
3756 Methods.push_back(M->getMethod());
3757 }
3758 }
3759
3761 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3762 HelperSelectorsForTypoCorrection(SelectedMethods,
3763 Sel.getAsString(), Methods[i]);
3764 }
3765 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3766}
3767
3768/// DiagnoseDuplicateIvars -
3769/// Check for duplicate ivars in the entire class at the start of
3770/// \@implementation. This becomes necessary because class extension can
3771/// add ivars to a class in random order which will not be known until
3772/// class's \@implementation is seen.
3774 ObjCInterfaceDecl *SID) {
3775 for (auto *Ivar : ID->ivars()) {
3776 if (Ivar->isInvalidDecl())
3777 continue;
3778 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3779 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3780 if (prevIvar) {
3781 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3782 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3783 Ivar->setInvalidDecl();
3784 }
3785 }
3786 }
3787}
3788
3789/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3791 if (S.getLangOpts().ObjCWeak) return;
3792
3793 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3794 ivar; ivar = ivar->getNextIvar()) {
3795 if (ivar->isInvalidDecl()) continue;
3796 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3797 if (S.getLangOpts().ObjCWeakRuntime) {
3798 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3799 } else {
3800 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3801 }
3802 }
3803 }
3804}
3805
3806/// Diagnose attempts to use flexible array member with retainable object type.
3808 ObjCInterfaceDecl *ID) {
3809 if (!S.getLangOpts().ObjCAutoRefCount)
3810 return;
3811
3812 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3813 ivar = ivar->getNextIvar()) {
3814 if (ivar->isInvalidDecl())
3815 continue;
3816 QualType IvarTy = ivar->getType();
3817 if (IvarTy->isIncompleteArrayType() &&
3819 IvarTy->isObjCLifetimeType()) {
3820 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3821 ivar->setInvalidDecl();
3822 }
3823 }
3824}
3825
3827 switch (SemaRef.CurContext->getDeclKind()) {
3828 case Decl::ObjCInterface:
3830 case Decl::ObjCProtocol:
3832 case Decl::ObjCCategory:
3833 if (cast<ObjCCategoryDecl>(SemaRef.CurContext)->IsClassExtension())
3836 case Decl::ObjCImplementation:
3838 case Decl::ObjCCategoryImpl:
3840
3841 default:
3842 return SemaObjC::OCK_None;
3843 }
3844}
3845
3847 if (T->isIncompleteArrayType())
3848 return true;
3849 const auto *RecordTy = T->getAs<RecordType>();
3850 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3851}
3852
3854 ObjCInterfaceDecl *IntfDecl = nullptr;
3855 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3857 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3858 Ivars = IntfDecl->ivars();
3859 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3860 IntfDecl = ImplDecl->getClassInterface();
3861 Ivars = ImplDecl->ivars();
3862 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3863 if (CategoryDecl->IsClassExtension()) {
3864 IntfDecl = CategoryDecl->getClassInterface();
3865 Ivars = CategoryDecl->ivars();
3866 }
3867 }
3868
3869 // Check if variable sized ivar is in interface and visible to subclasses.
3870 if (!isa<ObjCInterfaceDecl>(OCD)) {
3871 for (auto *ivar : Ivars) {
3872 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3873 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3874 << ivar->getDeclName() << ivar->getType();
3875 }
3876 }
3877 }
3878
3879 // Subsequent checks require interface decl.
3880 if (!IntfDecl)
3881 return;
3882
3883 // Check if variable sized ivar is followed by another ivar.
3884 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3885 ivar = ivar->getNextIvar()) {
3886 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3887 continue;
3888 QualType IvarTy = ivar->getType();
3889 bool IsInvalidIvar = false;
3890 if (IvarTy->isIncompleteArrayType()) {
3891 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3892 << ivar->getDeclName() << IvarTy
3893 << llvm::to_underlying(TagTypeKind::Class); // Use "class" for Obj-C.
3894 IsInvalidIvar = true;
3895 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3896 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3897 S.Diag(ivar->getLocation(),
3898 diag::err_objc_variable_sized_type_not_at_end)
3899 << ivar->getDeclName() << IvarTy;
3900 IsInvalidIvar = true;
3901 }
3902 }
3903 if (IsInvalidIvar) {
3904 S.Diag(ivar->getNextIvar()->getLocation(),
3905 diag::note_next_ivar_declaration)
3906 << ivar->getNextIvar()->getSynthesize();
3907 ivar->setInvalidDecl();
3908 }
3909 }
3910
3911 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3912 // Perform the check only if OCD is the first container to declare ivars to
3913 // avoid multiple warnings for the same ivar.
3914 ObjCIvarDecl *FirstIvar =
3915 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3916 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3917 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3918 while (SuperClass && SuperClass->ivar_empty())
3919 SuperClass = SuperClass->getSuperClass();
3920 if (SuperClass) {
3921 auto IvarIter = SuperClass->ivar_begin();
3922 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3923 const ObjCIvarDecl *LastIvar = *IvarIter;
3924 if (IsVariableSizedType(LastIvar->getType())) {
3925 S.Diag(FirstIvar->getLocation(),
3926 diag::warn_superclass_variable_sized_type_not_at_end)
3927 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3928 << LastIvar->getType() << SuperClass->getDeclName();
3929 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3930 << LastIvar->getDeclName();
3931 }
3932 }
3933 }
3934}
3935
3937 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
3938
3940 Sema &S, ObjCCategoryDecl *CDecl,
3941 const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
3942 for (auto *PI : Protocols)
3944}
3945
3947 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
3948 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
3949 PDecl = PDecl->getDefinition();
3950
3952 const auto *IDecl = CDecl->getClassInterface();
3953 for (auto *MD : PDecl->methods()) {
3954 if (!MD->isPropertyAccessor()) {
3955 if (const auto *CMD =
3956 IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
3957 if (CMD->isDirectMethod())
3958 DirectMembers.push_back(CMD);
3959 }
3960 }
3961 }
3962 for (auto *PD : PDecl->properties()) {
3963 if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
3964 PD->getIdentifier(),
3965 PD->isClassProperty()
3968 if (CPD->isDirectProperty())
3969 DirectMembers.push_back(CPD);
3970 }
3971 }
3972 if (!DirectMembers.empty()) {
3973 S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
3974 << CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
3975 for (const auto *MD : DirectMembers)
3976 S.Diag(MD->getLocation(), diag::note_direct_member_here);
3977 return;
3978 }
3979
3980 // Check on this protocols's referenced protocols, recursively.
3982 PDecl->protocols());
3983}
3984
3985// Note: For class/category implementations, allMethods is always null.
3987 ArrayRef<Decl *> allMethods,
3988 ArrayRef<DeclGroupPtrTy> allTUVars) {
3989 ASTContext &Context = getASTContext();
3991 return nullptr;
3992
3993 assert(AtEnd.isValid() && "Invalid location for '@end'");
3994
3995 auto *OCD = cast<ObjCContainerDecl>(SemaRef.CurContext);
3996 Decl *ClassDecl = OCD;
3997
3998 bool isInterfaceDeclKind =
3999 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
4000 || isa<ObjCProtocolDecl>(ClassDecl);
4001 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
4002
4003 // Make synthesized accessor stub functions visible.
4004 // ActOnPropertyImplDecl() creates them as not visible in case
4005 // they are overridden by an explicit method that is encountered
4006 // later.
4007 if (auto *OID = dyn_cast<ObjCImplementationDecl>(SemaRef.CurContext)) {
4008 for (auto *PropImpl : OID->property_impls()) {
4009 if (auto *Getter = PropImpl->getGetterMethodDecl())
4010 if (Getter->isSynthesizedAccessorStub())
4011 OID->addDecl(Getter);
4012 if (auto *Setter = PropImpl->getSetterMethodDecl())
4013 if (Setter->isSynthesizedAccessorStub())
4014 OID->addDecl(Setter);
4015 }
4016 }
4017
4018 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
4019 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
4020 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
4021
4022 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
4023 ObjCMethodDecl *Method =
4024 cast_or_null<ObjCMethodDecl>(allMethods[i]);
4025
4026 if (!Method) continue; // Already issued a diagnostic.
4027 if (Method->isInstanceMethod()) {
4028 /// Check for instance method of the same name with incompatible types
4029 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
4030 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4031 : false;
4032 if ((isInterfaceDeclKind && PrevMethod && !match)
4033 || (checkIdenticalMethods && match)) {
4034 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4035 << Method->getDeclName();
4036 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4037 Method->setInvalidDecl();
4038 } else {
4039 if (PrevMethod) {
4040 Method->setAsRedeclaration(PrevMethod);
4041 if (!Context.getSourceManager().isInSystemHeader(
4042 Method->getLocation()))
4043 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4044 << Method->getDeclName();
4045 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4046 }
4047 InsMap[Method->getSelector()] = Method;
4048 /// The following allows us to typecheck messages to "id".
4050 }
4051 } else {
4052 /// Check for class method of the same name with incompatible types
4053 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
4054 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4055 : false;
4056 if ((isInterfaceDeclKind && PrevMethod && !match)
4057 || (checkIdenticalMethods && match)) {
4058 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4059 << Method->getDeclName();
4060 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4061 Method->setInvalidDecl();
4062 } else {
4063 if (PrevMethod) {
4064 Method->setAsRedeclaration(PrevMethod);
4065 if (!Context.getSourceManager().isInSystemHeader(
4066 Method->getLocation()))
4067 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4068 << Method->getDeclName();
4069 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4070 }
4071 ClsMap[Method->getSelector()] = Method;
4073 }
4074 }
4075 }
4076 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
4077 // Nothing to do here.
4078 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
4079 // Categories are used to extend the class by declaring new methods.
4080 // By the same token, they are also used to add new properties. No
4081 // need to compare the added property to those in the class.
4082
4083 if (C->IsClassExtension()) {
4084 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
4086 }
4087
4089 C->protocols());
4090 }
4091 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
4092 if (CDecl->getIdentifier())
4093 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
4094 // user-defined setter/getter. It also synthesizes setter/getter methods
4095 // and adds them to the DeclContext and global method pools.
4096 for (auto *I : CDecl->properties())
4098 CDecl->setAtEndRange(AtEnd);
4099 }
4100 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
4101 IC->setAtEndRange(AtEnd);
4102 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
4103 // Any property declared in a class extension might have user
4104 // declared setter or getter in current class extension or one
4105 // of the other class extensions. Mark them as synthesized as
4106 // property will be synthesized when property with same name is
4107 // seen in the @implementation.
4108 for (const auto *Ext : IDecl->visible_extensions()) {
4109 for (const auto *Property : Ext->instance_properties()) {
4110 // Skip over properties declared @dynamic
4111 if (const ObjCPropertyImplDecl *PIDecl
4112 = IC->FindPropertyImplDecl(Property->getIdentifier(),
4113 Property->getQueryKind()))
4114 if (PIDecl->getPropertyImplementation()
4116 continue;
4117
4118 for (const auto *Ext : IDecl->visible_extensions()) {
4119 if (ObjCMethodDecl *GetterMethod =
4120 Ext->getInstanceMethod(Property->getGetterName()))
4121 GetterMethod->setPropertyAccessor(true);
4122 if (!Property->isReadOnly())
4123 if (ObjCMethodDecl *SetterMethod
4124 = Ext->getInstanceMethod(Property->getSetterName()))
4125 SetterMethod->setPropertyAccessor(true);
4126 }
4127 }
4128 }
4129 ImplMethodsVsClassMethods(S, IC, IDecl);
4133 if (IDecl->hasDesignatedInitializers())
4137
4138 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4139 if (IDecl->getSuperClass() == nullptr) {
4140 // This class has no superclass, so check that it has been marked with
4141 // __attribute((objc_root_class)).
4142 if (!HasRootClassAttr) {
4143 SourceLocation DeclLoc(IDecl->getLocation());
4144 SourceLocation SuperClassLoc(SemaRef.getLocForEndOfToken(DeclLoc));
4145 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4146 << IDecl->getIdentifier();
4147 // See if NSObject is in the current scope, and if it is, suggest
4148 // adding " : NSObject " to the class declaration.
4151 DeclLoc, Sema::LookupOrdinaryName);
4152 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4153 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4154 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4155 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4156 } else {
4157 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4158 }
4159 }
4160 } else if (HasRootClassAttr) {
4161 // Complain that only root classes may have this attribute.
4162 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4163 }
4164
4165 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4166 // An interface can subclass another interface with a
4167 // objc_subclassing_restricted attribute when it has that attribute as
4168 // well (because of interfaces imported from Swift). Therefore we have
4169 // to check if we can subclass in the implementation as well.
4170 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4171 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4172 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4173 Diag(Super->getLocation(), diag::note_class_declared);
4174 }
4175 }
4176
4177 if (IDecl->hasAttr<ObjCClassStubAttr>())
4178 Diag(IC->getLocation(), diag::err_implementation_of_class_stub);
4179
4181 while (IDecl->getSuperClass()) {
4182 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4183 IDecl = IDecl->getSuperClass();
4184 }
4185 }
4186 }
4188 } else if (ObjCCategoryImplDecl* CatImplClass =
4189 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4190 CatImplClass->setAtEndRange(AtEnd);
4191
4192 // Find category interface decl and then check that all methods declared
4193 // in this interface are implemented in the category @implementation.
4194 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4195 if (ObjCCategoryDecl *Cat
4196 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4197 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4198 }
4199 }
4200 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4201 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4202 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4203 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4204 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4205 Diag(Super->getLocation(), diag::note_class_declared);
4206 }
4207 }
4208
4209 if (IntfDecl->hasAttr<ObjCClassStubAttr>() &&
4210 !IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>())
4211 Diag(IntfDecl->getLocation(), diag::err_class_stub_subclassing_mismatch);
4212 }
4214 if (isInterfaceDeclKind) {
4215 // Reject invalid vardecls.
4216 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4217 DeclGroupRef DG = allTUVars[i].get();
4218 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4219 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4220 if (!VDecl->hasExternalStorage())
4221 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4222 }
4223 }
4224 }
4226
4227 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4228 DeclGroupRef DG = allTUVars[i].get();
4229 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4230 (*I)->setTopLevelDeclInObjCContainer();
4232 }
4233
4234 SemaRef.ActOnDocumentableDecl(ClassDecl);
4235 return ClassDecl;
4236}
4237
4238/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4239/// objective-c's type qualifier from the parser version of the same info.
4242 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4243}
4244
4245/// Check whether the declared result type of the given Objective-C
4246/// method declaration is compatible with the method's class.
4247///
4250 ObjCInterfaceDecl *CurrentClass) {
4251 QualType ResultType = Method->getReturnType();
4252
4253 // If an Objective-C method inherits its related result type, then its
4254 // declared result type must be compatible with its own class type. The
4255 // declared result type is compatible if:
4256 if (const ObjCObjectPointerType *ResultObjectType
4257 = ResultType->getAs<ObjCObjectPointerType>()) {
4258 // - it is id or qualified id, or
4259 if (ResultObjectType->isObjCIdType() ||
4260 ResultObjectType->isObjCQualifiedIdType())
4262
4263 if (CurrentClass) {
4264 if (ObjCInterfaceDecl *ResultClass
4265 = ResultObjectType->getInterfaceDecl()) {
4266 // - it is the same as the method's class type, or
4267 if (declaresSameEntity(CurrentClass, ResultClass))
4269
4270 // - it is a superclass of the method's class type
4271 if (ResultClass->isSuperClassOf(CurrentClass))
4273 }
4274 } else {
4275 // Any Objective-C pointer type might be acceptable for a protocol
4276 // method; we just don't know.
4277 return SemaObjC::RTC_Unknown;
4278 }
4279 }
4280
4282}
4283
4284namespace {
4285/// A helper class for searching for methods which a particular method
4286/// overrides.
4287class OverrideSearch {
4288public:
4289 const ObjCMethodDecl *Method;
4291 bool Recursive;
4292
4293public:
4294 OverrideSearch(Sema &S, const ObjCMethodDecl *method) : Method(method) {
4295 Selector selector = method->getSelector();
4296
4297 // Bypass this search if we've never seen an instance/class method
4298 // with this selector before.
4300 S.ObjC().MethodPool.find(selector);
4301 if (it == S.ObjC().MethodPool.end()) {
4302 if (!S.getExternalSource()) return;
4303 S.ObjC().ReadMethodPool(selector);
4304
4305 it = S.ObjC().MethodPool.find(selector);
4306 if (it == S.ObjC().MethodPool.end())
4307 return;
4308 }
4309 const ObjCMethodList &list =
4310 method->isInstanceMethod() ? it->second.first : it->second.second;
4311 if (!list.getMethod()) return;
4312
4313 const ObjCContainerDecl *container
4314 = cast<ObjCContainerDecl>(method->getDeclContext());
4315
4316 // Prevent the search from reaching this container again. This is
4317 // important with categories, which override methods from the
4318 // interface and each other.
4319 if (const ObjCCategoryDecl *Category =
4320 dyn_cast<ObjCCategoryDecl>(container)) {
4321 searchFromContainer(container);
4322 if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4323 searchFromContainer(Interface);
4324 } else {
4325 searchFromContainer(container);
4326 }
4327 }
4328
4329 typedef decltype(Overridden)::iterator iterator;
4330 iterator begin() const { return Overridden.begin(); }
4331 iterator end() const { return Overridden.end(); }
4332
4333private:
4334 void searchFromContainer(const ObjCContainerDecl *container) {
4335 if (container->isInvalidDecl()) return;
4336
4337 switch (container->getDeclKind()) {
4338#define OBJCCONTAINER(type, base) \
4339 case Decl::type: \
4340 searchFrom(cast<type##Decl>(container)); \
4341 break;
4342#define ABSTRACT_DECL(expansion)
4343#define DECL(type, base) \
4344 case Decl::type:
4345#include "clang/AST/DeclNodes.inc"
4346 llvm_unreachable("not an ObjC container!");
4347 }
4348 }
4349
4350 void searchFrom(const ObjCProtocolDecl *protocol) {
4351 if (!protocol->hasDefinition())
4352 return;
4353
4354 // A method in a protocol declaration overrides declarations from
4355 // referenced ("parent") protocols.
4356 search(protocol->getReferencedProtocols());
4357 }
4358
4359 void searchFrom(const ObjCCategoryDecl *category) {
4360 // A method in a category declaration overrides declarations from
4361 // the main class and from protocols the category references.
4362 // The main class is handled in the constructor.
4363 search(category->getReferencedProtocols());
4364 }
4365
4366 void searchFrom(const ObjCCategoryImplDecl *impl) {
4367 // A method in a category definition that has a category
4368 // declaration overrides declarations from the category
4369 // declaration.
4370 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4371 search(category);
4372 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4373 search(Interface);
4374
4375 // Otherwise it overrides declarations from the class.
4376 } else if (const auto *Interface = impl->getClassInterface()) {
4377 search(Interface);
4378 }
4379 }
4380
4381 void searchFrom(const ObjCInterfaceDecl *iface) {
4382 // A method in a class declaration overrides declarations from
4383 if (!iface->hasDefinition())
4384 return;
4385
4386 // - categories,
4387 for (auto *Cat : iface->known_categories())
4388 search(Cat);
4389
4390 // - the super class, and
4391 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4392 search(super);
4393
4394 // - any referenced protocols.
4395 search(iface->getReferencedProtocols());
4396 }
4397
4398 void searchFrom(const ObjCImplementationDecl *impl) {
4399 // A method in a class implementation overrides declarations from
4400 // the class interface.
4401 if (const auto *Interface = impl->getClassInterface())
4402 search(Interface);
4403 }
4404
4405 void search(const ObjCProtocolList &protocols) {
4406 for (const auto *Proto : protocols)
4407 search(Proto);
4408 }
4409
4410 void search(const ObjCContainerDecl *container) {
4411 // Check for a method in this container which matches this selector.
4412 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4413 Method->isInstanceMethod(),
4414 /*AllowHidden=*/true);
4415
4416 // If we find one, record it and bail out.
4417 if (meth) {
4418 Overridden.insert(meth);
4419 return;
4420 }
4421
4422 // Otherwise, search for methods that a hypothetical method here
4423 // would have overridden.
4424
4425 // Note that we're now in a recursive case.
4426 Recursive = true;
4427
4428 searchFromContainer(container);
4429 }
4430};
4431} // end anonymous namespace
4432
4434 ObjCMethodDecl *overridden) {
4435 if (overridden->isDirectMethod()) {
4436 const auto *attr = overridden->getAttr<ObjCDirectAttr>();
4437 Diag(method->getLocation(), diag::err_objc_override_direct_method);
4438 Diag(attr->getLocation(), diag::note_previous_declaration);
4439 } else if (method->isDirectMethod()) {
4440 const auto *attr = method->getAttr<ObjCDirectAttr>();
4441 Diag(attr->getLocation(), diag::err_objc_direct_on_override)
4442 << isa<ObjCProtocolDecl>(overridden->getDeclContext());
4443 Diag(overridden->getLocation(), diag::note_previous_declaration);
4444 }
4445}
4446
4448 ObjCInterfaceDecl *CurrentClass,
4450 ASTContext &Context = getASTContext();
4451 if (!ObjCMethod)
4452 return;
4453 auto IsMethodInCurrentClass = [CurrentClass](const ObjCMethodDecl *M) {
4454 // Checking canonical decl works across modules.
4455 return M->getClassInterface()->getCanonicalDecl() ==
4456 CurrentClass->getCanonicalDecl();
4457 };
4458 // Search for overridden methods and merge information down from them.
4459 OverrideSearch overrides(SemaRef, ObjCMethod);
4460 // Keep track if the method overrides any method in the class's base classes,
4461 // its protocols, or its categories' protocols; we will keep that info
4462 // in the ObjCMethodDecl.
4463 // For this info, a method in an implementation is not considered as
4464 // overriding the same method in the interface or its categories.
4465 bool hasOverriddenMethodsInBaseOrProtocol = false;
4466 for (ObjCMethodDecl *overridden : overrides) {
4467 if (!hasOverriddenMethodsInBaseOrProtocol) {
4468 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4469 !IsMethodInCurrentClass(overridden) || overridden->isOverriding()) {
4470 CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
4471 hasOverriddenMethodsInBaseOrProtocol = true;
4472 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4473 // OverrideSearch will return as "overridden" the same method in the
4474 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4475 // check whether a category of a base class introduced a method with the
4476 // same selector, after the interface method declaration.
4477 // To avoid unnecessary lookups in the majority of cases, we use the
4478 // extra info bits in GlobalMethodPool to check whether there were any
4479 // category methods with this selector.
4481 MethodPool.find(ObjCMethod->getSelector());
4482 if (It != MethodPool.end()) {
4483 ObjCMethodList &List =
4484 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4485 unsigned CategCount = List.getBits();
4486 if (CategCount > 0) {
4487 // If the method is in a category we'll do lookup if there were at
4488 // least 2 category methods recorded, otherwise only one will do.
4489 if (CategCount > 1 ||
4490 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4491 OverrideSearch overrides(SemaRef, overridden);
4492 for (ObjCMethodDecl *SuperOverridden : overrides) {
4493 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4494 !IsMethodInCurrentClass(SuperOverridden)) {
4495 CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
4496 hasOverriddenMethodsInBaseOrProtocol = true;
4497 overridden->setOverriding(true);
4498 break;
4499 }
4500 }
4501 }
4502 }
4503 }
4504 }
4505 }
4506
4507 // Propagate down the 'related result type' bit from overridden methods.
4508 if (RTC != SemaObjC::RTC_Incompatible && overridden->hasRelatedResultType())
4509 ObjCMethod->setRelatedResultType();
4510
4511 // Then merge the declarations.
4512 SemaRef.mergeObjCMethodDecls(ObjCMethod, overridden);
4513
4514 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4515 continue; // Conflicting properties are detected elsewhere.
4516
4517 // Check for overriding methods
4518 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4519 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4520 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4521 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4522
4523 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4524 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4525 !overridden->isImplicit() /* not meant for properties */) {
4526 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4527 E = ObjCMethod->param_end();
4528 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4529 PrevE = overridden->param_end();
4530 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4531 assert(PrevI != overridden->param_end() && "Param mismatch");
4532 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4533 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4534 // If type of argument of method in this class does not match its
4535 // respective argument type in the super class method, issue warning;
4536 if (!Context.typesAreCompatible(T1, T2)) {
4537 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4538 << T1 << T2;
4539 Diag(overridden->getLocation(), diag::note_previous_declaration);
4540 break;
4541 }
4542 }
4543 }
4544 }
4545
4546 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4547}
4548
4549/// Merge type nullability from for a redeclaration of the same entity,
4550/// producing the updated type of the redeclared entity.
4552 QualType type,
4553 bool usesCSKeyword,
4554 SourceLocation prevLoc,
4555 QualType prevType,
4556 bool prevUsesCSKeyword) {
4557 // Determine the nullability of both types.
4558 auto nullability = type->getNullability();
4559 auto prevNullability = prevType->getNullability();
4560
4561 // Easy case: both have nullability.
4562 if (nullability.has_value() == prevNullability.has_value()) {
4563 // Neither has nullability; continue.
4564 if (!nullability)
4565 return type;
4566
4567 // The nullabilities are equivalent; do nothing.
4568 if (*nullability == *prevNullability)
4569 return type;
4570
4571 // Complain about mismatched nullability.
4572 S.Diag(loc, diag::err_nullability_conflicting)
4573 << DiagNullabilityKind(*nullability, usesCSKeyword)
4574 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4575 return type;
4576 }
4577
4578 // If it's the redeclaration that has nullability, don't change anything.
4579 if (nullability)
4580 return type;
4581
4582 // Otherwise, provide the result with the same nullability.
4583 return S.Context.getAttributedType(
4585 type, type);
4586}
4587
4588/// Merge information from the declaration of a method in the \@interface
4589/// (or a category/extension) into the corresponding method in the
4590/// @implementation (for a class or category).
4592 ObjCMethodDecl *method,
4593 ObjCMethodDecl *prevMethod) {
4594 // Merge the objc_requires_super attribute.
4595 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4596 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4597 // merge the attribute into implementation.
4598 method->addAttr(
4599 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4600 method->getLocation()));
4601 }
4602
4603 // Merge nullability of the result type.
4604 QualType newReturnType
4606 S, method->getReturnTypeSourceRange().getBegin(),
4607 method->getReturnType(),
4609 prevMethod->getReturnTypeSourceRange().getBegin(),
4610 prevMethod->getReturnType(),
4612 method->setReturnType(newReturnType);
4613
4614 // Handle each of the parameters.
4615 unsigned numParams = method->param_size();
4616 unsigned numPrevParams = prevMethod->param_size();
4617 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4618 ParmVarDecl *param = method->param_begin()[i];
4619 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4620
4621 // Merge nullability.
4622 QualType newParamType
4624 S, param->getLocation(), param->getType(),
4626 prevParam->getLocation(), prevParam->getType(),
4628 param->setType(newParamType);
4629 }
4630}
4631
4632/// Verify that the method parameters/return value have types that are supported
4633/// by the x86 target.
4635 const ObjCMethodDecl *Method) {
4636 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4637 llvm::Triple::x86 &&
4638 "x86-specific check invoked for a different target");
4640 QualType T;
4641 for (const ParmVarDecl *P : Method->parameters()) {
4642 if (P->getType()->isVectorType()) {
4643 Loc = P->getBeginLoc();
4644 T = P->getType();
4645 break;
4646 }
4647 }
4648 if (Loc.isInvalid()) {
4649 if (Method->getReturnType()->isVectorType()) {
4651 T = Method->getReturnType();
4652 } else
4653 return;
4654 }
4655
4656 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4657 // iOS < 9 and macOS < 10.11.
4658 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4659 VersionTuple AcceptedInVersion;
4660 if (Triple.getOS() == llvm::Triple::IOS)
4661 AcceptedInVersion = VersionTuple(/*Major=*/9);
4662 else if (Triple.isMacOSX())
4663 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4664 else
4665 return;
4667 AcceptedInVersion)
4668 return;
4669 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4670 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4671 : /*parameter*/ 0)
4672 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4673}
4674
4675static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4676 if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
4677 CD->hasAttr<ObjCDirectMembersAttr>()) {
4678 Method->addAttr(
4679 ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4680 }
4681}
4682
4684 ObjCMethodDecl *Method,
4685 ObjCImplDecl *ImpDecl = nullptr) {
4686 auto Sel = Method->getSelector();
4687 bool isInstance = Method->isInstanceMethod();
4688 bool diagnosed = false;
4689
4690 auto diagClash = [&](const ObjCMethodDecl *IMD) {
4691 if (diagnosed || IMD->isImplicit())
4692 return;
4693 if (Method->isDirectMethod() || IMD->isDirectMethod()) {
4694 S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
4695 << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod()
4696 << Method->getDeclName();
4697 S.Diag(IMD->getLocation(), diag::note_previous_declaration);
4698 diagnosed = true;
4699 }
4700 };
4701
4702 // Look for any other declaration of this method anywhere we can see in this
4703 // compilation unit.
4704 //
4705 // We do not use IDecl->lookupMethod() because we have specific needs:
4706 //
4707 // - we absolutely do not need to walk protocols, because
4708 // diag::err_objc_direct_on_protocol has already been emitted
4709 // during parsing if there's a conflict,
4710 //
4711 // - when we do not find a match in a given @interface container,
4712 // we need to attempt looking it up in the @implementation block if the
4713 // translation unit sees it to find more clashes.
4714
4715 if (auto *IMD = IDecl->getMethod(Sel, isInstance))
4716 diagClash(IMD);
4717 else if (auto *Impl = IDecl->getImplementation())
4718 if (Impl != ImpDecl)
4719 if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
4720 diagClash(IMD);
4721
4722 for (const auto *Cat : IDecl->visible_categories())
4723 if (auto *IMD = Cat->getMethod(Sel, isInstance))
4724 diagClash(IMD);
4725 else if (auto CatImpl = Cat->getImplementation())
4726 if (CatImpl != ImpDecl)
4727 if (auto *IMD = Cat->getMethod(Sel, isInstance))
4728 diagClash(IMD);
4729}
4730
4732 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4733 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4734 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4735 // optional arguments. The number of types/arguments is obtained
4736 // from the Sel.getNumArgs().
4737 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4738 unsigned CNumArgs, // c-style args
4739 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4740 bool isVariadic, bool MethodDefinition) {
4741 ASTContext &Context = getASTContext();
4742 // Make sure we can establish a context for the method.
4744 Diag(MethodLoc, diag::err_missing_method_context);
4745 return nullptr;
4746 }
4747
4748 Decl *ClassDecl = cast<ObjCContainerDecl>(SemaRef.CurContext);
4749 QualType resultDeclType;
4750
4751 bool HasRelatedResultType = false;
4752 TypeSourceInfo *ReturnTInfo = nullptr;
4753 if (ReturnType) {
4754 resultDeclType = SemaRef.GetTypeFromParser(ReturnType, &ReturnTInfo);
4755
4756 if (SemaRef.CheckFunctionReturnType(resultDeclType, MethodLoc))
4757 return nullptr;
4758
4759 QualType bareResultType = resultDeclType;
4760 (void)AttributedType::stripOuterNullability(bareResultType);
4761 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4762 } else { // get the type for "id".
4763 resultDeclType = Context.getObjCIdType();
4764 Diag(MethodLoc, diag::warn_missing_method_return_type)
4765 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4766 }
4767
4769 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo,
4770 SemaRef.CurContext, MethodType == tok::minus, isVariadic,
4771 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4772 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4773 MethodDeclKind == tok::objc_optional
4776 HasRelatedResultType);
4777
4779
4780 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4781 QualType ArgType;
4782 TypeSourceInfo *DI;
4783
4784 if (!ArgInfo[i].Type) {
4785 ArgType = Context.getObjCIdType();
4786 DI = nullptr;
4787 } else {
4788 ArgType = SemaRef.GetTypeFromParser(ArgInfo[i].Type, &DI);
4789 }
4790
4791 LookupResult R(SemaRef, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4794 SemaRef.LookupName(R, S);
4795 if (R.isSingleResult()) {
4796 NamedDecl *PrevDecl = R.getFoundDecl();
4797 if (S->isDeclScope(PrevDecl)) {
4798 Diag(ArgInfo[i].NameLoc,
4799 (MethodDefinition ? diag::warn_method_param_redefinition
4800 : diag::warn_method_param_declaration))
4801 << ArgInfo[i].Name;
4802 Diag(PrevDecl->getLocation(),
4803 diag::note_previous_declaration);
4804 }
4805 }
4806
4807 SourceLocation StartLoc = DI
4808 ? DI->getTypeLoc().getBeginLoc()
4809 : ArgInfo[i].NameLoc;
4810
4811 ParmVarDecl *Param =
4812 SemaRef.CheckParameter(ObjCMethod, StartLoc, ArgInfo[i].NameLoc,
4813 ArgInfo[i].Name, ArgType, DI, SC_None);
4814
4815 Param->setObjCMethodScopeInfo(i);
4816
4817 Param->setObjCDeclQualifier(
4818 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4819
4820 // Apply the attributes to the parameter.
4822 ArgInfo[i].ArgAttrs);
4824 SemaRef.ProcessAPINotes(Param);
4825
4826 if (Param->hasAttr<BlocksAttr>()) {
4827 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4828 Param->setInvalidDecl();
4829 }
4830 S->AddDecl(Param);
4831 SemaRef.IdResolver.AddDecl(Param);
4832
4833 Params.push_back(Param);
4834 }
4835
4836 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4837 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4838 QualType ArgType = Param->getType();
4839 if (ArgType.isNull())
4840 ArgType = Context.getObjCIdType();
4841 else
4842 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4843 ArgType = Context.getAdjustedParameterType(ArgType);
4844
4845 Param->setDeclContext(ObjCMethod);
4846 Params.push_back(Param);
4847 }
4848
4849 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4850 ObjCMethod->setObjCDeclQualifier(
4852
4853 SemaRef.ProcessDeclAttributeList(SemaRef.TUScope, ObjCMethod, AttrList);
4855 SemaRef.ProcessAPINotes(ObjCMethod);
4856
4857 // Add the method now.
4858 const ObjCMethodDecl *PrevMethod = nullptr;
4859 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4860 if (MethodType == tok::minus) {
4861 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4862 ImpDecl->addInstanceMethod(ObjCMethod);
4863 } else {
4864 PrevMethod = ImpDecl->getClassMethod(Sel);
4865 ImpDecl->addClassMethod(ObjCMethod);
4866 }
4867
4868 // If this method overrides a previous @synthesize declaration,
4869 // register it with the property. Linear search through all
4870 // properties here, because the autosynthesized stub hasn't been
4871 // made visible yet, so it can be overridden by a later
4872 // user-specified implementation.
4873 for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4874 if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4875 if (Setter->getSelector() == Sel &&
4876 Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4877 assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4878 PropertyImpl->setSetterMethodDecl(ObjCMethod);
4879 }
4880 if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4881 if (Getter->getSelector() == Sel &&
4882 Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4883 assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4884 PropertyImpl->setGetterMethodDecl(ObjCMethod);
4885 break;
4886 }
4887 }
4888
4889 // A method is either tagged direct explicitly, or inherits it from its
4890 // canonical declaration.
4891 //
4892 // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4893 // because IDecl->lookupMethod() returns more possible matches than just
4894 // the canonical declaration.
4895 if (!ObjCMethod->isDirectMethod()) {
4896 const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4897 if (CanonicalMD->isDirectMethod()) {
4898 const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4899 ObjCMethod->addAttr(
4900 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4901 }
4902 }
4903
4904 // Merge information from the @interface declaration into the
4905 // @implementation.
4906 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4907 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4908 ObjCMethod->isInstanceMethod())) {
4909 mergeInterfaceMethodToImpl(SemaRef, ObjCMethod, IMD);
4910
4911 // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4912 // in one of these places:
4913 //
4914 // (1) the canonical declaration in an @interface container paired
4915 // with the ImplDecl,
4916 // (2) non canonical declarations in @interface not paired with the
4917 // ImplDecl for the same Class,
4918 // (3) any superclass container.
4919 //
4920 // Direct methods only allow for canonical declarations in the matching
4921 // container (case 1).
4922 //
4923 // Direct methods overriding a superclass declaration (case 3) is
4924 // handled during overrides checks in CheckObjCMethodOverrides().
4925 //
4926 // We deal with same-class container mismatches (Case 2) here.
4927 if (IDecl == IMD->getClassInterface()) {
4928 auto diagContainerMismatch = [&] {
4929 int decl = 0, impl = 0;
4930
4931 if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4932 decl = Cat->IsClassExtension() ? 1 : 2;
4933
4934 if (isa<ObjCCategoryImplDecl>(ImpDecl))
4935 impl = 1 + (decl != 0);
4936
4937 Diag(ObjCMethod->getLocation(),
4938 diag::err_objc_direct_impl_decl_mismatch)
4939 << decl << impl;
4940 Diag(IMD->getLocation(), diag::note_previous_declaration);
4941 };
4942
4943 if (ObjCMethod->isDirectMethod()) {
4944 const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4945 if (ObjCMethod->getCanonicalDecl() != IMD) {
4946 diagContainerMismatch();
4947 } else if (!IMD->isDirectMethod()) {
4948 Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4949 Diag(IMD->getLocation(), diag::note_previous_declaration);
4950 }
4951 } else if (IMD->isDirectMethod()) {
4952 const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4953 if (ObjCMethod->getCanonicalDecl() != IMD) {
4954 diagContainerMismatch();