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 //===----------------------------------------------------------------------===//
16 #include "clang/Sema/ExternalSemaSource.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/Parse/DeclSpec.h"
21 using namespace clang;
23 bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property,
24 ObjCMethodDecl *GetterMethod,
27 GetterMethod->getResultType() != property->getType()) {
28 AssignConvertType result = Incompatible;
29 if (property->getType()->isObjCObjectPointerType())
30 result = CheckAssignmentConstraints(GetterMethod->getResultType(), property->getType());
31 if (result != Compatible) {
32 Diag(Loc, diag::warn_accessor_property_type_mismatch)
33 << property->getDeclName()
34 << GetterMethod->getSelector();
35 Diag(GetterMethod->getLocation(), diag::note_declared_at);
42 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
43 /// and user declared, in the method definition's AST.
44 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) {
45 assert(getCurMethodDecl() == 0 && "Method parsing confused");
46 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D.getAs<Decl>());
48 // If we don't have a valid method decl, simply return.
52 CurFunctionNeedsScopeChecking = false;
54 // Allow the rest of sema to find private method decl implementations.
55 if (MDecl->isInstanceMethod())
56 AddInstanceMethodToGlobalPool(MDecl);
58 AddFactoryMethodToGlobalPool(MDecl);
60 // Allow all of Sema to see that we are entering a method definition.
61 PushDeclContext(FnBodyScope, MDecl);
63 // Create Decl objects for each parameter, entrring them in the scope for
64 // binding to their use.
66 // Insert the invisible arguments, self and _cmd!
67 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
69 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
70 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
72 // Introduce all of the other parameters into this scope.
73 for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
74 E = MDecl->param_end(); PI != E; ++PI)
75 if ((*PI)->getIdentifier())
76 PushOnScopeChains(*PI, FnBodyScope);
79 Sema::DeclPtrTy Sema::
80 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
81 IdentifierInfo *ClassName, SourceLocation ClassLoc,
82 IdentifierInfo *SuperName, SourceLocation SuperLoc,
83 const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs,
84 const SourceLocation *ProtoLocs,
85 SourceLocation EndProtoLoc, AttributeList *AttrList) {
86 assert(ClassName && "Missing class identifier");
88 // Check for another declaration kind with the same name.
89 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
90 if (PrevDecl && PrevDecl->isTemplateParameter()) {
91 // Maybe we will complain about the shadowed template parameter.
92 DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
93 // Just pretend that we didn't see the previous declaration.
97 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
98 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
99 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
102 ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
104 // Class already seen. Is it a forward declaration?
105 if (!IDecl->isForwardDecl()) {
106 IDecl->setInvalidDecl();
107 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
108 Diag(IDecl->getLocation(), diag::note_previous_definition);
110 // Return the previous class interface.
111 // FIXME: don't leak the objects passed in!
112 return DeclPtrTy::make(IDecl);
114 IDecl->setLocation(AtInterfaceLoc);
115 IDecl->setForwardDecl(false);
116 IDecl->setClassLoc(ClassLoc);
118 // Since this ObjCInterfaceDecl was created by a forward declaration,
119 // we now add it to the DeclContext since it wasn't added before
120 // (see ActOnForwardClassDeclaration).
121 CurContext->addDecl(IDecl);
124 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
127 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
128 ClassName, ClassLoc);
130 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
132 PushOnScopeChains(IDecl, TUScope);
136 // Check if a different kind of symbol declared in this scope.
137 PrevDecl = LookupSingleName(TUScope, SuperName, LookupOrdinaryName);
140 // Try to correct for a typo in the superclass name.
141 LookupResult R(*this, SuperName, SuperLoc, LookupOrdinaryName);
142 if (CorrectTypo(R, TUScope, 0) &&
143 (PrevDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
144 Diag(SuperLoc, diag::err_undef_superclass_suggest)
145 << SuperName << ClassName << PrevDecl->getDeclName();
146 Diag(PrevDecl->getLocation(), diag::note_previous_decl)
147 << PrevDecl->getDeclName();
151 if (PrevDecl == IDecl) {
152 Diag(SuperLoc, diag::err_recursive_superclass)
153 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
154 IDecl->setLocEnd(ClassLoc);
156 ObjCInterfaceDecl *SuperClassDecl =
157 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
159 // Diagnose classes that inherit from deprecated classes.
161 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
163 if (PrevDecl && SuperClassDecl == 0) {
164 // The previous declaration was not a class decl. Check if we have a
165 // typedef. If we do, get the underlying class type.
166 if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
167 QualType T = TDecl->getUnderlyingType();
168 if (T->isObjCInterfaceType()) {
169 if (NamedDecl *IDecl = T->getAs<ObjCInterfaceType>()->getDecl())
170 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
174 // This handles the following case:
176 // typedef int SuperClass;
177 // @interface MyClass : SuperClass {} @end
179 if (!SuperClassDecl) {
180 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
181 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
185 if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
187 Diag(SuperLoc, diag::err_undef_superclass)
188 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
189 else if (SuperClassDecl->isForwardDecl())
190 Diag(SuperLoc, diag::err_undef_superclass)
191 << SuperClassDecl->getDeclName() << ClassName
192 << SourceRange(AtInterfaceLoc, ClassLoc);
194 IDecl->setSuperClass(SuperClassDecl);
195 IDecl->setSuperClassLoc(SuperLoc);
196 IDecl->setLocEnd(SuperLoc);
198 } else { // we have a root class.
199 IDecl->setLocEnd(ClassLoc);
202 /// Check then save referenced protocols.
204 IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
206 IDecl->setLocEnd(EndProtoLoc);
209 CheckObjCDeclScope(IDecl);
210 return DeclPtrTy::make(IDecl);
213 /// ActOnCompatiblityAlias - this action is called after complete parsing of
214 /// @compatibility_alias declaration. It sets up the alias relationships.
215 Sema::DeclPtrTy Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
216 IdentifierInfo *AliasName,
217 SourceLocation AliasLocation,
218 IdentifierInfo *ClassName,
219 SourceLocation ClassLocation) {
220 // Look for previous declaration of alias name
221 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
223 if (isa<ObjCCompatibleAliasDecl>(ADecl))
224 Diag(AliasLocation, diag::warn_previous_alias_decl);
226 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
227 Diag(ADecl->getLocation(), diag::note_previous_declaration);
230 // Check for class declaration
231 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
232 if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
233 QualType T = TDecl->getUnderlyingType();
234 if (T->isObjCInterfaceType()) {
235 if (NamedDecl *IDecl = T->getAs<ObjCInterfaceType>()->getDecl()) {
236 ClassName = IDecl->getIdentifier();
237 CDeclU = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
241 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
243 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
245 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
249 // Everything checked out, instantiate a new alias declaration AST.
250 ObjCCompatibleAliasDecl *AliasDecl =
251 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
253 if (!CheckObjCDeclScope(AliasDecl))
254 PushOnScopeChains(AliasDecl, TUScope);
256 return DeclPtrTy::make(AliasDecl);
259 void Sema::CheckForwardProtocolDeclarationForCircularDependency(
260 IdentifierInfo *PName,
261 SourceLocation &Ploc, SourceLocation PrevLoc,
262 const ObjCList<ObjCProtocolDecl> &PList) {
263 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
264 E = PList.end(); I != E; ++I) {
266 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier())) {
267 if (PDecl->getIdentifier() == PName) {
268 Diag(Ploc, diag::err_protocol_has_circular_dependency);
269 Diag(PrevLoc, diag::note_previous_definition);
271 CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
272 PDecl->getLocation(), PDecl->getReferencedProtocols());
278 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
279 IdentifierInfo *ProtocolName,
280 SourceLocation ProtocolLoc,
281 const DeclPtrTy *ProtoRefs,
282 unsigned NumProtoRefs,
283 const SourceLocation *ProtoLocs,
284 SourceLocation EndProtoLoc,
285 AttributeList *AttrList) {
286 // FIXME: Deal with AttrList.
287 assert(ProtocolName && "Missing protocol identifier");
288 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName);
290 // Protocol already seen. Better be a forward protocol declaration
291 if (!PDecl->isForwardDecl()) {
292 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
293 Diag(PDecl->getLocation(), diag::note_previous_definition);
294 // Just return the protocol we already had.
295 // FIXME: don't leak the objects passed in!
296 return DeclPtrTy::make(PDecl);
298 ObjCList<ObjCProtocolDecl> PList;
299 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
300 CheckForwardProtocolDeclarationForCircularDependency(
301 ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
302 PList.Destroy(Context);
304 // Make sure the cached decl gets a valid start location.
305 PDecl->setLocation(AtProtoInterfaceLoc);
306 PDecl->setForwardDecl(false);
308 PDecl = ObjCProtocolDecl::Create(Context, CurContext,
309 AtProtoInterfaceLoc,ProtocolName);
310 PushOnScopeChains(PDecl, TUScope);
311 PDecl->setForwardDecl(false);
314 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
316 /// Check then save referenced protocols.
317 PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
319 PDecl->setLocEnd(EndProtoLoc);
322 CheckObjCDeclScope(PDecl);
323 return DeclPtrTy::make(PDecl);
326 /// FindProtocolDeclaration - This routine looks up protocols and
327 /// issues an error if they are not declared. It returns list of
328 /// protocol declarations in its 'Protocols' argument.
330 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
331 const IdentifierLocPair *ProtocolId,
332 unsigned NumProtocols,
333 llvm::SmallVectorImpl<DeclPtrTy> &Protocols) {
334 for (unsigned i = 0; i != NumProtocols; ++i) {
335 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first);
337 LookupResult R(*this, ProtocolId[i].first, ProtocolId[i].second,
338 LookupObjCProtocolName);
339 if (CorrectTypo(R, TUScope, 0) &&
340 (PDecl = R.getAsSingle<ObjCProtocolDecl>())) {
341 Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
342 << ProtocolId[i].first << R.getLookupName();
343 Diag(PDecl->getLocation(), diag::note_previous_decl)
344 << PDecl->getDeclName();
349 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
350 << ProtocolId[i].first;
354 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
356 // If this is a forward declaration and we are supposed to warn in this
358 if (WarnOnDeclarations && PDecl->isForwardDecl())
359 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
360 << ProtocolId[i].first;
361 Protocols.push_back(DeclPtrTy::make(PDecl));
365 /// DiagnosePropertyMismatch - Compares two properties for their
366 /// attributes and types and warns on a variety of inconsistencies.
369 Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
370 ObjCPropertyDecl *SuperProperty,
371 const IdentifierInfo *inheritedName) {
372 ObjCPropertyDecl::PropertyAttributeKind CAttr =
373 Property->getPropertyAttributes();
374 ObjCPropertyDecl::PropertyAttributeKind SAttr =
375 SuperProperty->getPropertyAttributes();
376 if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
377 && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
378 Diag(Property->getLocation(), diag::warn_readonly_property)
379 << Property->getDeclName() << inheritedName;
380 if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
381 != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
382 Diag(Property->getLocation(), diag::warn_property_attribute)
383 << Property->getDeclName() << "copy" << inheritedName;
384 else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
385 != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
386 Diag(Property->getLocation(), diag::warn_property_attribute)
387 << Property->getDeclName() << "retain" << inheritedName;
389 if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
390 != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
391 Diag(Property->getLocation(), diag::warn_property_attribute)
392 << Property->getDeclName() << "atomic" << inheritedName;
393 if (Property->getSetterName() != SuperProperty->getSetterName())
394 Diag(Property->getLocation(), diag::warn_property_attribute)
395 << Property->getDeclName() << "setter" << inheritedName;
396 if (Property->getGetterName() != SuperProperty->getGetterName())
397 Diag(Property->getLocation(), diag::warn_property_attribute)
398 << Property->getDeclName() << "getter" << inheritedName;
401 Context.getCanonicalType(SuperProperty->getType());
403 Context.getCanonicalType(Property->getType());
405 if (!Context.typesAreCompatible(LHSType, RHSType)) {
406 // FIXME: Incorporate this test with typesAreCompatible.
407 if (LHSType->isObjCQualifiedIdType() && RHSType->isObjCQualifiedIdType())
408 if (Context.ObjCQualifiedIdTypesAreCompatible(LHSType, RHSType, false))
410 Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
411 << Property->getType() << SuperProperty->getType() << inheritedName;
415 /// ComparePropertiesInBaseAndSuper - This routine compares property
416 /// declarations in base and its super class, if any, and issues
417 /// diagnostics in a variety of inconsistant situations.
419 void Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
420 ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
424 for (ObjCInterfaceDecl::prop_iterator S = SDecl->prop_begin(),
425 E = SDecl->prop_end(); S != E; ++S) {
426 ObjCPropertyDecl *SuperPDecl = (*S);
427 // Does property in super class has declaration in current class?
428 for (ObjCInterfaceDecl::prop_iterator I = IDecl->prop_begin(),
429 E = IDecl->prop_end(); I != E; ++I) {
430 ObjCPropertyDecl *PDecl = (*I);
431 if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
432 DiagnosePropertyMismatch(PDecl, SuperPDecl,
433 SDecl->getIdentifier());
438 /// MatchOneProtocolPropertiesInClass - This routine goes thru the list
439 /// of properties declared in a protocol and compares their attribute against
440 /// the same property declared in the class or category.
442 Sema::MatchOneProtocolPropertiesInClass(Decl *CDecl,
443 ObjCProtocolDecl *PDecl) {
444 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
447 ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
448 assert (CatDecl && "MatchOneProtocolPropertiesInClass");
449 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
450 E = PDecl->prop_end(); P != E; ++P) {
451 ObjCPropertyDecl *Pr = (*P);
452 ObjCCategoryDecl::prop_iterator CP, CE;
453 // Is this property already in category's list of properties?
454 for (CP = CatDecl->prop_begin(), CE = CatDecl->prop_end(); CP != CE; ++CP)
455 if ((*CP)->getIdentifier() == Pr->getIdentifier())
458 // Property protocol already exist in class. Diagnose any mismatch.
459 DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
463 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
464 E = PDecl->prop_end(); P != E; ++P) {
465 ObjCPropertyDecl *Pr = (*P);
466 ObjCInterfaceDecl::prop_iterator CP, CE;
467 // Is this property already in class's list of properties?
468 for (CP = IDecl->prop_begin(), CE = IDecl->prop_end(); CP != CE; ++CP)
469 if ((*CP)->getIdentifier() == Pr->getIdentifier())
472 // Property protocol already exist in class. Diagnose any mismatch.
473 DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
477 /// CompareProperties - This routine compares properties
478 /// declared in 'ClassOrProtocol' objects (which can be a class or an
479 /// inherited protocol with the list of properties for class/category 'CDecl'
481 void Sema::CompareProperties(Decl *CDecl,
482 DeclPtrTy ClassOrProtocol) {
483 Decl *ClassDecl = ClassOrProtocol.getAs<Decl>();
484 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
488 ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
489 assert (CatDecl && "CompareProperties");
490 if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
491 for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
492 E = MDecl->protocol_end(); P != E; ++P)
493 // Match properties of category with those of protocol (*P)
494 MatchOneProtocolPropertiesInClass(CatDecl, *P);
496 // Go thru the list of protocols for this category and recursively match
497 // their properties with those in the category.
498 for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
499 E = CatDecl->protocol_end(); P != E; ++P)
500 CompareProperties(CatDecl, DeclPtrTy::make(*P));
502 ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
503 for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
504 E = MD->protocol_end(); P != E; ++P)
505 MatchOneProtocolPropertiesInClass(CatDecl, *P);
510 if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
511 for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
512 E = MDecl->protocol_end(); P != E; ++P)
513 // Match properties of class IDecl with those of protocol (*P).
514 MatchOneProtocolPropertiesInClass(IDecl, *P);
516 // Go thru the list of protocols for this class and recursively match
517 // their properties with those declared in the class.
518 for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
519 E = IDecl->protocol_end(); P != E; ++P)
520 CompareProperties(IDecl, DeclPtrTy::make(*P));
522 ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
523 for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
524 E = MD->protocol_end(); P != E; ++P)
525 MatchOneProtocolPropertiesInClass(IDecl, *P);
529 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
530 /// a class method in its extension.
532 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
533 ObjCInterfaceDecl *ID) {
535 return; // Possibly due to previous error
537 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
538 for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
539 e = ID->meth_end(); i != e; ++i) {
540 ObjCMethodDecl *MD = *i;
541 MethodMap[MD->getSelector()] = MD;
544 if (MethodMap.empty())
546 for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
547 e = CAT->meth_end(); i != e; ++i) {
548 ObjCMethodDecl *Method = *i;
549 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
550 if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
551 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
552 << Method->getDeclName();
553 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
558 /// ActOnForwardProtocolDeclaration - Handle @protocol foo;
560 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
561 const IdentifierLocPair *IdentList,
563 AttributeList *attrList) {
564 llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
565 llvm::SmallVector<SourceLocation, 8> ProtoLocs;
567 for (unsigned i = 0; i != NumElts; ++i) {
568 IdentifierInfo *Ident = IdentList[i].first;
569 ObjCProtocolDecl *PDecl = LookupProtocol(Ident);
570 if (PDecl == 0) { // Not already seen?
571 PDecl = ObjCProtocolDecl::Create(Context, CurContext,
572 IdentList[i].second, Ident);
573 PushOnScopeChains(PDecl, TUScope);
576 ProcessDeclAttributeList(TUScope, PDecl, attrList);
577 Protocols.push_back(PDecl);
578 ProtoLocs.push_back(IdentList[i].second);
581 ObjCForwardProtocolDecl *PDecl =
582 ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
583 Protocols.data(), Protocols.size(),
585 CurContext->addDecl(PDecl);
586 CheckObjCDeclScope(PDecl);
587 return DeclPtrTy::make(PDecl);
590 Sema::DeclPtrTy Sema::
591 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
592 IdentifierInfo *ClassName, SourceLocation ClassLoc,
593 IdentifierInfo *CategoryName,
594 SourceLocation CategoryLoc,
595 const DeclPtrTy *ProtoRefs,
596 unsigned NumProtoRefs,
597 const SourceLocation *ProtoLocs,
598 SourceLocation EndProtoLoc) {
599 ObjCCategoryDecl *CDecl =
600 ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, ClassLoc,
601 CategoryLoc, CategoryName);
602 // FIXME: PushOnScopeChains?
603 CurContext->addDecl(CDecl);
605 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc);
606 /// Check that class of this category is already completely declared.
607 if (!IDecl || IDecl->isForwardDecl()) {
608 CDecl->setInvalidDecl();
609 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
610 return DeclPtrTy::make(CDecl);
613 CDecl->setClassInterface(IDecl);
615 // If the interface is deprecated, warn about it.
616 (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
618 /// Check for duplicate interface declaration for this category
619 ObjCCategoryDecl *CDeclChain;
620 for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
621 CDeclChain = CDeclChain->getNextClassCategory()) {
622 if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
623 Diag(CategoryLoc, diag::warn_dup_category_def)
624 << ClassName << CategoryName;
625 Diag(CDeclChain->getLocation(), diag::note_previous_definition);
630 CDecl->insertNextClassCategory();
633 CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
635 // Protocols in the class extension belong to the class.
636 if (!CDecl->getIdentifier())
637 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
638 NumProtoRefs, ProtoLocs,
642 CheckObjCDeclScope(CDecl);
643 return DeclPtrTy::make(CDecl);
646 /// ActOnStartCategoryImplementation - Perform semantic checks on the
647 /// category implementation declaration and build an ObjCCategoryImplDecl
649 Sema::DeclPtrTy Sema::ActOnStartCategoryImplementation(
650 SourceLocation AtCatImplLoc,
651 IdentifierInfo *ClassName, SourceLocation ClassLoc,
652 IdentifierInfo *CatName, SourceLocation CatLoc) {
653 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc);
654 ObjCCategoryDecl *CatIDecl = 0;
656 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
658 // Category @implementation with no corresponding @interface.
659 // Create and install one.
660 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
661 SourceLocation(), SourceLocation(),
663 CatIDecl->setClassInterface(IDecl);
664 CatIDecl->insertNextClassCategory();
668 ObjCCategoryImplDecl *CDecl =
669 ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
671 /// Check that class of this category is already completely declared.
672 if (!IDecl || IDecl->isForwardDecl())
673 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
675 // FIXME: PushOnScopeChains?
676 CurContext->addDecl(CDecl);
678 /// Check that CatName, category name, is not used in another implementation.
680 if (CatIDecl->getImplementation()) {
681 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
683 Diag(CatIDecl->getImplementation()->getLocation(),
684 diag::note_previous_definition);
686 CatIDecl->setImplementation(CDecl);
689 CheckObjCDeclScope(CDecl);
690 return DeclPtrTy::make(CDecl);
693 Sema::DeclPtrTy Sema::ActOnStartClassImplementation(
694 SourceLocation AtClassImplLoc,
695 IdentifierInfo *ClassName, SourceLocation ClassLoc,
696 IdentifierInfo *SuperClassname,
697 SourceLocation SuperClassLoc) {
698 ObjCInterfaceDecl* IDecl = 0;
699 // Check for another declaration kind with the same name.
701 = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
702 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
703 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
704 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
705 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
706 // If this is a forward declaration of an interface, warn.
707 if (IDecl->isForwardDecl()) {
708 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
712 // We did not find anything with the name ClassName; try to correct for
713 // typos in the class name.
714 LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
715 if (CorrectTypo(R, TUScope, 0) &&
716 (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
717 // Suggest the (potentially) correct interface name. However, put the
718 // fix-it hint itself in a separate note, since changing the name in
719 // the warning would make the fix-it change semantics.However, don't
720 // provide a code-modification hint or use the typo name for recovery,
721 // because this is just a warning. The program may actually be correct.
722 Diag(ClassLoc, diag::warn_undef_interface_suggest)
723 << ClassName << R.getLookupName();
724 Diag(IDecl->getLocation(), diag::note_previous_decl)
726 << CodeModificationHint::CreateReplacement(ClassLoc,
727 R.getLookupName().getAsString());
730 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
734 // Check that super class name is valid class name
735 ObjCInterfaceDecl* SDecl = 0;
736 if (SuperClassname) {
737 // Check if a different kind of symbol declared in this scope.
738 PrevDecl = LookupSingleName(TUScope, SuperClassname, LookupOrdinaryName);
739 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
740 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
742 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
744 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
746 Diag(SuperClassLoc, diag::err_undef_superclass)
747 << SuperClassname << ClassName;
748 else if (IDecl && IDecl->getSuperClass() != SDecl) {
749 // This implementation and its interface do not have the same
751 Diag(SuperClassLoc, diag::err_conflicting_super_class)
752 << SDecl->getDeclName();
753 Diag(SDecl->getLocation(), diag::note_previous_definition);
759 // Legacy case of @implementation with no corresponding @interface.
760 // Build, chain & install the interface decl into the identifier.
762 // FIXME: Do we support attributes on the @implementation? If so we should
764 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
765 ClassName, ClassLoc, false, true);
766 IDecl->setSuperClass(SDecl);
767 IDecl->setLocEnd(ClassLoc);
769 PushOnScopeChains(IDecl, TUScope);
771 // Mark the interface as being completed, even if it was just as
773 // declaration; the user cannot reopen it.
774 IDecl->setForwardDecl(false);
777 ObjCImplementationDecl* IMPDecl =
778 ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
781 if (CheckObjCDeclScope(IMPDecl))
782 return DeclPtrTy::make(IMPDecl);
784 // Check that there is no duplicate implementation of this class.
785 if (IDecl->getImplementation()) {
786 // FIXME: Don't leak everything!
787 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
788 Diag(IDecl->getImplementation()->getLocation(),
789 diag::note_previous_definition);
790 } else { // add it to the list.
791 IDecl->setImplementation(IMPDecl);
792 PushOnScopeChains(IMPDecl, TUScope);
794 return DeclPtrTy::make(IMPDecl);
797 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
798 ObjCIvarDecl **ivars, unsigned numIvars,
799 SourceLocation RBrace) {
800 assert(ImpDecl && "missing implementation decl");
801 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
804 /// Check case of non-existing @interface decl.
805 /// (legacy objective-c @implementation decl without an @interface decl).
806 /// Add implementations's ivar to the synthesize class's ivar list.
807 if (IDecl->isImplicitInterfaceDecl()) {
808 IDecl->setIVarList(ivars, numIvars, Context);
809 IDecl->setLocEnd(RBrace);
812 // If implementation has empty ivar list, just return.
816 assert(ivars && "missing @implementation ivars");
818 // Check interface's Ivar list against those in the implementation.
819 // names and types must match.
822 ObjCInterfaceDecl::ivar_iterator
823 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
824 for (; numIvars > 0 && IVI != IVE; ++IVI) {
825 ObjCIvarDecl* ImplIvar = ivars[j++];
826 ObjCIvarDecl* ClsIvar = *IVI;
827 assert (ImplIvar && "missing implementation ivar");
828 assert (ClsIvar && "missing class ivar");
830 // First, make sure the types match.
831 if (Context.getCanonicalType(ImplIvar->getType()) !=
832 Context.getCanonicalType(ClsIvar->getType())) {
833 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
834 << ImplIvar->getIdentifier()
835 << ImplIvar->getType() << ClsIvar->getType();
836 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
837 } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
838 Expr *ImplBitWidth = ImplIvar->getBitWidth();
839 Expr *ClsBitWidth = ClsIvar->getBitWidth();
840 if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
841 ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
842 Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
843 << ImplIvar->getIdentifier();
844 Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
847 // Make sure the names are identical.
848 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
849 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
850 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
851 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
857 Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
859 Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
862 void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
863 bool &IncompleteImpl) {
864 if (!IncompleteImpl) {
865 Diag(ImpLoc, diag::warn_incomplete_impl);
866 IncompleteImpl = true;
868 Diag(ImpLoc, diag::warn_undef_method_impl) << method->getDeclName();
871 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
872 ObjCMethodDecl *IntfMethodDecl) {
873 if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(),
874 ImpMethodDecl->getResultType()) &&
875 !Context.QualifiedIdConformsQualifiedId(IntfMethodDecl->getResultType(),
876 ImpMethodDecl->getResultType())) {
877 Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types)
878 << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType()
879 << ImpMethodDecl->getResultType();
880 Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
883 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
884 IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
885 IM != EM; ++IM, ++IF) {
886 QualType ParmDeclTy = (*IF)->getType().getUnqualifiedType();
887 QualType ParmImpTy = (*IM)->getType().getUnqualifiedType();
888 if (Context.typesAreCompatible(ParmDeclTy, ParmImpTy) ||
889 Context.QualifiedIdConformsQualifiedId(ParmDeclTy, ParmImpTy))
892 Diag((*IM)->getLocation(), diag::warn_conflicting_param_types)
893 << ImpMethodDecl->getDeclName() << (*IF)->getType()
895 Diag((*IF)->getLocation(), diag::note_previous_definition);
899 /// isPropertyReadonly - Return true if property is readonly, by searching
900 /// for the property in the class and in its categories and implementations
902 bool Sema::isPropertyReadonly(ObjCPropertyDecl *PDecl,
903 ObjCInterfaceDecl *IDecl) {
904 // by far the most common case.
905 if (!PDecl->isReadOnly())
907 // Even if property is ready only, if interface has a user defined setter,
908 // it is not considered read only.
909 if (IDecl->getInstanceMethod(PDecl->getSetterName()))
912 // Main class has the property as 'readonly'. Must search
913 // through the category list to see if the property's
914 // attribute has been over-ridden to 'readwrite'.
915 for (ObjCCategoryDecl *Category = IDecl->getCategoryList();
916 Category; Category = Category->getNextClassCategory()) {
917 // Even if property is ready only, if a category has a user defined setter,
918 // it is not considered read only.
919 if (Category->getInstanceMethod(PDecl->getSetterName()))
921 ObjCPropertyDecl *P =
922 Category->FindPropertyDeclaration(PDecl->getIdentifier());
923 if (P && !P->isReadOnly())
927 // Also, check for definition of a setter method in the implementation if
929 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurContext)) {
930 if (ObjCImplementationDecl *IMD =
931 dyn_cast<ObjCImplementationDecl>(OMD->getDeclContext())) {
932 if (IMD->getInstanceMethod(PDecl->getSetterName()))
934 } else if (ObjCCategoryImplDecl *CIMD =
935 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
936 if (CIMD->getInstanceMethod(PDecl->getSetterName()))
940 // Lastly, look through the implementation (if one is in scope).
941 if (ObjCImplementationDecl *ImpDecl = IDecl->getImplementation())
942 if (ImpDecl->getInstanceMethod(PDecl->getSetterName()))
944 // If all fails, look at the super class.
945 if (ObjCInterfaceDecl *SIDecl = IDecl->getSuperClass())
946 return isPropertyReadonly(PDecl, SIDecl);
950 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
951 /// improve the efficiency of selector lookups and type checking by associating
952 /// with each protocol / interface / category the flattened instance tables. If
953 /// we used an immutable set to keep the table then it wouldn't add significant
954 /// memory cost and it would be handy for lookups.
956 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
957 /// Declared in protocol, and those referenced by it.
958 void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
959 ObjCProtocolDecl *PDecl,
960 bool& IncompleteImpl,
961 const llvm::DenseSet<Selector> &InsMap,
962 const llvm::DenseSet<Selector> &ClsMap,
963 ObjCInterfaceDecl *IDecl) {
964 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
965 ObjCInterfaceDecl *NSIDecl = 0;
966 if (getLangOptions().NeXTRuntime) {
967 // check to see if class implements forwardInvocation method and objects
968 // of this class are derived from 'NSProxy' so that to forward requests
969 // from one object to another.
970 // Under such conditions, which means that every method possible is
971 // implemented in the class, we should not issue "Method definition not
973 // FIXME: Use a general GetUnarySelector method for this.
974 IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
975 Selector fISelector = Context.Selectors.getSelector(1, &II);
976 if (InsMap.count(fISelector))
977 // Is IDecl derived from 'NSProxy'? If so, no instance methods
978 // need be implemented in the implementation.
979 NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
982 // If a method lookup fails locally we still need to look and see if
983 // the method was implemented by a base class or an inherited
984 // protocol. This lookup is slow, but occurs rarely in correct code
985 // and otherwise would terminate in a warning.
987 // check unimplemented instance methods.
989 for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
990 E = PDecl->instmeth_end(); I != E; ++I) {
991 ObjCMethodDecl *method = *I;
992 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
993 !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
995 !Super->lookupInstanceMethod(method->getSelector()))) {
996 // Ugly, but necessary. Method declared in protcol might have
997 // have been synthesized due to a property declared in the class which
998 // uses the protocol.
999 ObjCMethodDecl *MethodInClass =
1000 IDecl->lookupInstanceMethod(method->getSelector());
1001 if (!MethodInClass || !MethodInClass->isSynthesized())
1002 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
1005 // check unimplemented class methods
1006 for (ObjCProtocolDecl::classmeth_iterator
1007 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1009 ObjCMethodDecl *method = *I;
1010 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1011 !ClsMap.count(method->getSelector()) &&
1012 (!Super || !Super->lookupClassMethod(method->getSelector())))
1013 WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
1015 // Check on this protocols's referenced protocols, recursively.
1016 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1017 E = PDecl->protocol_end(); PI != E; ++PI)
1018 CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
1021 /// MatchAllMethodDeclarations - Check methods declaraed in interface or
1022 /// or protocol against those declared in their implementations.
1024 void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
1025 const llvm::DenseSet<Selector> &ClsMap,
1026 llvm::DenseSet<Selector> &InsMapSeen,
1027 llvm::DenseSet<Selector> &ClsMapSeen,
1028 ObjCImplDecl* IMPDecl,
1029 ObjCContainerDecl* CDecl,
1030 bool &IncompleteImpl,
1031 bool ImmediateClass) {
1032 // Check and see if instance methods in class interface have been
1033 // implemented in the implementation class. If so, their types match.
1034 for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1035 E = CDecl->instmeth_end(); I != E; ++I) {
1036 if (InsMapSeen.count((*I)->getSelector()))
1038 InsMapSeen.insert((*I)->getSelector());
1039 if (!(*I)->isSynthesized() &&
1040 !InsMap.count((*I)->getSelector())) {
1042 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
1045 ObjCMethodDecl *ImpMethodDecl =
1046 IMPDecl->getInstanceMethod((*I)->getSelector());
1047 ObjCMethodDecl *IntfMethodDecl =
1048 CDecl->getInstanceMethod((*I)->getSelector());
1049 assert(IntfMethodDecl &&
1050 "IntfMethodDecl is null in ImplMethodsVsClassMethods");
1051 // ImpMethodDecl may be null as in a @dynamic property.
1053 WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
1057 // Check and see if class methods in class interface have been
1058 // implemented in the implementation class. If so, their types match.
1059 for (ObjCInterfaceDecl::classmeth_iterator
1060 I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
1061 if (ClsMapSeen.count((*I)->getSelector()))
1063 ClsMapSeen.insert((*I)->getSelector());
1064 if (!ClsMap.count((*I)->getSelector())) {
1066 WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
1068 ObjCMethodDecl *ImpMethodDecl =
1069 IMPDecl->getClassMethod((*I)->getSelector());
1070 ObjCMethodDecl *IntfMethodDecl =
1071 CDecl->getClassMethod((*I)->getSelector());
1072 WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
1075 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1076 // Check for any implementation of a methods declared in protocol.
1077 for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
1078 E = I->protocol_end(); PI != E; ++PI)
1079 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1081 (*PI), IncompleteImpl, false);
1082 if (I->getSuperClass())
1083 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1085 I->getSuperClass(), IncompleteImpl, false);
1089 /// CollectImmediateProperties - This routine collects all properties in
1090 /// the class and its conforming protocols; but not those it its super class.
1091 void Sema::CollectImmediateProperties(ObjCContainerDecl *CDecl,
1092 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>& PropMap) {
1093 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1094 for (ObjCContainerDecl::prop_iterator P = IDecl->prop_begin(),
1095 E = IDecl->prop_end(); P != E; ++P) {
1096 ObjCPropertyDecl *Prop = (*P);
1097 PropMap[Prop->getIdentifier()] = Prop;
1099 // scan through class's protocols.
1100 for (ObjCInterfaceDecl::protocol_iterator PI = IDecl->protocol_begin(),
1101 E = IDecl->protocol_end(); PI != E; ++PI)
1102 CollectImmediateProperties((*PI), PropMap);
1104 if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1105 for (ObjCContainerDecl::prop_iterator P = CATDecl->prop_begin(),
1106 E = CATDecl->prop_end(); P != E; ++P) {
1107 ObjCPropertyDecl *Prop = (*P);
1108 PropMap[Prop->getIdentifier()] = Prop;
1110 // scan through class's protocols.
1111 for (ObjCInterfaceDecl::protocol_iterator PI = CATDecl->protocol_begin(),
1112 E = CATDecl->protocol_end(); PI != E; ++PI)
1113 CollectImmediateProperties((*PI), PropMap);
1115 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1116 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1117 E = PDecl->prop_end(); P != E; ++P) {
1118 ObjCPropertyDecl *Prop = (*P);
1119 ObjCPropertyDecl *&PropEntry = PropMap[Prop->getIdentifier()];
1123 // scan through protocol's protocols.
1124 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1125 E = PDecl->protocol_end(); PI != E; ++PI)
1126 CollectImmediateProperties((*PI), PropMap);
1130 void Sema::DiagnoseUnimplementedProperties(ObjCImplDecl* IMPDecl,
1131 ObjCContainerDecl *CDecl,
1132 const llvm::DenseSet<Selector>& InsMap) {
1133 llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*> PropMap;
1134 CollectImmediateProperties(CDecl, PropMap);
1135 if (PropMap.empty())
1138 llvm::DenseSet<ObjCPropertyDecl *> PropImplMap;
1139 for (ObjCImplDecl::propimpl_iterator
1140 I = IMPDecl->propimpl_begin(),
1141 EI = IMPDecl->propimpl_end(); I != EI; ++I)
1142 PropImplMap.insert((*I)->getPropertyDecl());
1144 for (llvm::DenseMap<IdentifierInfo *, ObjCPropertyDecl*>::iterator
1145 P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
1146 ObjCPropertyDecl *Prop = P->second;
1147 // Is there a matching propery synthesize/dynamic?
1148 if (Prop->isInvalidDecl() ||
1149 Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
1150 PropImplMap.count(Prop))
1153 if (!InsMap.count(Prop->getGetterName())) {
1154 Diag(Prop->getLocation(),
1155 isa<ObjCCategoryDecl>(CDecl) ?
1156 diag::warn_setter_getter_impl_required_in_category :
1157 diag::warn_setter_getter_impl_required)
1158 << Prop->getDeclName() << Prop->getGetterName();
1159 Diag(IMPDecl->getLocation(),
1160 diag::note_property_impl_required);
1163 if (!Prop->isReadOnly() && !InsMap.count(Prop->getSetterName())) {
1164 Diag(Prop->getLocation(),
1165 isa<ObjCCategoryDecl>(CDecl) ?
1166 diag::warn_setter_getter_impl_required_in_category :
1167 diag::warn_setter_getter_impl_required)
1168 << Prop->getDeclName() << Prop->getSetterName();
1169 Diag(IMPDecl->getLocation(),
1170 diag::note_property_impl_required);
1175 void Sema::ImplMethodsVsClassMethods(ObjCImplDecl* IMPDecl,
1176 ObjCContainerDecl* CDecl,
1177 bool IncompleteImpl) {
1178 llvm::DenseSet<Selector> InsMap;
1179 // Check and see if instance methods in class interface have been
1180 // implemented in the implementation class.
1181 for (ObjCImplementationDecl::instmeth_iterator
1182 I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1183 InsMap.insert((*I)->getSelector());
1185 // Check and see if properties declared in the interface have either 1)
1186 // an implementation or 2) there is a @synthesize/@dynamic implementation
1187 // of the property in the @implementation.
1188 if (isa<ObjCInterfaceDecl>(CDecl))
1189 DiagnoseUnimplementedProperties(IMPDecl, CDecl, InsMap);
1191 llvm::DenseSet<Selector> ClsMap;
1192 for (ObjCImplementationDecl::classmeth_iterator
1193 I = IMPDecl->classmeth_begin(),
1194 E = IMPDecl->classmeth_end(); I != E; ++I)
1195 ClsMap.insert((*I)->getSelector());
1197 // Check for type conflict of methods declared in a class/protocol and
1198 // its implementation; if any.
1199 llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
1200 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1202 IncompleteImpl, true);
1204 // Check the protocol list for unimplemented methods in the @implementation
1206 // Check and see if class methods in class interface have been
1207 // implemented in the implementation class.
1209 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1210 for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
1211 E = I->protocol_end(); PI != E; ++PI)
1212 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1214 // Check class extensions (unnamed categories)
1215 for (ObjCCategoryDecl *Categories = I->getCategoryList();
1216 Categories; Categories = Categories->getNextClassCategory()) {
1217 if (!Categories->getIdentifier()) {
1218 ImplMethodsVsClassMethods(IMPDecl, Categories, IncompleteImpl);
1222 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1223 // For extended class, unimplemented methods in its protocols will
1224 // be reported in the primary class.
1225 if (C->getIdentifier()) {
1226 for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1227 E = C->protocol_end(); PI != E; ++PI)
1228 CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1229 InsMap, ClsMap, C->getClassInterface());
1230 // Report unimplemented properties in the category as well.
1231 // When reporting on missing setter/getters, do not report when
1232 // setter/getter is implemented in category's primary class
1234 if (ObjCInterfaceDecl *ID = C->getClassInterface())
1235 if (ObjCImplDecl *IMP = ID->getImplementation()) {
1236 for (ObjCImplementationDecl::instmeth_iterator
1237 I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
1238 InsMap.insert((*I)->getSelector());
1240 DiagnoseUnimplementedProperties(IMPDecl, CDecl, InsMap);
1243 assert(false && "invalid ObjCContainerDecl type.");
1247 Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl,
1248 ObjCContainerDecl* IDecl) {
1249 // Rules apply in non-GC mode only
1250 if (getLangOptions().getGCMode() != LangOptions::NonGC)
1252 for (ObjCContainerDecl::prop_iterator I = IDecl->prop_begin(),
1253 E = IDecl->prop_end();
1255 ObjCPropertyDecl *Property = (*I);
1256 unsigned Attributes = Property->getPropertyAttributes();
1257 // We only care about readwrite atomic property.
1258 if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) ||
1259 !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite))
1261 if (const ObjCPropertyImplDecl *PIDecl
1262 = IMPDecl->FindPropertyImplDecl(Property->getIdentifier())) {
1263 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1265 ObjCMethodDecl *GetterMethod =
1266 IMPDecl->getInstanceMethod(Property->getGetterName());
1267 ObjCMethodDecl *SetterMethod =
1268 IMPDecl->getInstanceMethod(Property->getSetterName());
1269 if ((GetterMethod && !SetterMethod) || (!GetterMethod && SetterMethod)) {
1270 SourceLocation MethodLoc =
1271 (GetterMethod ? GetterMethod->getLocation()
1272 : SetterMethod->getLocation());
1273 Diag(MethodLoc, diag::warn_atomic_property_rule)
1274 << Property->getIdentifier();
1275 Diag(Property->getLocation(), diag::note_property_declare);
1281 /// ActOnForwardClassDeclaration -
1283 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1284 IdentifierInfo **IdentList,
1285 SourceLocation *IdentLocs,
1287 llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1289 for (unsigned i = 0; i != NumElts; ++i) {
1290 // Check for another declaration kind with the same name.
1292 = LookupSingleName(TUScope, IdentList[i], LookupOrdinaryName);
1293 if (PrevDecl && PrevDecl->isTemplateParameter()) {
1294 // Maybe we will complain about the shadowed template parameter.
1295 DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1296 // Just pretend that we didn't see the previous declaration.
1300 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1301 // GCC apparently allows the following idiom:
1303 // typedef NSObject < XCElementTogglerP > XCElementToggler;
1304 // @class XCElementToggler;
1306 // FIXME: Make an extension?
1307 TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1308 if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
1309 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1310 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1312 // a forward class declaration matching a typedef name of a class refers
1313 // to the underlying class.
1314 if (ObjCInterfaceType * OI =
1315 dyn_cast<ObjCInterfaceType>(TDD->getUnderlyingType()))
1316 PrevDecl = OI->getDecl();
1319 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1320 if (!IDecl) { // Not already seen? Make a forward decl.
1321 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1322 IdentList[i], IdentLocs[i], true);
1324 // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1325 // the current DeclContext. This prevents clients that walk DeclContext
1326 // from seeing the imaginary ObjCInterfaceDecl until it is actually
1327 // declared later (if at all). We also take care to explicitly make
1328 // sure this declaration is visible for name lookup.
1329 PushOnScopeChains(IDecl, TUScope, false);
1330 CurContext->makeDeclVisibleInContext(IDecl, true);
1333 Interfaces.push_back(IDecl);
1336 assert(Interfaces.size() == NumElts);
1337 ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1338 Interfaces.data(), IdentLocs,
1340 CurContext->addDecl(CDecl);
1341 CheckObjCDeclScope(CDecl);
1342 return DeclPtrTy::make(CDecl);
1346 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1347 /// returns true, or false, accordingly.
1348 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1349 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1350 const ObjCMethodDecl *PrevMethod,
1351 bool matchBasedOnSizeAndAlignment) {
1352 QualType T1 = Context.getCanonicalType(Method->getResultType());
1353 QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1356 // The result types are different.
1357 if (!matchBasedOnSizeAndAlignment)
1359 // Incomplete types don't have a size and alignment.
1360 if (T1->isIncompleteType() || T2->isIncompleteType())
1362 // Check is based on size and alignment.
1363 if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1367 ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1368 E = Method->param_end();
1369 ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1371 for (; ParamI != E; ++ParamI, ++PrevI) {
1372 assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1373 T1 = Context.getCanonicalType((*ParamI)->getType());
1374 T2 = Context.getCanonicalType((*PrevI)->getType());
1376 // The result types are different.
1377 if (!matchBasedOnSizeAndAlignment)
1379 // Incomplete types don't have a size and alignment.
1380 if (T1->isIncompleteType() || T2->isIncompleteType())
1382 // Check is based on size and alignment.
1383 if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1390 /// \brief Read the contents of the instance and factory method pools
1391 /// for a given selector from external storage.
1393 /// This routine should only be called once, when neither the instance
1394 /// nor the factory method pool has an entry for this selector.
1395 Sema::MethodPool::iterator Sema::ReadMethodPool(Selector Sel,
1397 assert(ExternalSource && "We need an external AST source");
1398 assert(InstanceMethodPool.find(Sel) == InstanceMethodPool.end() &&
1399 "Selector data already loaded into the instance method pool");
1400 assert(FactoryMethodPool.find(Sel) == FactoryMethodPool.end() &&
1401 "Selector data already loaded into the factory method pool");
1403 // Read the method list from the external source.
1404 std::pair<ObjCMethodList, ObjCMethodList> Methods
1405 = ExternalSource->ReadMethodPool(Sel);
1408 if (Methods.second.Method)
1409 FactoryMethodPool[Sel] = Methods.second;
1410 return InstanceMethodPool.insert(std::make_pair(Sel, Methods.first)).first;
1413 if (Methods.first.Method)
1414 InstanceMethodPool[Sel] = Methods.first;
1416 return FactoryMethodPool.insert(std::make_pair(Sel, Methods.second)).first;
1419 void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1420 llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1421 = InstanceMethodPool.find(Method->getSelector());
1422 if (Pos == InstanceMethodPool.end()) {
1423 if (ExternalSource && !FactoryMethodPool.count(Method->getSelector()))
1424 Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/true);
1426 Pos = InstanceMethodPool.insert(std::make_pair(Method->getSelector(),
1427 ObjCMethodList())).first;
1430 ObjCMethodList &Entry = Pos->second;
1431 if (Entry.Method == 0) {
1432 // Haven't seen a method with this selector name yet - add it.
1433 Entry.Method = Method;
1438 // We've seen a method with this name, see if we have already seen this type
1440 for (ObjCMethodList *List = &Entry; List; List = List->Next)
1441 if (MatchTwoMethodDeclarations(Method, List->Method))
1444 // We have a new signature for an existing method - add it.
1445 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1446 Entry.Next = new ObjCMethodList(Method, Entry.Next);
1449 // FIXME: Finish implementing -Wno-strict-selector-match.
1450 ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1453 llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1454 = InstanceMethodPool.find(Sel);
1455 if (Pos == InstanceMethodPool.end()) {
1456 if (ExternalSource && !FactoryMethodPool.count(Sel))
1457 Pos = ReadMethodPool(Sel, /*isInstance=*/true);
1462 ObjCMethodList &MethList = Pos->second;
1463 bool issueWarning = false;
1465 if (MethList.Method && MethList.Next) {
1466 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1467 // This checks if the methods differ by size & alignment.
1468 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1469 issueWarning = warn;
1471 if (issueWarning && (MethList.Method && MethList.Next)) {
1472 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1473 Diag(MethList.Method->getLocStart(), diag::note_using)
1474 << MethList.Method->getSourceRange();
1475 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1476 Diag(Next->Method->getLocStart(), diag::note_also_found)
1477 << Next->Method->getSourceRange();
1479 return MethList.Method;
1482 void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1483 llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1484 = FactoryMethodPool.find(Method->getSelector());
1485 if (Pos == FactoryMethodPool.end()) {
1486 if (ExternalSource && !InstanceMethodPool.count(Method->getSelector()))
1487 Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/false);
1489 Pos = FactoryMethodPool.insert(std::make_pair(Method->getSelector(),
1490 ObjCMethodList())).first;
1493 ObjCMethodList &FirstMethod = Pos->second;
1494 if (!FirstMethod.Method) {
1495 // Haven't seen a method with this selector name yet - add it.
1496 FirstMethod.Method = Method;
1497 FirstMethod.Next = 0;
1499 // We've seen a method with this name, now check the type signature(s).
1500 bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1502 for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1504 match = MatchTwoMethodDeclarations(Method, Next->Method);
1507 // We have a new signature for an existing method - add it.
1508 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1509 struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
1510 FirstMethod.Next = OMI;
1515 ObjCMethodDecl *Sema::LookupFactoryMethodInGlobalPool(Selector Sel,
1517 llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1518 = FactoryMethodPool.find(Sel);
1519 if (Pos == FactoryMethodPool.end()) {
1520 if (ExternalSource && !InstanceMethodPool.count(Sel))
1521 Pos = ReadMethodPool(Sel, /*isInstance=*/false);
1526 ObjCMethodList &MethList = Pos->second;
1527 bool issueWarning = false;
1529 if (MethList.Method && MethList.Next) {
1530 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1531 // This checks if the methods differ by size & alignment.
1532 if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1533 issueWarning = true;
1535 if (issueWarning && (MethList.Method && MethList.Next)) {
1536 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1537 Diag(MethList.Method->getLocStart(), diag::note_using)
1538 << MethList.Method->getSourceRange();
1539 for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1540 Diag(Next->Method->getLocStart(), diag::note_also_found)
1541 << Next->Method->getSourceRange();
1543 return MethList.Method;
1546 /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1547 /// have the property type and issue diagnostics if they don't.
1548 /// Also synthesize a getter/setter method if none exist (and update the
1549 /// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1550 /// methods is the "right" thing to do.
1551 void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1552 ObjCContainerDecl *CD) {
1553 ObjCMethodDecl *GetterMethod, *SetterMethod;
1555 GetterMethod = CD->getInstanceMethod(property->getGetterName());
1556 SetterMethod = CD->getInstanceMethod(property->getSetterName());
1557 DiagnosePropertyAccessorMismatch(property, GetterMethod,
1558 property->getLocation());
1561 ObjCPropertyDecl::PropertyAttributeKind CAttr =
1562 property->getPropertyAttributes();
1563 if ((!(CAttr & ObjCPropertyDecl::OBJC_PR_readonly)) &&
1564 Context.getCanonicalType(SetterMethod->getResultType()) !=
1566 Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1567 if (SetterMethod->param_size() != 1 ||
1568 ((*SetterMethod->param_begin())->getType() != property->getType())) {
1569 Diag(property->getLocation(),
1570 diag::warn_accessor_property_type_mismatch)
1571 << property->getDeclName()
1572 << SetterMethod->getSelector();
1573 Diag(SetterMethod->getLocation(), diag::note_declared_at);
1577 // Synthesize getter/setter methods if none exist.
1578 // Find the default getter and if one not found, add one.
1579 // FIXME: The synthesized property we set here is misleading. We almost always
1580 // synthesize these methods unless the user explicitly provided prototypes
1581 // (which is odd, but allowed). Sema should be typechecking that the
1582 // declarations jive in that situation (which it is not currently).
1583 if (!GetterMethod) {
1584 // No instance method of same name as property getter name was found.
1585 // Declare a getter method and add it to the list of methods
1587 GetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1588 property->getLocation(), property->getGetterName(),
1589 property->getType(), CD, true, false, true,
1590 (property->getPropertyImplementation() ==
1591 ObjCPropertyDecl::Optional) ?
1592 ObjCMethodDecl::Optional :
1593 ObjCMethodDecl::Required);
1594 CD->addDecl(GetterMethod);
1596 // A user declared getter will be synthesize when @synthesize of
1597 // the property with the same name is seen in the @implementation
1598 GetterMethod->setSynthesized(true);
1599 property->setGetterMethodDecl(GetterMethod);
1601 // Skip setter if property is read-only.
1602 if (!property->isReadOnly()) {
1603 // Find the default setter and if one not found, add one.
1604 if (!SetterMethod) {
1605 // No instance method of same name as property setter name was found.
1606 // Declare a setter method and add it to the list of methods
1608 SetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1609 property->getLocation(),
1610 property->getSetterName(),
1611 Context.VoidTy, CD, true, false, true,
1612 (property->getPropertyImplementation() ==
1613 ObjCPropertyDecl::Optional) ?
1614 ObjCMethodDecl::Optional :
1615 ObjCMethodDecl::Required);
1616 // Invent the arguments for the setter. We don't bother making a
1617 // nice name for the argument.
1618 ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
1619 property->getLocation(),
1620 property->getIdentifier(),
1621 property->getType(),
1625 SetterMethod->setMethodParams(Context, &Argument, 1);
1626 CD->addDecl(SetterMethod);
1628 // A user declared setter will be synthesize when @synthesize of
1629 // the property with the same name is seen in the @implementation
1630 SetterMethod->setSynthesized(true);
1631 property->setSetterMethodDecl(SetterMethod);
1633 // Add any synthesized methods to the global pool. This allows us to
1634 // handle the following, which is supported by GCC (and part of the design).
1637 // @property double bar;
1640 // void thisIsUnfortunate() {
1642 // double bar = [foo bar];
1646 AddInstanceMethodToGlobalPool(GetterMethod);
1648 AddInstanceMethodToGlobalPool(SetterMethod);
1651 /// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1652 /// identical selector names in current and its super classes and issues
1653 /// a warning if any of their argument types are incompatible.
1654 void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1655 ObjCMethodDecl *Method,
1657 ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1658 if (ID == 0) return;
1660 while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1661 ObjCMethodDecl *SuperMethodDecl =
1662 SD->lookupMethod(Method->getSelector(), IsInstance);
1663 if (SuperMethodDecl == 0) {
1667 ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1668 E = Method->param_end();
1669 ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1670 for (; ParamI != E; ++ParamI, ++PrevI) {
1671 // Number of parameters are the same and is guaranteed by selector match.
1672 assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1673 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1674 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1675 // If type of arguement of method in this class does not match its
1676 // respective argument type in the super class method, issue warning;
1677 if (!Context.typesAreCompatible(T1, T2)) {
1678 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1680 Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1688 // Note: For class/category implemenations, allMethods/allProperties is
1690 void Sema::ActOnAtEnd(SourceRange AtEnd,
1691 DeclPtrTy classDecl,
1692 DeclPtrTy *allMethods, unsigned allNum,
1693 DeclPtrTy *allProperties, unsigned pNum,
1694 DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1695 Decl *ClassDecl = classDecl.getAs<Decl>();
1697 // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1698 // always passing in a decl. If the decl has an error, isInvalidDecl()
1703 bool isInterfaceDeclKind =
1704 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1705 || isa<ObjCProtocolDecl>(ClassDecl);
1706 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1708 if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1709 // FIXME: This is wrong. We shouldn't be pretending that there is
1710 // an '@end' in the declaration.
1711 SourceLocation L = ClassDecl->getLocation();
1714 Diag(L, diag::warn_missing_atend);
1717 DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1719 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1720 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1721 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1723 for (unsigned i = 0; i < allNum; i++ ) {
1724 ObjCMethodDecl *Method =
1725 cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>());
1727 if (!Method) continue; // Already issued a diagnostic.
1728 if (Method->isInstanceMethod()) {
1729 /// Check for instance method of the same name with incompatible types
1730 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1731 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1733 if ((isInterfaceDeclKind && PrevMethod && !match)
1734 || (checkIdenticalMethods && match)) {
1735 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1736 << Method->getDeclName();
1737 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1739 DC->addDecl(Method);
1740 InsMap[Method->getSelector()] = Method;
1741 /// The following allows us to typecheck messages to "id".
1742 AddInstanceMethodToGlobalPool(Method);
1743 // verify that the instance method conforms to the same definition of
1744 // parent methods if it shadows one.
1745 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1748 /// Check for class method of the same name with incompatible types
1749 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1750 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1752 if ((isInterfaceDeclKind && PrevMethod && !match)
1753 || (checkIdenticalMethods && match)) {
1754 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1755 << Method->getDeclName();
1756 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1758 DC->addDecl(Method);
1759 ClsMap[Method->getSelector()] = Method;
1760 /// The following allows us to typecheck messages to "Class".
1761 AddFactoryMethodToGlobalPool(Method);
1762 // verify that the class method conforms to the same definition of
1763 // parent methods if it shadows one.
1764 CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1768 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1769 // Compares properties declared in this class to those of its
1771 ComparePropertiesInBaseAndSuper(I);
1772 CompareProperties(I, DeclPtrTy::make(I));
1773 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1774 // Categories are used to extend the class by declaring new methods.
1775 // By the same token, they are also used to add new properties. No
1776 // need to compare the added property to those in the class.
1778 // Compare protocol properties with those in category
1779 CompareProperties(C, DeclPtrTy::make(C));
1780 if (C->getIdentifier() == 0)
1781 DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1783 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1784 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1785 // user-defined setter/getter. It also synthesizes setter/getter methods
1786 // and adds them to the DeclContext and global method pools.
1787 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1788 E = CDecl->prop_end();
1790 ProcessPropertyDecl(*I, CDecl);
1791 CDecl->setAtEndRange(AtEnd);
1793 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1794 IC->setAtEndRange(AtEnd);
1795 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1796 ImplMethodsVsClassMethods(IC, IDecl);
1797 AtomicPropertySetterGetterRules(IC, IDecl);
1799 } else if (ObjCCategoryImplDecl* CatImplClass =
1800 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1801 CatImplClass->setAtEndRange(AtEnd);
1803 // Find category interface decl and then check that all methods declared
1804 // in this interface are implemented in the category @implementation.
1805 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1806 for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1807 Categories; Categories = Categories->getNextClassCategory()) {
1808 if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1809 ImplMethodsVsClassMethods(CatImplClass, Categories);
1815 if (isInterfaceDeclKind) {
1816 // Reject invalid vardecls.
1817 for (unsigned i = 0; i != tuvNum; i++) {
1818 DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1819 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1820 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1821 if (!VDecl->hasExternalStorage())
1822 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1829 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1830 /// objective-c's type qualifier from the parser version of the same info.
1831 static Decl::ObjCDeclQualifier
1832 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1833 Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1834 if (PQTVal & ObjCDeclSpec::DQ_In)
1835 ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1836 if (PQTVal & ObjCDeclSpec::DQ_Inout)
1837 ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1838 if (PQTVal & ObjCDeclSpec::DQ_Out)
1839 ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1840 if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1841 ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1842 if (PQTVal & ObjCDeclSpec::DQ_Byref)
1843 ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1844 if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1845 ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1850 Sema::DeclPtrTy Sema::ActOnMethodDeclaration(
1851 SourceLocation MethodLoc, SourceLocation EndLoc,
1852 tok::TokenKind MethodType, DeclPtrTy classDecl,
1853 ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1855 // optional arguments. The number of types/arguments is obtained
1856 // from the Sel.getNumArgs().
1857 ObjCArgInfo *ArgInfo,
1858 llvm::SmallVectorImpl<Declarator> &Cdecls,
1859 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1861 Decl *ClassDecl = classDecl.getAs<Decl>();
1863 // Make sure we can establish a context for the method.
1865 Diag(MethodLoc, diag::error_missing_method_context);
1866 FunctionLabelMap.clear();
1869 QualType resultDeclType;
1872 resultDeclType = GetTypeFromParser(ReturnType);
1874 // Methods cannot return interface types. All ObjC objects are
1875 // passed by reference.
1876 if (resultDeclType->isObjCInterfaceType()) {
1877 Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1878 << 0 << resultDeclType;
1881 } else // get the type for "id".
1882 resultDeclType = Context.getObjCIdType();
1884 ObjCMethodDecl* ObjCMethod =
1885 ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1886 cast<DeclContext>(ClassDecl),
1887 MethodType == tok::minus, isVariadic,
1889 MethodDeclKind == tok::objc_optional ?
1890 ObjCMethodDecl::Optional :
1891 ObjCMethodDecl::Required);
1893 llvm::SmallVector<ParmVarDecl*, 16> Params;
1895 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1899 if (ArgInfo[i].Type == 0) {
1900 ArgType = Context.getObjCIdType();
1903 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1904 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1905 ArgType = adjustParameterType(ArgType);
1909 = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc,
1910 ArgInfo[i].Name, ArgType, DI,
1913 if (ArgType->isObjCInterfaceType()) {
1914 Diag(ArgInfo[i].NameLoc,
1915 diag::err_object_cannot_be_passed_returned_by_value)
1917 Param->setInvalidDecl();
1920 Param->setObjCDeclQualifier(
1921 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1923 // Apply the attributes to the parameter.
1924 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
1926 Params.push_back(Param);
1929 ObjCMethod->setMethodParams(Context, Params.data(), Sel.getNumArgs());
1930 ObjCMethod->setObjCDeclQualifier(
1931 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1932 const ObjCMethodDecl *PrevMethod = 0;
1935 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
1937 const ObjCMethodDecl *InterfaceMD = 0;
1939 // For implementations (which can be very "coarse grain"), we add the
1940 // method now. This allows the AST to implement lookup methods that work
1941 // incrementally (without waiting until we parse the @end). It also allows
1942 // us to flag multiple declaration errors as they occur.
1943 if (ObjCImplementationDecl *ImpDecl =
1944 dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1945 if (MethodType == tok::minus) {
1946 PrevMethod = ImpDecl->getInstanceMethod(Sel);
1947 ImpDecl->addInstanceMethod(ObjCMethod);
1949 PrevMethod = ImpDecl->getClassMethod(Sel);
1950 ImpDecl->addClassMethod(ObjCMethod);
1952 InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
1953 MethodType == tok::minus);
1955 Diag(EndLoc, diag::warn_attribute_method_def);
1956 } else if (ObjCCategoryImplDecl *CatImpDecl =
1957 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1958 if (MethodType == tok::minus) {
1959 PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1960 CatImpDecl->addInstanceMethod(ObjCMethod);
1962 PrevMethod = CatImpDecl->getClassMethod(Sel);
1963 CatImpDecl->addClassMethod(ObjCMethod);
1966 Diag(EndLoc, diag::warn_attribute_method_def);
1969 // You can never have two method definitions with the same name.
1970 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1971 << ObjCMethod->getDeclName();
1972 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1975 // If the interface declared this method, and it was deprecated there,
1976 // mark it deprecated here.
1977 if (InterfaceMD && InterfaceMD->hasAttr<DeprecatedAttr>())
1978 ObjCMethod->addAttr(::new (Context) DeprecatedAttr());
1980 return DeclPtrTy::make(ObjCMethod);
1983 void Sema::CheckObjCPropertyAttributes(QualType PropertyTy,
1985 unsigned &Attributes) {
1986 // FIXME: Improve the reported location.
1988 // readonly and readwrite/assign/retain/copy conflict.
1989 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1990 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1991 ObjCDeclSpec::DQ_PR_assign |
1992 ObjCDeclSpec::DQ_PR_copy |
1993 ObjCDeclSpec::DQ_PR_retain))) {
1994 const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1996 (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1998 (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
2001 Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
2002 diag::err_objc_property_attr_mutually_exclusive :
2003 diag::warn_objc_property_attr_mutually_exclusive)
2004 << "readonly" << which;
2007 // Check for copy or retain on non-object types.
2008 if ((Attributes & (ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) &&
2009 !PropertyTy->isObjCObjectPointerType() &&
2010 !PropertyTy->isBlockPointerType() &&
2011 !Context.isObjCNSObjectType(PropertyTy)) {
2012 Diag(Loc, diag::err_objc_property_requires_object)
2013 << (Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain");
2014 Attributes &= ~(ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain);
2017 // Check for more than one of { assign, copy, retain }.
2018 if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
2019 if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
2020 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2021 << "assign" << "copy";
2022 Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
2024 if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
2025 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2026 << "assign" << "retain";
2027 Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2029 } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
2030 if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
2031 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2032 << "copy" << "retain";
2033 Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2037 // Warn if user supplied no assignment attribute, property is
2038 // readwrite, and this is an object type.
2039 if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
2040 ObjCDeclSpec::DQ_PR_retain)) &&
2041 !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2042 PropertyTy->isObjCObjectPointerType()) {
2043 // Skip this warning in gc-only mode.
2044 if (getLangOptions().getGCMode() != LangOptions::GCOnly)
2045 Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
2047 // If non-gc code warn that this is likely inappropriate.
2048 if (getLangOptions().getGCMode() == LangOptions::NonGC)
2049 Diag(Loc, diag::warn_objc_property_default_assign_on_object);
2051 // FIXME: Implement warning dependent on NSCopying being
2052 // implemented. See also:
2053 // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
2054 // (please trim this list while you are at it).
2057 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy)
2058 && getLangOptions().getGCMode() == LangOptions::GCOnly
2059 && PropertyTy->isBlockPointerType())
2060 Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
2063 Sema::DeclPtrTy Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
2064 FieldDeclarator &FD,
2068 DeclPtrTy ClassCategory,
2069 bool *isOverridingProperty,
2070 tok::ObjCKeywordKind MethodImplKind) {
2071 unsigned Attributes = ODS.getPropertyAttributes();
2072 bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
2073 // default is readwrite!
2074 !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
2075 // property is defaulted to 'assign' if it is readwrite and is
2076 // not retain or copy
2077 bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
2079 !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
2080 !(Attributes & ObjCDeclSpec::DQ_PR_copy)));
2081 QualType T = GetTypeForDeclarator(FD.D, S);
2082 if (T->isReferenceType()) {
2083 Diag(AtLoc, diag::error_reference_property);
2086 Decl *ClassDecl = ClassCategory.getAs<Decl>();
2087 ObjCInterfaceDecl *CCPrimary = 0; // continuation class's primary class
2088 // May modify Attributes.
2089 CheckObjCPropertyAttributes(T, AtLoc, Attributes);
2090 if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
2091 if (!CDecl->getIdentifier()) {
2092 // This is a continuation class. property requires special
2094 if ((CCPrimary = CDecl->getClassInterface())) {
2095 // Find the property in continuation class's primary class only.
2096 IdentifierInfo *PropertyId = FD.D.getIdentifier();
2097 if (ObjCPropertyDecl *PIDecl =
2098 CCPrimary->FindPropertyVisibleInPrimaryClass(PropertyId)) {
2099 // property 'PIDecl's readonly attribute will be over-ridden
2100 // with continuation class's readwrite property attribute!
2101 unsigned PIkind = PIDecl->getPropertyAttributes();
2102 if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
2103 unsigned retainCopyNonatomic =
2104 (ObjCPropertyDecl::OBJC_PR_retain |
2105 ObjCPropertyDecl::OBJC_PR_copy |
2106 ObjCPropertyDecl::OBJC_PR_nonatomic);
2107 if ((Attributes & retainCopyNonatomic) !=
2108 (PIkind & retainCopyNonatomic)) {
2109 Diag(AtLoc, diag::warn_property_attr_mismatch);
2110 Diag(PIDecl->getLocation(), diag::note_property_declare);
2112 DeclContext *DC = dyn_cast<DeclContext>(CCPrimary);
2113 assert(DC && "ClassDecl is not a DeclContext");
2114 DeclContext::lookup_result Found =
2115 DC->lookup(PIDecl->getDeclName());
2116 bool PropertyInPrimaryClass = false;
2117 for (; Found.first != Found.second; ++Found.first)
2118 if (isa<ObjCPropertyDecl>(*Found.first)) {
2119 PropertyInPrimaryClass = true;
2122 if (!PropertyInPrimaryClass) {
2123 // Protocol is not in the primary class. Must build one for it.
2124 ObjCDeclSpec ProtocolPropertyODS;
2125 // FIXME. Assuming that ObjCDeclSpec::ObjCPropertyAttributeKind and
2126 // ObjCPropertyDecl::PropertyAttributeKind have identical values.
2127 // Should consolidate both into one enum type.
2128 ProtocolPropertyODS.setPropertyAttributes(
2129 (ObjCDeclSpec::ObjCPropertyAttributeKind)PIkind);
2130 DeclPtrTy ProtocolPtrTy =
2131 ActOnProperty(S, AtLoc, FD, ProtocolPropertyODS,
2132 PIDecl->getGetterName(),
2133 PIDecl->getSetterName(),
2134 DeclPtrTy::make(CCPrimary), isOverridingProperty,
2136 PIDecl = ProtocolPtrTy.getAs<ObjCPropertyDecl>();
2138 PIDecl->makeitReadWriteAttribute();
2139 if (Attributes & ObjCDeclSpec::DQ_PR_retain)
2140 PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
2141 if (Attributes & ObjCDeclSpec::DQ_PR_copy)
2142 PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
2143 PIDecl->setSetterName(SetterSel);
2145 Diag(AtLoc, diag::err_use_continuation_class)
2146 << CCPrimary->getDeclName();
2147 Diag(PIDecl->getLocation(), diag::note_property_declare);
2149 *isOverridingProperty = true;
2150 // Make sure setter decl is synthesized, and added to primary
2152 ProcessPropertyDecl(PIDecl, CCPrimary);
2155 // No matching property found in the primary class. Just fall thru
2156 // and add property to continuation class's primary class.
2157 ClassDecl = CCPrimary;
2159 Diag(CDecl->getLocation(), diag::err_continuation_class);
2160 *isOverridingProperty = true;
2165 // Issue a warning if property is 'assign' as default and its object, which is
2166 // gc'able conforms to NSCopying protocol
2167 if (getLangOptions().getGCMode() != LangOptions::NonGC &&
2168 isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign))
2169 if (T->isObjCObjectPointerType()) {
2170 QualType InterfaceTy = T->getPointeeType();
2171 if (const ObjCInterfaceType *OIT =
2172 InterfaceTy->getAs<ObjCInterfaceType>()) {
2173 ObjCInterfaceDecl *IDecl = OIT->getDecl();
2175 if (ObjCProtocolDecl* PNSCopying =
2176 LookupProtocol(&Context.Idents.get("NSCopying")))
2177 if (IDecl->ClassImplementsProtocol(PNSCopying, true))
2178 Diag(AtLoc, diag::warn_implements_nscopying)
2179 << FD.D.getIdentifier();
2182 if (T->isObjCInterfaceType())
2183 Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object);
2185 DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
2186 assert(DC && "ClassDecl is not a DeclContext");
2187 ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC,
2188 FD.D.getIdentifierLoc(),
2189 FD.D.getIdentifier(),
2191 DeclContext::lookup_result Found = DC->lookup(PDecl->getDeclName());
2192 if (Found.first != Found.second && isa<ObjCPropertyDecl>(*Found.first)) {
2193 Diag(PDecl->getLocation(), diag::err_duplicate_property);
2194 Diag((*Found.first)->getLocation(), diag::note_property_declare);
2195 PDecl->setInvalidDecl();
2200 if (T->isArrayType() || T->isFunctionType()) {
2201 Diag(AtLoc, diag::err_property_type) << T;
2202 PDecl->setInvalidDecl();
2205 ProcessDeclAttributes(S, PDecl, FD.D);
2207 // Regardless of setter/getter attribute, we save the default getter/setter
2208 // selector names in anticipation of declaration of setter/getter methods.
2209 PDecl->setGetterName(GetterSel);
2210 PDecl->setSetterName(SetterSel);
2212 if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
2213 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
2215 if (Attributes & ObjCDeclSpec::DQ_PR_getter)
2216 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
2218 if (Attributes & ObjCDeclSpec::DQ_PR_setter)
2219 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
2222 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
2224 if (Attributes & ObjCDeclSpec::DQ_PR_retain)
2225 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
2227 if (Attributes & ObjCDeclSpec::DQ_PR_copy)
2228 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
2231 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
2233 if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
2234 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
2236 if (MethodImplKind == tok::objc_required)
2237 PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
2238 else if (MethodImplKind == tok::objc_optional)
2239 PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
2240 // A case of continuation class adding a new property in the class. This
2241 // is not what it was meant for. However, gcc supports it and so should we.
2242 // Make sure setter/getters are declared here.
2244 ProcessPropertyDecl(PDecl, CCPrimary);
2246 return DeclPtrTy::make(PDecl);
2249 /// ActOnPropertyImplDecl - This routine performs semantic checks and
2250 /// builds the AST node for a property implementation declaration; declared
2251 /// as @synthesize or @dynamic.
2253 Sema::DeclPtrTy Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
2254 SourceLocation PropertyLoc,
2256 DeclPtrTy ClassCatImpDecl,
2257 IdentifierInfo *PropertyId,
2258 IdentifierInfo *PropertyIvar) {
2259 Decl *ClassImpDecl = ClassCatImpDecl.getAs<Decl>();
2260 // Make sure we have a context for the property implementation declaration.
2261 if (!ClassImpDecl) {
2262 Diag(AtLoc, diag::error_missing_property_context);
2265 ObjCPropertyDecl *property = 0;
2266 ObjCInterfaceDecl* IDecl = 0;
2267 // Find the class or category class where this property must have
2269 ObjCImplementationDecl *IC = 0;
2270 ObjCCategoryImplDecl* CatImplClass = 0;
2271 if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
2272 IDecl = IC->getClassInterface();
2273 // We always synthesize an interface for an implementation
2274 // without an interface decl. So, IDecl is always non-zero.
2276 "ActOnPropertyImplDecl - @implementation without @interface");
2278 // Look for this property declaration in the @implementation's @interface
2279 property = IDecl->FindPropertyDeclaration(PropertyId);
2281 Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
2284 if (const ObjCCategoryDecl *CD =
2285 dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) {
2286 if (CD->getIdentifier()) {
2287 Diag(PropertyLoc, diag::error_category_property) << CD->getDeclName();
2288 Diag(property->getLocation(), diag::note_property_declare);
2292 } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
2294 Diag(AtLoc, diag::error_synthesize_category_decl);
2297 IDecl = CatImplClass->getClassInterface();
2299 Diag(AtLoc, diag::error_missing_property_interface);
2302 ObjCCategoryDecl *Category =
2303 IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
2305 // If category for this implementation not found, it is an error which
2306 // has already been reported eralier.
2309 // Look for this property declaration in @implementation's category
2310 property = Category->FindPropertyDeclaration(PropertyId);
2312 Diag(PropertyLoc, diag::error_bad_category_property_decl)
2313 << Category->getDeclName();
2317 Diag(AtLoc, diag::error_bad_property_context);
2320 ObjCIvarDecl *Ivar = 0;
2321 // Check that we have a valid, previously declared ivar for @synthesize
2325 PropertyIvar = PropertyId;
2326 QualType PropType = Context.getCanonicalType(property->getType());
2327 // Check that this is a previously declared 'ivar' in 'IDecl' interface
2328 ObjCInterfaceDecl *ClassDeclared;
2329 Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
2331 DeclContext *EnclosingContext = cast_or_null<DeclContext>(IDecl);
2332 assert(EnclosingContext &&
2333 "null DeclContext for synthesized ivar - ActOnPropertyImplDecl");
2334 Ivar = ObjCIvarDecl::Create(Context, EnclosingContext, PropertyLoc,
2335 PropertyIvar, PropType, /*Dinfo=*/0,
2336 ObjCIvarDecl::Public,
2338 Ivar->setLexicalDeclContext(IDecl);
2339 IDecl->addDecl(Ivar);
2340 property->setPropertyIvarDecl(Ivar);
2341 if (!getLangOptions().ObjCNonFragileABI)
2342 Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId;
2343 // Note! I deliberately want it to fall thru so, we have a
2344 // a property implementation and to avoid future warnings.
2345 } else if (getLangOptions().ObjCNonFragileABI &&
2346 ClassDeclared != IDecl) {
2347 Diag(PropertyLoc, diag::error_ivar_in_superclass_use)
2348 << property->getDeclName() << Ivar->getDeclName()
2349 << ClassDeclared->getDeclName();
2350 Diag(Ivar->getLocation(), diag::note_previous_access_declaration)
2351 << Ivar << Ivar->getNameAsCString();
2352 // Note! I deliberately want it to fall thru so more errors are caught.
2354 QualType IvarType = Context.getCanonicalType(Ivar->getType());
2356 // Check that type of property and its ivar are type compatible.
2357 if (PropType != IvarType) {
2358 if (CheckAssignmentConstraints(PropType, IvarType) != Compatible) {
2359 Diag(PropertyLoc, diag::error_property_ivar_type)
2360 << property->getDeclName() << Ivar->getDeclName();
2361 // Note! I deliberately want it to fall thru so, we have a
2362 // a property implementation and to avoid future warnings.
2365 // FIXME! Rules for properties are somewhat different that those
2366 // for assignments. Use a new routine to consolidate all cases;
2367 // specifically for property redeclarations as well as for ivars.
2368 QualType lhsType =Context.getCanonicalType(PropType).getUnqualifiedType();
2369 QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
2370 if (lhsType != rhsType &&
2371 lhsType->isArithmeticType()) {
2372 Diag(PropertyLoc, diag::error_property_ivar_type)
2373 << property->getDeclName() << Ivar->getDeclName();
2374 // Fall thru - see previous comment
2376 // __weak is explicit. So it works on Canonical type.
2377 if (PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
2378 getLangOptions().getGCMode() != LangOptions::NonGC) {
2379 Diag(PropertyLoc, diag::error_weak_property)
2380 << property->getDeclName() << Ivar->getDeclName();
2381 // Fall thru - see previous comment
2383 if ((property->getType()->isObjCObjectPointerType() ||
2384 PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
2385 getLangOptions().getGCMode() != LangOptions::NonGC) {
2386 Diag(PropertyLoc, diag::error_strong_property)
2387 << property->getDeclName() << Ivar->getDeclName();
2388 // Fall thru - see previous comment
2391 } else if (PropertyIvar)
2393 Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
2394 assert (property && "ActOnPropertyImplDecl - property declaration missing");
2395 ObjCPropertyImplDecl *PIDecl =
2396 ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
2399 ObjCPropertyImplDecl::Synthesize
2400 : ObjCPropertyImplDecl::Dynamic),
2404 if (ObjCPropertyImplDecl *PPIDecl =
2405 IC->FindPropertyImplIvarDecl(PropertyIvar)) {
2406 Diag(PropertyLoc, diag::error_duplicate_ivar_use)
2407 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
2409 Diag(PPIDecl->getLocation(), diag::note_previous_use);
2412 if (ObjCPropertyImplDecl *PPIDecl
2413 = IC->FindPropertyImplDecl(PropertyId)) {
2414 Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
2415 Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
2418 IC->addPropertyImplementation(PIDecl);
2421 if (ObjCPropertyImplDecl *PPIDecl =
2422 CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
2423 Diag(PropertyLoc, diag::error_duplicate_ivar_use)
2424 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
2426 Diag(PPIDecl->getLocation(), diag::note_previous_use);
2429 if (ObjCPropertyImplDecl *PPIDecl =
2430 CatImplClass->FindPropertyImplDecl(PropertyId)) {
2431 Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
2432 Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
2435 CatImplClass->addPropertyImplementation(PIDecl);
2438 return DeclPtrTy::make(PIDecl);
2441 bool Sema::CheckObjCDeclScope(Decl *D) {
2442 if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
2445 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
2446 D->setInvalidDecl();
2451 /// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2452 /// instance variables of ClassName into Decls.
2453 void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart,
2454 IdentifierInfo *ClassName,
2455 llvm::SmallVectorImpl<DeclPtrTy> &Decls) {
2456 // Check that ClassName is a valid class
2457 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2459 Diag(DeclStart, diag::err_undef_interface) << ClassName;
2462 if (LangOpts.ObjCNonFragileABI) {
2463 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
2467 // Collect the instance variables
2468 llvm::SmallVector<FieldDecl*, 32> RecFields;
2469 Context.CollectObjCIvars(Class, RecFields);
2470 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
2471 for (unsigned i = 0; i < RecFields.size(); i++) {
2472 FieldDecl* ID = RecFields[i];
2473 RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>());
2474 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, ID->getLocation(),
2475 ID->getIdentifier(), ID->getType(),
2477 Decls.push_back(Sema::DeclPtrTy::make(FD));
2480 // Introduce all of these fields into the appropriate scope.
2481 for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin();
2482 D != Decls.end(); ++D) {
2483 FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>());
2484 if (getLangOptions().CPlusPlus)
2485 PushOnScopeChains(cast<FieldDecl>(FD), S);
2486 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>()))
2487 Record->addDecl(FD);