1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for Objective C declarations.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/Sema/Lookup.h"
16 #include "clang/Sema/ExternalSemaSource.h"
17 #include "clang/Sema/Scope.h"
18 #include "clang/Sema/ScopeInfo.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/Sema/DeclSpec.h"
23 #include "llvm/ADT/DenseSet.h"
25 using namespace clang;
27 static void DiagnoseObjCImplementedDeprecations(Sema &S,
29 SourceLocation ImplLoc,
31 if (ND && ND->isDeprecated()) {
32 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
34 S.Diag(ND->getLocation(), diag::note_method_declared_at);
36 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
40 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
41 /// and user declared, in the method definition's AST.
42 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
43 assert(getCurMethodDecl() == 0 && "Method parsing confused");
44 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
46 // If we don't have a valid method decl, simply return.
50 // Allow the rest of sema to find private method decl implementations.
51 if (MDecl->isInstanceMethod())
52 AddInstanceMethodToGlobalPool(MDecl, true);
54 AddFactoryMethodToGlobalPool(MDecl, true);
56 // Allow all of Sema to see that we are entering a method definition.
57 PushDeclContext(FnBodyScope, MDecl);
60 // Create Decl objects for each parameter, entrring them in the scope for
61 // binding to their use.
63 // Insert the invisible arguments, self and _cmd!
64 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
66 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
67 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
69 // Introduce all of the other parameters into this scope.
70 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
71 E = MDecl->param_end(); PI != E; ++PI) {
72 ParmVarDecl *Param = (*PI);
73 if (!Param->isInvalidDecl() &&
74 RequireCompleteType(Param->getLocation(), Param->getType(),
75 diag::err_typecheck_decl_incomplete_type))
76 Param->setInvalidDecl();
77 if ((*PI)->getIdentifier())
78 PushOnScopeChains(*PI, FnBodyScope);
80 // Warn on implementating deprecated methods under
81 // -Wdeprecated-implementations flag.
82 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface())
83 if (ObjCMethodDecl *IMD =
84 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod()))
85 DiagnoseObjCImplementedDeprecations(*this,
86 dyn_cast<NamedDecl>(IMD),
87 MDecl->getLocation(), 0);
91 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
92 IdentifierInfo *ClassName, SourceLocation ClassLoc,
93 IdentifierInfo *SuperName, SourceLocation SuperLoc,
94 Decl * const *ProtoRefs, unsigned NumProtoRefs,
95 const SourceLocation *ProtoLocs,
96 SourceLocation EndProtoLoc, AttributeList *AttrList) {
97 assert(ClassName && "Missing class identifier");
99 // Check for another declaration kind with the same name.
100 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
101 LookupOrdinaryName, ForRedeclaration);
103 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
104 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
105 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
108 ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
110 // Class already seen. Is it a forward declaration?
111 if (!IDecl->isForwardDecl()) {
112 IDecl->setInvalidDecl();
113 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
114 Diag(IDecl->getLocation(), diag::note_previous_definition);
116 // Return the previous class interface.
117 // FIXME: don't leak the objects passed in!
120 IDecl->setLocation(AtInterfaceLoc);
121 IDecl->setForwardDecl(false);
122 IDecl->setClassLoc(ClassLoc);
123 // If the forward decl was in a PCH, we need to write it again in a
124 // dependent AST file.
125 IDecl->setChangedSinceDeserialization(true);
127 // Since this ObjCInterfaceDecl was created by a forward declaration,
128 // we now add it to the DeclContext since it wasn't added before
129 // (see ActOnForwardClassDeclaration).
130 IDecl->setLexicalDeclContext(CurContext);
131 CurContext->addDecl(IDecl);
134 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
137 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
138 ClassName, ClassLoc);
140 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
142 PushOnScopeChains(IDecl, TUScope);
146 // Check if a different kind of symbol declared in this scope.
147 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
151 // Try to correct for a typo in the superclass name.
152 LookupResult R(*this, SuperName, SuperLoc, LookupOrdinaryName);
153 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
154 (PrevDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
155 Diag(SuperLoc, diag::err_undef_superclass_suggest)
156 << SuperName << ClassName << PrevDecl->getDeclName();
157 Diag(PrevDecl->getLocation(), diag::note_previous_decl)
158 << PrevDecl->getDeclName();
162 if (PrevDecl == IDecl) {
163 Diag(SuperLoc, diag::err_recursive_superclass)
164 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
165 IDecl->setLocEnd(ClassLoc);
167 ObjCInterfaceDecl *SuperClassDecl =
168 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
170 // Diagnose classes that inherit from deprecated classes.
172 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
174 if (PrevDecl && SuperClassDecl == 0) {
175 // The previous declaration was not a class decl. Check if we have a
176 // typedef. If we do, get the underlying class type.
177 if (const TypedefNameDecl *TDecl =
178 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
179 QualType T = TDecl->getUnderlyingType();
180 if (T->isObjCObjectType()) {
181 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
182 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
186 // This handles the following case:
188 // typedef int SuperClass;
189 // @interface MyClass : SuperClass {} @end
191 if (!SuperClassDecl) {
192 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
193 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
197 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
199 Diag(SuperLoc, diag::err_undef_superclass)
200 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
201 else if (SuperClassDecl->isForwardDecl())
202 Diag(SuperLoc, diag::err_undef_superclass)
203 << SuperClassDecl->getDeclName() << ClassName
204 << SourceRange(AtInterfaceLoc, ClassLoc);
206 IDecl->setSuperClass(SuperClassDecl);
207 IDecl->setSuperClassLoc(SuperLoc);
208 IDecl->setLocEnd(SuperLoc);
210 } else { // we have a root class.
211 IDecl->setLocEnd(ClassLoc);
214 // Check then save referenced protocols.
216 IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
218 IDecl->setLocEnd(EndProtoLoc);
221 CheckObjCDeclScope(IDecl);
225 /// ActOnCompatiblityAlias - this action is called after complete parsing of
226 /// @compatibility_alias declaration. It sets up the alias relationships.
227 Decl *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
228 IdentifierInfo *AliasName,
229 SourceLocation AliasLocation,
230 IdentifierInfo *ClassName,
231 SourceLocation ClassLocation) {
232 // Look for previous declaration of alias name
233 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
234 LookupOrdinaryName, ForRedeclaration);
236 if (isa<ObjCCompatibleAliasDecl>(ADecl))
237 Diag(AliasLocation, diag::warn_previous_alias_decl);
239 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
240 Diag(ADecl->getLocation(), diag::note_previous_declaration);
243 // Check for class declaration
244 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
245 LookupOrdinaryName, ForRedeclaration);
246 if (const TypedefNameDecl *TDecl =
247 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
248 QualType T = TDecl->getUnderlyingType();
249 if (T->isObjCObjectType()) {
250 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
251 ClassName = IDecl->getIdentifier();
252 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
253 LookupOrdinaryName, ForRedeclaration);
257 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
259 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
261 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
265 // Everything checked out, instantiate a new alias declaration AST.
266 ObjCCompatibleAliasDecl *AliasDecl =
267 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
269 if (!CheckObjCDeclScope(AliasDecl))
270 PushOnScopeChains(AliasDecl, TUScope);
275 void Sema::CheckForwardProtocolDeclarationForCircularDependency(
276 IdentifierInfo *PName,
277 SourceLocation &Ploc, SourceLocation PrevLoc,
278 const ObjCList<ObjCProtocolDecl> &PList) {
279 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
280 E = PList.end(); I != E; ++I) {
282 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
284 if (PDecl->getIdentifier() == PName) {
285 Diag(Ploc, diag::err_protocol_has_circular_dependency);
286 Diag(PrevLoc, diag::note_previous_definition);
288 CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
289 PDecl->getLocation(), PDecl->getReferencedProtocols());
295 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
296 IdentifierInfo *ProtocolName,
297 SourceLocation ProtocolLoc,
298 Decl * const *ProtoRefs,
299 unsigned NumProtoRefs,
300 const SourceLocation *ProtoLocs,
301 SourceLocation EndProtoLoc,
302 AttributeList *AttrList) {
303 // FIXME: Deal with AttrList.
304 assert(ProtocolName && "Missing protocol identifier");
305 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
307 // Protocol already seen. Better be a forward protocol declaration
308 if (!PDecl->isForwardDecl()) {
309 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
310 Diag(PDecl->getLocation(), diag::note_previous_definition);
311 // Just return the protocol we already had.
312 // FIXME: don't leak the objects passed in!
315 ObjCList<ObjCProtocolDecl> PList;
316 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
317 CheckForwardProtocolDeclarationForCircularDependency(
318 ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
320 // Make sure the cached decl gets a valid start location.
321 PDecl->setLocation(AtProtoInterfaceLoc);
322 PDecl->setForwardDecl(false);
323 CurContext->addDecl(PDecl);
324 // Repeat in dependent AST files.
325 PDecl->setChangedSinceDeserialization(true);
327 PDecl = ObjCProtocolDecl::Create(Context, CurContext,
328 AtProtoInterfaceLoc,ProtocolName);
329 PushOnScopeChains(PDecl, TUScope);
330 PDecl->setForwardDecl(false);
333 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
335 /// Check then save referenced protocols.
336 PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
338 PDecl->setLocEnd(EndProtoLoc);
341 CheckObjCDeclScope(PDecl);
345 /// FindProtocolDeclaration - This routine looks up protocols and
346 /// issues an error if they are not declared. It returns list of
347 /// protocol declarations in its 'Protocols' argument.
349 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
350 const IdentifierLocPair *ProtocolId,
351 unsigned NumProtocols,
352 llvm::SmallVectorImpl<Decl *> &Protocols) {
353 for (unsigned i = 0; i != NumProtocols; ++i) {
354 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
355 ProtocolId[i].second);
357 LookupResult R(*this, ProtocolId[i].first, ProtocolId[i].second,
358 LookupObjCProtocolName);
359 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
360 (PDecl = R.getAsSingle<ObjCProtocolDecl>())) {
361 Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
362 << ProtocolId[i].first << R.getLookupName();
363 Diag(PDecl->getLocation(), diag::note_previous_decl)
364 << PDecl->getDeclName();
369 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
370 << ProtocolId[i].first;
374 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
376 // If this is a forward declaration and we are supposed to warn in this
378 if (WarnOnDeclarations && PDecl->isForwardDecl())
379 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
380 << ProtocolId[i].first;
381 Protocols.push_back(PDecl);
385 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
386 /// a class method in its extension.
388 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
389 ObjCInterfaceDecl *ID) {
391 return; // Possibly due to previous error
393 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
394 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
395 e = ID->meth_end(); i != e; ++i) {
396 ObjCMethodDecl *MD = *i;
397 MethodMap[MD->getSelector()] = MD;
400 if (MethodMap.empty())
402 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
403 e = CAT->meth_end(); i != e; ++i) {
404 ObjCMethodDecl *Method = *i;
405 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
406 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
407 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
408 << Method->getDeclName();
409 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
414 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
416 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
417 const IdentifierLocPair *IdentList,
419 AttributeList *attrList) {
420 llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
421 llvm::SmallVector<SourceLocation, 8> ProtoLocs;
423 for (unsigned i = 0; i != NumElts; ++i) {
424 IdentifierInfo *Ident = IdentList[i].first;
425 ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
427 if (PDecl == 0) { // Not already seen?
428 PDecl = ObjCProtocolDecl::Create(Context, CurContext,
429 IdentList[i].second, Ident);
430 PushOnScopeChains(PDecl, TUScope, false);
434 ProcessDeclAttributeList(TUScope, PDecl, attrList);
436 PDecl->setChangedSinceDeserialization(true);
438 Protocols.push_back(PDecl);
439 ProtoLocs.push_back(IdentList[i].second);
442 ObjCForwardProtocolDecl *PDecl =
443 ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
444 Protocols.data(), Protocols.size(),
446 CurContext->addDecl(PDecl);
447 CheckObjCDeclScope(PDecl);
452 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
453 IdentifierInfo *ClassName, SourceLocation ClassLoc,
454 IdentifierInfo *CategoryName,
455 SourceLocation CategoryLoc,
456 Decl * const *ProtoRefs,
457 unsigned NumProtoRefs,
458 const SourceLocation *ProtoLocs,
459 SourceLocation EndProtoLoc) {
460 ObjCCategoryDecl *CDecl;
461 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
463 /// Check that class of this category is already completely declared.
464 if (!IDecl || IDecl->isForwardDecl()) {
465 // Create an invalid ObjCCategoryDecl to serve as context for
466 // the enclosing method declarations. We mark the decl invalid
467 // to make it clear that this isn't a valid AST.
468 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
469 ClassLoc, CategoryLoc, CategoryName);
470 CDecl->setInvalidDecl();
471 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
475 if (!CategoryName && IDecl->getImplementation()) {
476 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
477 Diag(IDecl->getImplementation()->getLocation(),
478 diag::note_implementation_declared);
481 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
482 ClassLoc, CategoryLoc, CategoryName);
483 // FIXME: PushOnScopeChains?
484 CurContext->addDecl(CDecl);
486 CDecl->setClassInterface(IDecl);
487 // Insert class extension to the list of class's categories.
489 CDecl->insertNextClassCategory();
491 // If the interface is deprecated, warn about it.
492 (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
495 /// Check for duplicate interface declaration for this category
496 ObjCCategoryDecl *CDeclChain;
497 for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
498 CDeclChain = CDeclChain->getNextClassCategory()) {
499 if (CDeclChain->getIdentifier() == CategoryName) {
500 // Class extensions can be declared multiple times.
501 Diag(CategoryLoc, diag::warn_dup_category_def)
502 << ClassName << CategoryName;
503 Diag(CDeclChain->getLocation(), diag::note_previous_definition);
508 CDecl->insertNextClassCategory();
512 CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
514 // Protocols in the class extension belong to the class.
515 if (CDecl->IsClassExtension())
516 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
517 NumProtoRefs, Context);
520 CheckObjCDeclScope(CDecl);
524 /// ActOnStartCategoryImplementation - Perform semantic checks on the
525 /// category implementation declaration and build an ObjCCategoryImplDecl
527 Decl *Sema::ActOnStartCategoryImplementation(
528 SourceLocation AtCatImplLoc,
529 IdentifierInfo *ClassName, SourceLocation ClassLoc,
530 IdentifierInfo *CatName, SourceLocation CatLoc) {
531 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
532 ObjCCategoryDecl *CatIDecl = 0;
534 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
536 // Category @implementation with no corresponding @interface.
537 // Create and install one.
538 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
539 SourceLocation(), SourceLocation(),
541 CatIDecl->setClassInterface(IDecl);
542 CatIDecl->insertNextClassCategory();
546 ObjCCategoryImplDecl *CDecl =
547 ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
549 /// Check that class of this category is already completely declared.
550 if (!IDecl || IDecl->isForwardDecl())
551 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
553 // FIXME: PushOnScopeChains?
554 CurContext->addDecl(CDecl);
556 /// Check that CatName, category name, is not used in another implementation.
558 if (CatIDecl->getImplementation()) {
559 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
561 Diag(CatIDecl->getImplementation()->getLocation(),
562 diag::note_previous_definition);
564 CatIDecl->setImplementation(CDecl);
565 // Warn on implementating category of deprecated class under
566 // -Wdeprecated-implementations flag.
567 DiagnoseObjCImplementedDeprecations(*this,
568 dyn_cast<NamedDecl>(IDecl),
569 CDecl->getLocation(), 2);
573 CheckObjCDeclScope(CDecl);
577 Decl *Sema::ActOnStartClassImplementation(
578 SourceLocation AtClassImplLoc,
579 IdentifierInfo *ClassName, SourceLocation ClassLoc,
580 IdentifierInfo *SuperClassname,
581 SourceLocation SuperClassLoc) {
582 ObjCInterfaceDecl* IDecl = 0;
583 // Check for another declaration kind with the same name.
585 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
587 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
588 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
589 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
590 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
591 // If this is a forward declaration of an interface, warn.
592 if (IDecl->isForwardDecl()) {
593 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
597 // We did not find anything with the name ClassName; try to correct for
598 // typos in the class name.
599 LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
600 if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
601 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
602 // Suggest the (potentially) correct interface name. However, put the
603 // fix-it hint itself in a separate note, since changing the name in
604 // the warning would make the fix-it change semantics.However, don't
605 // provide a code-modification hint or use the typo name for recovery,
606 // because this is just a warning. The program may actually be correct.
607 Diag(ClassLoc, diag::warn_undef_interface_suggest)
608 << ClassName << R.getLookupName();
609 Diag(IDecl->getLocation(), diag::note_previous_decl)
611 << FixItHint::CreateReplacement(ClassLoc,
612 R.getLookupName().getAsString());
615 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
619 // Check that super class name is valid class name
620 ObjCInterfaceDecl* SDecl = 0;
621 if (SuperClassname) {
622 // Check if a different kind of symbol declared in this scope.
623 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
625 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
626 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
628 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
630 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
632 Diag(SuperClassLoc, diag::err_undef_superclass)
633 << SuperClassname << ClassName;
634 else if (IDecl && IDecl->getSuperClass() != SDecl) {
635 // This implementation and its interface do not have the same
637 Diag(SuperClassLoc, diag::err_conflicting_super_class)
638 << SDecl->getDeclName();
639 Diag(SDecl->getLocation(), diag::note_previous_definition);
645 // Legacy case of @implementation with no corresponding @interface.
646 // Build, chain & install the interface decl into the identifier.
648 // FIXME: Do we support attributes on the @implementation? If so we should
650 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
651 ClassName, ClassLoc, false, true);
652 IDecl->setSuperClass(SDecl);
653 IDecl->setLocEnd(ClassLoc);
655 PushOnScopeChains(IDecl, TUScope);
657 // Mark the interface as being completed, even if it was just as
659 // declaration; the user cannot reopen it.
660 IDecl->setForwardDecl(false);
663 ObjCImplementationDecl* IMPDecl =
664 ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
667 if (CheckObjCDeclScope(IMPDecl))
670 // Check that there is no duplicate implementation of this class.
671 if (IDecl->getImplementation()) {
672 // FIXME: Don't leak everything!
673 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
674 Diag(IDecl->getImplementation()->getLocation(),
675 diag::note_previous_definition);
676 } else { // add it to the list.
677 IDecl->setImplementation(IMPDecl);
678 PushOnScopeChains(IMPDecl, TUScope);
679 // Warn on implementating deprecated class under
680 // -Wdeprecated-implementations flag.
681 DiagnoseObjCImplementedDeprecations(*this,
682 dyn_cast<NamedDecl>(IDecl),
683 IMPDecl->getLocation(), 1);
688 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
689 ObjCIvarDecl **ivars, unsigned numIvars,
690 SourceLocation RBrace) {
691 assert(ImpDecl && "missing implementation decl");
692 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
695 /// Check case of non-existing @interface decl.
696 /// (legacy objective-c @implementation decl without an @interface decl).
697 /// Add implementations's ivar to the synthesize class's ivar list.
698 if (IDecl->isImplicitInterfaceDecl()) {
699 IDecl->setLocEnd(RBrace);
700 // Add ivar's to class's DeclContext.
701 for (unsigned i = 0, e = numIvars; i != e; ++i) {
702 ivars[i]->setLexicalDeclContext(ImpDecl);
703 IDecl->makeDeclVisibleInContext(ivars[i], false);
704 ImpDecl->addDecl(ivars[i]);
709 // If implementation has empty ivar list, just return.
713 assert(ivars && "missing @implementation ivars");
714 if (LangOpts.ObjCNonFragileABI2) {
715 if (ImpDecl->getSuperClass())
716 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
717 for (unsigned i = 0; i < numIvars; i++) {
718 ObjCIvarDecl* ImplIvar = ivars[i];
719 if (const ObjCIvarDecl *ClsIvar =
720 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
721 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
722 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
725 // Instance ivar to Implementation's DeclContext.
726 ImplIvar->setLexicalDeclContext(ImpDecl);
727 IDecl->makeDeclVisibleInContext(ImplIvar, false);
728 ImpDecl->addDecl(ImplIvar);
732 // Check interface's Ivar list against those in the implementation.
733 // names and types must match.
736 ObjCInterfaceDecl::ivar_iterator
737 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
738 for (; numIvars > 0 && IVI != IVE; ++IVI) {
739 ObjCIvarDecl* ImplIvar = ivars[j++];
740 ObjCIvarDecl* ClsIvar = *IVI;
741 assert (ImplIvar && "missing implementation ivar");
742 assert (ClsIvar && "missing class ivar");
744 // First, make sure the types match.
745 if (Context.getCanonicalType(ImplIvar->getType()) !=
746 Context.getCanonicalType(ClsIvar->getType())) {
747 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
748 << ImplIvar->getIdentifier()
749 << ImplIvar->getType() << ClsIvar->getType();
750 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
751 } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
752 Expr *ImplBitWidth = ImplIvar->getBitWidth();
753 Expr *ClsBitWidth = ClsIvar->getBitWidth();
754 if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
755 ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
756 Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
757 << ImplIvar->getIdentifier();
758 Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
761 // Make sure the names are identical.
762 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
763 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
764 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
765 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
771 Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
773 Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
776 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
777 bool &IncompleteImpl, unsigned DiagID) {
778 if (!IncompleteImpl) {
779 Diag(ImpLoc, diag::warn_incomplete_impl);
780 IncompleteImpl = true;
782 if (DiagID == diag::warn_unimplemented_protocol_method)
783 Diag(ImpLoc, DiagID) << method->getDeclName();
785 Diag(method->getLocation(), DiagID) << method->getDeclName();
788 /// Determines if type B can be substituted for type A. Returns true if we can
789 /// guarantee that anything that the user will do to an object of type A can
790 /// also be done to an object of type B. This is trivially true if the two
791 /// types are the same, or if B is a subclass of A. It becomes more complex
792 /// in cases where protocols are involved.
794 /// Object types in Objective-C describe the minimum requirements for an
795 /// object, rather than providing a complete description of a type. For
796 /// example, if A is a subclass of B, then B* may refer to an instance of A.
797 /// The principle of substitutability means that we may use an instance of A
798 /// anywhere that we may use an instance of B - it will implement all of the
799 /// ivars of B and all of the methods of B.
801 /// This substitutability is important when type checking methods, because
802 /// the implementation may have stricter type definitions than the interface.
803 /// The interface specifies minimum requirements, but the implementation may
804 /// have more accurate ones. For example, a method may privately accept
805 /// instances of B, but only publish that it accepts instances of A. Any
806 /// object passed to it will be type checked against B, and so will implicitly
807 /// by a valid A*. Similarly, a method may return a subclass of the class that
808 /// it is declared as returning.
810 /// This is most important when considering subclassing. A method in a
811 /// subclass must accept any object as an argument that its superclass's
812 /// implementation accepts. It may, however, accept a more general type
813 /// without breaking substitutability (i.e. you can still use the subclass
814 /// anywhere that you can use the superclass, but not vice versa). The
815 /// converse requirement applies to return types: the return type for a
816 /// subclass method must be a valid object of the kind that the superclass
817 /// advertises, but it may be specified more accurately. This avoids the need
818 /// for explicit down-casting by callers.
820 /// Note: This is a stricter requirement than for assignment.
821 static bool isObjCTypeSubstitutable(ASTContext &Context,
822 const ObjCObjectPointerType *A,
823 const ObjCObjectPointerType *B,
825 // Reject a protocol-unqualified id.
826 if (rejectId && B->isObjCIdType()) return false;
828 // If B is a qualified id, then A must also be a qualified id and it must
829 // implement all of the protocols in B. It may not be a qualified class.
830 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
831 // stricter definition so it is not substitutable for id<A>.
832 if (B->isObjCQualifiedIdType()) {
833 return A->isObjCQualifiedIdType() &&
834 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
840 // id is a special type that bypasses type checking completely. We want a
841 // warning when it is used in one place but not another.
842 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
845 // If B is a qualified id, then A must also be a qualified id (which it isn't
846 // if we've got this far)
847 if (B->isObjCQualifiedIdType()) return false;
850 // Now we know that A and B are (potentially-qualified) class types. The
851 // normal rules for assignment apply.
852 return Context.canAssignObjCInterfaces(A, B);
855 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
856 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
859 static void CheckMethodOverrideReturn(Sema &S,
860 ObjCMethodDecl *MethodImpl,
861 ObjCMethodDecl *MethodDecl,
862 bool IsProtocolMethodDecl) {
863 if (IsProtocolMethodDecl &&
864 (MethodDecl->getObjCDeclQualifier() !=
865 MethodImpl->getObjCDeclQualifier())) {
866 S.Diag(MethodImpl->getLocation(),
867 diag::warn_conflicting_ret_type_modifiers)
868 << MethodImpl->getDeclName()
869 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
870 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
871 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
874 if (S.Context.hasSameUnqualifiedType(MethodImpl->getResultType(),
875 MethodDecl->getResultType()))
878 unsigned DiagID = diag::warn_conflicting_ret_types;
880 // Mismatches between ObjC pointers go into a different warning
881 // category, and sometimes they're even completely whitelisted.
882 if (const ObjCObjectPointerType *ImplPtrTy =
883 MethodImpl->getResultType()->getAs<ObjCObjectPointerType>()) {
884 if (const ObjCObjectPointerType *IfacePtrTy =
885 MethodDecl->getResultType()->getAs<ObjCObjectPointerType>()) {
886 // Allow non-matching return types as long as they don't violate
887 // the principle of substitutability. Specifically, we permit
888 // return types that are subclasses of the declared return type,
889 // or that are more-qualified versions of the declared type.
890 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
893 DiagID = diag::warn_non_covariant_ret_types;
897 S.Diag(MethodImpl->getLocation(), DiagID)
898 << MethodImpl->getDeclName()
899 << MethodDecl->getResultType()
900 << MethodImpl->getResultType()
901 << getTypeRange(MethodImpl->getResultTypeSourceInfo());
902 S.Diag(MethodDecl->getLocation(), diag::note_previous_definition)
903 << getTypeRange(MethodDecl->getResultTypeSourceInfo());
906 static void CheckMethodOverrideParam(Sema &S,
907 ObjCMethodDecl *MethodImpl,
908 ObjCMethodDecl *MethodDecl,
909 ParmVarDecl *ImplVar,
910 ParmVarDecl *IfaceVar,
911 bool IsProtocolMethodDecl) {
912 if (IsProtocolMethodDecl &&
913 (ImplVar->getObjCDeclQualifier() !=
914 IfaceVar->getObjCDeclQualifier())) {
915 S.Diag(ImplVar->getLocation(),
916 diag::warn_conflicting_param_modifiers)
917 << getTypeRange(ImplVar->getTypeSourceInfo())
918 << MethodImpl->getDeclName();
919 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
920 << getTypeRange(IfaceVar->getTypeSourceInfo());
923 QualType ImplTy = ImplVar->getType();
924 QualType IfaceTy = IfaceVar->getType();
926 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
929 unsigned DiagID = diag::warn_conflicting_param_types;
931 // Mismatches between ObjC pointers go into a different warning
932 // category, and sometimes they're even completely whitelisted.
933 if (const ObjCObjectPointerType *ImplPtrTy =
934 ImplTy->getAs<ObjCObjectPointerType>()) {
935 if (const ObjCObjectPointerType *IfacePtrTy =
936 IfaceTy->getAs<ObjCObjectPointerType>()) {
937 // Allow non-matching argument types as long as they don't
938 // violate the principle of substitutability. Specifically, the
939 // implementation must accept any objects that the superclass
940 // accepts, however it may also accept others.
941 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
944 DiagID = diag::warn_non_contravariant_param_types;
948 S.Diag(ImplVar->getLocation(), DiagID)
949 << getTypeRange(ImplVar->getTypeSourceInfo())
950 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
951 S.Diag(IfaceVar->getLocation(), diag::note_previous_definition)
952 << getTypeRange(IfaceVar->getTypeSourceInfo());
956 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
957 ObjCMethodDecl *MethodDecl,
958 bool IsProtocolMethodDecl) {
959 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
960 IsProtocolMethodDecl);
962 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
963 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
964 IM != EM; ++IM, ++IF)
965 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
966 IsProtocolMethodDecl);
968 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
969 Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic);
970 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
974 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
975 /// improve the efficiency of selector lookups and type checking by associating
976 /// with each protocol / interface / category the flattened instance tables. If
977 /// we used an immutable set to keep the table then it wouldn't add significant
978 /// memory cost and it would be handy for lookups.
980 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
981 /// Declared in protocol, and those referenced by it.
982 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
983 ObjCProtocolDecl *PDecl,
984 bool& IncompleteImpl,
985 const llvm::DenseSet<Selector> &InsMap,
986 const llvm::DenseSet<Selector> &ClsMap,
987 ObjCContainerDecl *CDecl) {
988 ObjCInterfaceDecl *IDecl;
989 if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
990 IDecl = C->getClassInterface();
992 IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
993 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
995 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
996 ObjCInterfaceDecl *NSIDecl = 0;
997 if (getLangOptions().NeXTRuntime) {
998 // check to see if class implements forwardInvocation method and objects
999 // of this class are derived from 'NSProxy' so that to forward requests
1000 // from one object to another.
1001 // Under such conditions, which means that every method possible is
1002 // implemented in the class, we should not issue "Method definition not
1004 // FIXME: Use a general GetUnarySelector method for this.
1005 IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
1006 Selector fISelector = Context.Selectors.getSelector(1, &II);
1007 if (InsMap.count(fISelector))
1008 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1009 // need be implemented in the implementation.
1010 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
1013 // If a method lookup fails locally we still need to look and see if
1014 // the method was implemented by a base class or an inherited
1015 // protocol. This lookup is slow, but occurs rarely in correct code
1016 // and otherwise would terminate in a warning.
1018 // check unimplemented instance methods.
1020 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1021 E = PDecl->instmeth_end(); I != E; ++I) {
1022 ObjCMethodDecl *method = *I;
1023 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1024 !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
1026 !Super->lookupInstanceMethod(method->getSelector()))) {
1027 // Ugly, but necessary. Method declared in protcol might have
1028 // have been synthesized due to a property declared in the class which
1029 // uses the protocol.
1030 ObjCMethodDecl *MethodInClass =
1031 IDecl->lookupInstanceMethod(method->getSelector());
1032 if (!MethodInClass || !MethodInClass->isSynthesized()) {
1033 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1034 if (Diags.getDiagnosticLevel(DIAG, ImpLoc)
1035 != Diagnostic::Ignored) {
1036 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1037 Diag(method->getLocation(), diag::note_method_declared_at);
1038 Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
1039 << PDecl->getDeclName();
1044 // check unimplemented class methods
1045 for (ObjCProtocolDecl::classmeth_iterator
1046 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1048 ObjCMethodDecl *method = *I;
1049 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1050 !ClsMap.count(method->getSelector()) &&
1051 (!Super || !Super->lookupClassMethod(method->getSelector()))) {
1052 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1053 if (Diags.getDiagnosticLevel(DIAG, ImpLoc) != Diagnostic::Ignored) {
1054 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
1055 Diag(method->getLocation(), diag::note_method_declared_at);
1056 Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
1057 PDecl->getDeclName();
1061 // Check on this protocols's referenced protocols, recursively.
1062 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1063 E = PDecl->protocol_end(); PI != E; ++PI)
1064 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
1067 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
1068 /// or protocol against those declared in their implementations.
1070 void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1071 const llvm::DenseSet<Selector> &ClsMap,
1072 llvm::DenseSet<Selector> &InsMapSeen,
1073 llvm::DenseSet<Selector> &ClsMapSeen,
1074 ObjCImplDecl* IMPDecl,
1075 ObjCContainerDecl* CDecl,
1076 bool &IncompleteImpl,
1077 bool ImmediateClass) {
1078 // Check and see if instance methods in class interface have been
1079 // implemented in the implementation class. If so, their types match.
1080 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1081 E = CDecl->instmeth_end(); I != E; ++I) {
1082 if (InsMapSeen.count((*I)->getSelector()))
1084 InsMapSeen.insert((*I)->getSelector());
1085 if (!(*I)->isSynthesized() &&
1086 !InsMap.count((*I)->getSelector())) {
1088 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1089 diag::note_undef_method_impl);
1092 ObjCMethodDecl *ImpMethodDecl =
1093 IMPDecl->getInstanceMethod((*I)->getSelector());
1094 ObjCMethodDecl *MethodDecl =
1095 CDecl->getInstanceMethod((*I)->getSelector());
1096 assert(MethodDecl &&
1097 "MethodDecl is null in ImplMethodsVsClassMethods");
1098 // ImpMethodDecl may be null as in a @dynamic property.
1100 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1101 isa<ObjCProtocolDecl>(CDecl));
1105 // Check and see if class methods in class interface have been
1106 // implemented in the implementation class. If so, their types match.
1107 for (ObjCInterfaceDecl::classmeth_iterator
1108 I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1109 if (ClsMapSeen.count((*I)->getSelector()))
1111 ClsMapSeen.insert((*I)->getSelector());
1112 if (!ClsMap.count((*I)->getSelector())) {
1114 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
1115 diag::note_undef_method_impl);
1117 ObjCMethodDecl *ImpMethodDecl =
1118 IMPDecl->getClassMethod((*I)->getSelector());
1119 ObjCMethodDecl *MethodDecl =
1120 CDecl->getClassMethod((*I)->getSelector());
1121 WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1122 isa<ObjCProtocolDecl>(CDecl));
1126 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1127 // Also methods in class extensions need be looked at next.
1128 for (const ObjCCategoryDecl *ClsExtDecl = I->getFirstClassExtension();
1129 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension())
1130 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1132 const_cast<ObjCCategoryDecl *>(ClsExtDecl),
1133 IncompleteImpl, false);
1135 // Check for any implementation of a methods declared in protocol.
1136 for (ObjCInterfaceDecl::all_protocol_iterator
1137 PI = I->all_referenced_protocol_begin(),
1138 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1139 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1141 (*PI), IncompleteImpl, false);
1142 if (I->getSuperClass())
1143 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1145 I->getSuperClass(), IncompleteImpl, false);
1149 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1150 ObjCContainerDecl* CDecl,
1151 bool IncompleteImpl) {
1152 llvm::DenseSet<Selector> InsMap;
1153 // Check and see if instance methods in class interface have been
1154 // implemented in the implementation class.
1155 for (ObjCImplementationDecl::instmeth_iterator
1156 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1157 InsMap.insert((*I)->getSelector());
1159 // Check and see if properties declared in the interface have either 1)
1160 // an implementation or 2) there is a @synthesize/@dynamic implementation
1161 // of the property in the @implementation.
1162 if (isa<ObjCInterfaceDecl>(CDecl) &&
1163 !(LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCNonFragileABI2))
1164 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1166 llvm::DenseSet<Selector> ClsMap;
1167 for (ObjCImplementationDecl::classmeth_iterator
1168 I = IMPDecl->classmeth_begin(),
1169 E = IMPDecl->classmeth_end(); I != E; ++I)
1170 ClsMap.insert((*I)->getSelector());
1172 // Check for type conflict of methods declared in a class/protocol and
1173 // its implementation; if any.
1174 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1175 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1177 IncompleteImpl, true);
1179 // Check the protocol list for unimplemented methods in the @implementation
1181 // Check and see if class methods in class interface have been
1182 // implemented in the implementation class.
1184 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1185 for (ObjCInterfaceDecl::all_protocol_iterator
1186 PI = I->all_referenced_protocol_begin(),
1187 E = I->all_referenced_protocol_end(); PI != E; ++PI)
1188 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1190 // Check class extensions (unnamed categories)
1191 for (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
1192 Categories; Categories = Categories->getNextClassExtension())
1193 ImplMethodsVsClassMethods(S, IMPDecl,
1194 const_cast<ObjCCategoryDecl*>(Categories),
1196 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1197 // For extended class, unimplemented methods in its protocols will
1198 // be reported in the primary class.
1199 if (!C->IsClassExtension()) {
1200 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1201 E = C->protocol_end(); PI != E; ++PI)
1202 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1203 InsMap, ClsMap, CDecl);
1204 // Report unimplemented properties in the category as well.
1205 // When reporting on missing setter/getters, do not report when
1206 // setter/getter is implemented in category's primary class
1208 if (ObjCInterfaceDecl *ID = C->getClassInterface())
1209 if (ObjCImplDecl *IMP = ID->getImplementation()) {
1210 for (ObjCImplementationDecl::instmeth_iterator
1211 I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1212 InsMap.insert((*I)->getSelector());
1214 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
1217 assert(false && "invalid ObjCContainerDecl type.");
1220 /// ActOnForwardClassDeclaration -
1222 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1223 IdentifierInfo **IdentList,
1224 SourceLocation *IdentLocs,
1226 llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1228 for (unsigned i = 0; i != NumElts; ++i) {
1229 // Check for another declaration kind with the same name.
1231 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1232 LookupOrdinaryName, ForRedeclaration);
1233 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1234 // Maybe we will complain about the shadowed template parameter.
1235 DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1236 // Just pretend that we didn't see the previous declaration.
1240 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1241 // GCC apparently allows the following idiom:
1243 // typedef NSObject < XCElementTogglerP > XCElementToggler;
1244 // @class XCElementToggler;
1246 // FIXME: Make an extension?
1247 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
1248 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1249 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1250 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1252 // a forward class declaration matching a typedef name of a class refers
1253 // to the underlying class.
1254 if (const ObjCObjectType *OI =
1255 TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1256 PrevDecl = OI->getInterface();
1259 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1260 if (!IDecl) { // Not already seen? Make a forward decl.
1261 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1262 IdentList[i], IdentLocs[i], true);
1264 // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1265 // the current DeclContext. This prevents clients that walk DeclContext
1266 // from seeing the imaginary ObjCInterfaceDecl until it is actually
1267 // declared later (if at all). We also take care to explicitly make
1268 // sure this declaration is visible for name lookup.
1269 PushOnScopeChains(IDecl, TUScope, false);
1270 CurContext->makeDeclVisibleInContext(IDecl, true);
1273 Interfaces.push_back(IDecl);
1276 assert(Interfaces.size() == NumElts);
1277 ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1278 Interfaces.data(), IdentLocs,
1280 CurContext->addDecl(CDecl);
1281 CheckObjCDeclScope(CDecl);
1286 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1287 /// returns true, or false, accordingly.
1288 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1289 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1290 const ObjCMethodDecl *PrevMethod,
1291 bool matchBasedOnSizeAndAlignment,
1292 bool matchBasedOnStrictEqulity) {
1293 QualType T1 = Context.getCanonicalType(Method->getResultType());
1294 QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1297 // The result types are different.
1298 if (!matchBasedOnSizeAndAlignment || matchBasedOnStrictEqulity)
1300 // Incomplete types don't have a size and alignment.
1301 if (T1->isIncompleteType() || T2->isIncompleteType())
1303 // Check is based on size and alignment.
1304 if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1308 ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1309 E = Method->param_end();
1310 ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1312 for (; ParamI != E; ++ParamI, ++PrevI) {
1313 assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1314 T1 = Context.getCanonicalType((*ParamI)->getType());
1315 T2 = Context.getCanonicalType((*PrevI)->getType());
1317 // The result types are different.
1318 if (!matchBasedOnSizeAndAlignment || matchBasedOnStrictEqulity)
1320 // Incomplete types don't have a size and alignment.
1321 if (T1->isIncompleteType() || T2->isIncompleteType())
1323 // Check is based on size and alignment.
1324 if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1331 /// \brief Read the contents of the method pool for a given selector from
1332 /// external storage.
1334 /// This routine should only be called once, when the method pool has no entry
1335 /// for this selector.
1336 Sema::GlobalMethodPool::iterator Sema::ReadMethodPool(Selector Sel) {
1337 assert(ExternalSource && "We need an external AST source");
1338 assert(MethodPool.find(Sel) == MethodPool.end() &&
1339 "Selector data already loaded into the method pool");
1341 // Read the method list from the external source.
1342 GlobalMethods Methods = ExternalSource->ReadMethodPool(Sel);
1344 return MethodPool.insert(std::make_pair(Sel, Methods)).first;
1347 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
1349 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
1350 if (Pos == MethodPool.end()) {
1352 Pos = ReadMethodPool(Method->getSelector());
1354 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
1355 GlobalMethods())).first;
1357 Method->setDefined(impl);
1358 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
1359 if (Entry.Method == 0) {
1360 // Haven't seen a method with this selector name yet - add it.
1361 Entry.Method = Method;
1366 // We've seen a method with this name, see if we have already seen this type
1368 for (ObjCMethodList *List = &Entry; List; List = List->Next)
1369 if (MatchTwoMethodDeclarations(Method, List->Method)) {
1370 ObjCMethodDecl *PrevObjCMethod = List->Method;
1371 PrevObjCMethod->setDefined(impl);
1372 // If a method is deprecated, push it in the global pool.
1373 // This is used for better diagnostics.
1374 if (Method->isDeprecated()) {
1375 if (!PrevObjCMethod->isDeprecated())
1376 List->Method = Method;
1378 // If new method is unavailable, push it into global pool
1379 // unless previous one is deprecated.
1380 if (Method->isUnavailable()) {
1381 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
1382 List->Method = Method;
1387 // We have a new signature for an existing method - add it.
1388 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1389 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1390 Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1393 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
1394 bool receiverIdOrClass,
1395 bool warn, bool instance) {
1396 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1397 if (Pos == MethodPool.end()) {
1399 Pos = ReadMethodPool(Sel);
1404 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
1406 bool strictSelectorMatch = receiverIdOrClass && warn &&
1407 (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
1409 Diagnostic::Ignored);
1410 if (warn && MethList.Method && MethList.Next) {
1411 bool issueWarning = false;
1412 if (strictSelectorMatch)
1413 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
1414 // This checks if the methods differ in type mismatch.
1415 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, false, true))
1416 issueWarning = true;
1420 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next) {
1421 // This checks if the methods differ by size & alignment.
1422 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1423 issueWarning = true;
1427 if (strictSelectorMatch)
1428 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
1430 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1431 Diag(MethList.Method->getLocStart(), diag::note_using)
1432 << MethList.Method->getSourceRange();
1433 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1434 Diag(Next->Method->getLocStart(), diag::note_also_found)
1435 << Next->Method->getSourceRange();
1438 return MethList.Method;
1441 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
1442 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
1443 if (Pos == MethodPool.end())
1446 GlobalMethods &Methods = Pos->second;
1448 if (Methods.first.Method && Methods.first.Method->isDefined())
1449 return Methods.first.Method;
1450 if (Methods.second.Method && Methods.second.Method->isDefined())
1451 return Methods.second.Method;
1455 /// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1456 /// identical selector names in current and its super classes and issues
1457 /// a warning if any of their argument types are incompatible.
1458 void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1459 ObjCMethodDecl *Method,
1461 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1462 if (ID == 0) return;
1464 while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1465 ObjCMethodDecl *SuperMethodDecl =
1466 SD->lookupMethod(Method->getSelector(), IsInstance);
1467 if (SuperMethodDecl == 0) {
1471 ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1472 E = Method->param_end();
1473 ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1474 for (; ParamI != E; ++ParamI, ++PrevI) {
1475 // Number of parameters are the same and is guaranteed by selector match.
1476 assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1477 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1478 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1479 // If type of argument of method in this class does not match its
1480 // respective argument type in the super class method, issue warning;
1481 if (!Context.typesAreCompatible(T1, T2)) {
1482 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1484 Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1492 /// DiagnoseDuplicateIvars -
1493 /// Check for duplicate ivars in the entire class at the start of
1494 /// @implementation. This becomes necesssary because class extension can
1495 /// add ivars to a class in random order which will not be known until
1496 /// class's @implementation is seen.
1497 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
1498 ObjCInterfaceDecl *SID) {
1499 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
1500 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
1501 ObjCIvarDecl* Ivar = (*IVI);
1502 if (Ivar->isInvalidDecl())
1504 if (IdentifierInfo *II = Ivar->getIdentifier()) {
1505 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
1507 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
1508 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
1509 Ivar->setInvalidDecl();
1515 // Note: For class/category implemenations, allMethods/allProperties is
1517 void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
1519 Decl **allMethods, unsigned allNum,
1520 Decl **allProperties, unsigned pNum,
1521 DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1522 // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1523 // always passing in a decl. If the decl has an error, isInvalidDecl()
1528 bool isInterfaceDeclKind =
1529 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1530 || isa<ObjCProtocolDecl>(ClassDecl);
1531 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1533 if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1534 // FIXME: This is wrong. We shouldn't be pretending that there is
1535 // an '@end' in the declaration.
1536 SourceLocation L = ClassDecl->getLocation();
1539 Diag(L, diag::err_missing_atend);
1542 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1543 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1544 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1546 for (unsigned i = 0; i < allNum; i++ ) {
1547 ObjCMethodDecl *Method =
1548 cast_or_null<ObjCMethodDecl>(allMethods[i]);
1550 if (!Method) continue; // Already issued a diagnostic.
1551 if (Method->isInstanceMethod()) {
1552 /// Check for instance method of the same name with incompatible types
1553 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1554 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1556 if ((isInterfaceDeclKind && PrevMethod && !match)
1557 || (checkIdenticalMethods && match)) {
1558 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1559 << Method->getDeclName();
1560 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1561 Method->setInvalidDecl();
1563 InsMap[Method->getSelector()] = Method;
1564 /// The following allows us to typecheck messages to "id".
1565 AddInstanceMethodToGlobalPool(Method);
1566 // verify that the instance method conforms to the same definition of
1567 // parent methods if it shadows one.
1568 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1571 /// Check for class method of the same name with incompatible types
1572 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1573 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1575 if ((isInterfaceDeclKind && PrevMethod && !match)
1576 || (checkIdenticalMethods && match)) {
1577 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1578 << Method->getDeclName();
1579 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1580 Method->setInvalidDecl();
1582 ClsMap[Method->getSelector()] = Method;
1583 /// The following allows us to typecheck messages to "Class".
1584 AddFactoryMethodToGlobalPool(Method);
1585 // verify that the class method conforms to the same definition of
1586 // parent methods if it shadows one.
1587 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1591 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1592 // Compares properties declared in this class to those of its
1594 ComparePropertiesInBaseAndSuper(I);
1595 CompareProperties(I, I);
1596 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1597 // Categories are used to extend the class by declaring new methods.
1598 // By the same token, they are also used to add new properties. No
1599 // need to compare the added property to those in the class.
1601 // Compare protocol properties with those in category
1602 CompareProperties(C, C);
1603 if (C->IsClassExtension()) {
1604 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
1605 DiagnoseClassExtensionDupMethods(C, CCPrimary);
1608 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1609 if (CDecl->getIdentifier())
1610 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1611 // user-defined setter/getter. It also synthesizes setter/getter methods
1612 // and adds them to the DeclContext and global method pools.
1613 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1614 E = CDecl->prop_end();
1616 ProcessPropertyDecl(*I, CDecl);
1617 CDecl->setAtEndRange(AtEnd);
1619 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1620 IC->setAtEndRange(AtEnd);
1621 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1622 // Any property declared in a class extension might have user
1623 // declared setter or getter in current class extension or one
1624 // of the other class extensions. Mark them as synthesized as
1625 // property will be synthesized when property with same name is
1626 // seen in the @implementation.
1627 for (const ObjCCategoryDecl *ClsExtDecl =
1628 IDecl->getFirstClassExtension();
1629 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
1630 for (ObjCContainerDecl::prop_iterator I = ClsExtDecl->prop_begin(),
1631 E = ClsExtDecl->prop_end(); I != E; ++I) {
1632 ObjCPropertyDecl *Property = (*I);
1633 // Skip over properties declared @dynamic
1634 if (const ObjCPropertyImplDecl *PIDecl
1635 = IC->FindPropertyImplDecl(Property->getIdentifier()))
1636 if (PIDecl->getPropertyImplementation()
1637 == ObjCPropertyImplDecl::Dynamic)
1640 for (const ObjCCategoryDecl *CExtDecl =
1641 IDecl->getFirstClassExtension();
1642 CExtDecl; CExtDecl = CExtDecl->getNextClassExtension()) {
1643 if (ObjCMethodDecl *GetterMethod =
1644 CExtDecl->getInstanceMethod(Property->getGetterName()))
1645 GetterMethod->setSynthesized(true);
1646 if (!Property->isReadOnly())
1647 if (ObjCMethodDecl *SetterMethod =
1648 CExtDecl->getInstanceMethod(Property->getSetterName()))
1649 SetterMethod->setSynthesized(true);
1654 if (LangOpts.ObjCDefaultSynthProperties &&
1655 LangOpts.ObjCNonFragileABI2)
1656 DefaultSynthesizeProperties(S, IC, IDecl);
1657 ImplMethodsVsClassMethods(S, IC, IDecl);
1658 AtomicPropertySetterGetterRules(IC, IDecl);
1660 if (LangOpts.ObjCNonFragileABI2)
1661 while (IDecl->getSuperClass()) {
1662 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
1663 IDecl = IDecl->getSuperClass();
1666 SetIvarInitializers(IC);
1667 } else if (ObjCCategoryImplDecl* CatImplClass =
1668 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1669 CatImplClass->setAtEndRange(AtEnd);
1671 // Find category interface decl and then check that all methods declared
1672 // in this interface are implemented in the category @implementation.
1673 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1674 for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1675 Categories; Categories = Categories->getNextClassCategory()) {
1676 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1677 ImplMethodsVsClassMethods(S, CatImplClass, Categories);
1683 if (isInterfaceDeclKind) {
1684 // Reject invalid vardecls.
1685 for (unsigned i = 0; i != tuvNum; i++) {
1686 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1687 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1688 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1689 if (!VDecl->hasExternalStorage())
1690 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1697 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1698 /// objective-c's type qualifier from the parser version of the same info.
1699 static Decl::ObjCDeclQualifier
1700 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1701 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
1705 bool containsInvalidMethodImplAttribute(const AttrVec &A) {
1706 // The 'ibaction' attribute is allowed on method definitions because of
1707 // how the IBAction macro is used on both method declarations and definitions.
1708 // If the method definitions contains any other attributes, return true.
1709 for (AttrVec::const_iterator i = A.begin(), e = A.end(); i != e; ++i)
1710 if ((*i)->getKind() != attr::IBAction)
1715 Decl *Sema::ActOnMethodDeclaration(
1717 SourceLocation MethodLoc, SourceLocation EndLoc,
1718 tok::TokenKind MethodType, Decl *ClassDecl,
1719 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
1721 // optional arguments. The number of types/arguments is obtained
1722 // from the Sel.getNumArgs().
1723 ObjCArgInfo *ArgInfo,
1724 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
1725 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1726 bool isVariadic, bool MethodDefinition) {
1727 // Make sure we can establish a context for the method.
1729 Diag(MethodLoc, diag::error_missing_method_context);
1732 QualType resultDeclType;
1734 TypeSourceInfo *ResultTInfo = 0;
1736 resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
1738 // Methods cannot return interface types. All ObjC objects are
1739 // passed by reference.
1740 if (resultDeclType->isObjCObjectType()) {
1741 Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1742 << 0 << resultDeclType;
1745 } else // get the type for "id".
1746 resultDeclType = Context.getObjCIdType();
1748 ObjCMethodDecl* ObjCMethod =
1749 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1751 cast<DeclContext>(ClassDecl),
1752 MethodType == tok::minus, isVariadic,
1754 MethodDeclKind == tok::objc_optional ?
1755 ObjCMethodDecl::Optional :
1756 ObjCMethodDecl::Required);
1758 llvm::SmallVector<ParmVarDecl*, 16> Params;
1760 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1764 if (ArgInfo[i].Type == 0) {
1765 ArgType = Context.getObjCIdType();
1768 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1769 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1770 ArgType = adjustParameterType(ArgType);
1773 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
1774 LookupOrdinaryName, ForRedeclaration);
1776 if (R.isSingleResult()) {
1777 NamedDecl *PrevDecl = R.getFoundDecl();
1778 if (S->isDeclScope(PrevDecl)) {
1779 Diag(ArgInfo[i].NameLoc,
1780 (MethodDefinition ? diag::warn_method_param_redefinition
1781 : diag::warn_method_param_declaration))
1783 Diag(PrevDecl->getLocation(),
1784 diag::note_previous_declaration);
1788 SourceLocation StartLoc = DI
1789 ? DI->getTypeLoc().getBeginLoc()
1790 : ArgInfo[i].NameLoc;
1792 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
1793 ArgInfo[i].NameLoc, ArgInfo[i].Name,
1794 ArgType, DI, SC_None, SC_None);
1796 Param->setObjCMethodScopeInfo(i);
1798 Param->setObjCDeclQualifier(
1799 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1801 // Apply the attributes to the parameter.
1802 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
1805 IdResolver.AddDecl(Param);
1807 Params.push_back(Param);
1810 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
1811 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
1812 QualType ArgType = Param->getType();
1813 if (ArgType.isNull())
1814 ArgType = Context.getObjCIdType();
1816 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1817 ArgType = adjustParameterType(ArgType);
1818 if (ArgType->isObjCObjectType()) {
1819 Diag(Param->getLocation(),
1820 diag::err_object_cannot_be_passed_returned_by_value)
1822 Param->setInvalidDecl();
1824 Param->setDeclContext(ObjCMethod);
1826 Params.push_back(Param);
1829 ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
1831 ObjCMethod->setObjCDeclQualifier(
1832 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1833 const ObjCMethodDecl *PrevMethod = 0;
1836 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
1838 const ObjCMethodDecl *InterfaceMD = 0;
1840 // Add the method now.
1841 if (ObjCImplementationDecl *ImpDecl =
1842 dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1843 if (MethodType == tok::minus) {
1844 PrevMethod = ImpDecl->getInstanceMethod(Sel);
1845 ImpDecl->addInstanceMethod(ObjCMethod);
1847 PrevMethod = ImpDecl->getClassMethod(Sel);
1848 ImpDecl->addClassMethod(ObjCMethod);
1850 InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
1851 MethodType == tok::minus);
1852 if (ObjCMethod->hasAttrs() &&
1853 containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
1854 Diag(EndLoc, diag::warn_attribute_method_def);
1855 } else if (ObjCCategoryImplDecl *CatImpDecl =
1856 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1857 if (MethodType == tok::minus) {
1858 PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1859 CatImpDecl->addInstanceMethod(ObjCMethod);
1861 PrevMethod = CatImpDecl->getClassMethod(Sel);
1862 CatImpDecl->addClassMethod(ObjCMethod);
1864 if (ObjCMethod->hasAttrs() &&
1865 containsInvalidMethodImplAttribute(ObjCMethod->getAttrs()))
1866 Diag(EndLoc, diag::warn_attribute_method_def);
1868 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
1871 // You can never have two method definitions with the same name.
1872 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1873 << ObjCMethod->getDeclName();
1874 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1877 // Merge information down from the interface declaration if we have one.
1879 mergeObjCMethodDecls(ObjCMethod, InterfaceMD);
1884 bool Sema::CheckObjCDeclScope(Decl *D) {
1885 if (isa<TranslationUnitDecl>(CurContext->getRedeclContext()))
1888 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1889 D->setInvalidDecl();
1894 /// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1895 /// instance variables of ClassName into Decls.
1896 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
1897 IdentifierInfo *ClassName,
1898 llvm::SmallVectorImpl<Decl*> &Decls) {
1899 // Check that ClassName is a valid class
1900 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
1902 Diag(DeclStart, diag::err_undef_interface) << ClassName;
1905 if (LangOpts.ObjCNonFragileABI) {
1906 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
1910 // Collect the instance variables
1911 llvm::SmallVector<ObjCIvarDecl*, 32> Ivars;
1912 Context.DeepCollectObjCIvars(Class, true, Ivars);
1913 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1914 for (unsigned i = 0; i < Ivars.size(); i++) {
1915 FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
1916 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
1917 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
1918 /*FIXME: StartL=*/ID->getLocation(),
1920 ID->getIdentifier(), ID->getType(),
1922 Decls.push_back(FD);
1925 // Introduce all of these fields into the appropriate scope.
1926 for (llvm::SmallVectorImpl<Decl*>::iterator D = Decls.begin();
1927 D != Decls.end(); ++D) {
1928 FieldDecl *FD = cast<FieldDecl>(*D);
1929 if (getLangOptions().CPlusPlus)
1930 PushOnScopeChains(cast<FieldDecl>(FD), S);
1931 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
1932 Record->addDecl(FD);
1936 /// \brief Build a type-check a new Objective-C exception variable declaration.
1937 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
1938 SourceLocation StartLoc,
1939 SourceLocation IdLoc,
1942 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
1943 // duration shall not be qualified by an address-space qualifier."
1944 // Since all parameters have automatic store duration, they can not have
1945 // an address space.
1946 if (T.getAddressSpace() != 0) {
1947 Diag(IdLoc, diag::err_arg_with_address_space);
1951 // An @catch parameter must be an unqualified object pointer type;
1952 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
1954 // Don't do any further checking.
1955 } else if (T->isDependentType()) {
1956 // Okay: we don't know what this type will instantiate to.
1957 } else if (!T->isObjCObjectPointerType()) {
1959 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
1960 } else if (T->isObjCQualifiedIdType()) {
1962 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
1965 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
1966 T, TInfo, SC_None, SC_None);
1967 New->setExceptionVariable(true);
1970 New->setInvalidDecl();
1974 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
1975 const DeclSpec &DS = D.getDeclSpec();
1977 // We allow the "register" storage class on exception variables because
1978 // GCC did, but we drop it completely. Any other storage class is an error.
1979 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1980 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
1981 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
1982 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
1983 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
1984 << DS.getStorageClassSpec();
1986 if (D.getDeclSpec().isThreadSpecified())
1987 Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
1988 D.getMutableDeclSpec().ClearStorageClassSpecs();
1990 DiagnoseFunctionSpecifiers(D);
1992 // Check that there are no default arguments inside the type of this
1993 // exception object (C++ only).
1994 if (getLangOptions().CPlusPlus)
1995 CheckExtraCXXDefaultArguments(D);
1997 TagDecl *OwnedDecl = 0;
1998 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
1999 QualType ExceptionType = TInfo->getType();
2001 if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
2002 // Objective-C++: Types shall not be defined in exception types.
2003 Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
2004 << Context.getTypeDeclType(OwnedDecl);
2007 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
2008 D.getSourceRange().getBegin(),
2009 D.getIdentifierLoc(),
2013 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2014 if (D.getCXXScopeSpec().isSet()) {
2015 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
2016 << D.getCXXScopeSpec().getRange();
2017 New->setInvalidDecl();
2020 // Add the parameter declaration into this scope.
2022 if (D.getIdentifier())
2023 IdResolver.AddDecl(New);
2025 ProcessDeclAttributes(S, New, D);
2027 if (New->hasAttr<BlocksAttr>())
2028 Diag(New->getLocation(), diag::err_block_on_nonlocal);
2032 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
2034 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
2035 llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
2036 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
2037 Iv= Iv->getNextIvar()) {
2038 QualType QT = Context.getBaseElementType(Iv->getType());
2039 if (QT->isRecordType())
2040 Ivars.push_back(Iv);
2044 void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
2045 CXXCtorInitializer ** initializers,
2046 unsigned numInitializers) {
2047 if (numInitializers > 0) {
2048 NumIvarInitializers = numInitializers;
2049 CXXCtorInitializer **ivarInitializers =
2050 new (C) CXXCtorInitializer*[NumIvarInitializers];
2051 memcpy(ivarInitializers, initializers,
2052 numInitializers * sizeof(CXXCtorInitializer*));
2053 IvarInitializers = ivarInitializers;
2057 void Sema::DiagnoseUseOfUnimplementedSelectors() {
2058 // Warning will be issued only when selector table is
2059 // generated (which means there is at lease one implementation
2060 // in the TU). This is to match gcc's behavior.
2061 if (ReferencedSelectors.empty() ||
2062 !Context.AnyObjCImplementation())
2064 for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
2065 ReferencedSelectors.begin(),
2066 E = ReferencedSelectors.end(); S != E; ++S) {
2067 Selector Sel = (*S).first;
2068 if (!LookupImplementedMethodInGlobalPool(Sel))
2069 Diag((*S).second, diag::warn_unimplemented_selector) << Sel;