1 //===--- SemaObjCProperty.cpp - Semantic Analysis for ObjC @property ------===//
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 @property and
11 // @synthesize declarations.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Sema/SemaInternal.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/AST/ExprCXX.h"
20 #include "clang/AST/ASTMutationListener.h"
21 #include "clang/Lex/Lexer.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "llvm/ADT/DenseSet.h"
24 #include "llvm/ADT/SmallString.h"
25 #include "clang/Lex/Preprocessor.h"
27 using namespace clang;
29 //===----------------------------------------------------------------------===//
31 //===----------------------------------------------------------------------===//
33 /// getImpliedARCOwnership - Given a set of property attributes and a
34 /// type, infer an expected lifetime. The type's ownership qualification
35 /// is not considered.
37 /// Returns OCL_None if the attributes as stated do not imply an ownership.
38 /// Never returns OCL_Autoreleasing.
39 static Qualifiers::ObjCLifetime getImpliedARCOwnership(
40 ObjCPropertyDecl::PropertyAttributeKind attrs,
42 // retain, strong, copy, weak, and unsafe_unretained are only legal
43 // on properties of retainable pointer type.
44 if (attrs & (ObjCPropertyDecl::OBJC_PR_retain |
45 ObjCPropertyDecl::OBJC_PR_strong |
46 ObjCPropertyDecl::OBJC_PR_copy)) {
47 return Qualifiers::OCL_Strong;
48 } else if (attrs & ObjCPropertyDecl::OBJC_PR_weak) {
49 return Qualifiers::OCL_Weak;
50 } else if (attrs & ObjCPropertyDecl::OBJC_PR_unsafe_unretained) {
51 return Qualifiers::OCL_ExplicitNone;
54 // assign can appear on other types, so we have to check the
56 if (attrs & ObjCPropertyDecl::OBJC_PR_assign &&
57 type->isObjCRetainableType()) {
58 return Qualifiers::OCL_ExplicitNone;
61 return Qualifiers::OCL_None;
64 /// Check the internal consistency of a property declaration.
65 static void checkARCPropertyDecl(Sema &S, ObjCPropertyDecl *property) {
66 if (property->isInvalidDecl()) return;
68 ObjCPropertyDecl::PropertyAttributeKind propertyKind
69 = property->getPropertyAttributes();
70 Qualifiers::ObjCLifetime propertyLifetime
71 = property->getType().getObjCLifetime();
73 // Nothing to do if we don't have a lifetime.
74 if (propertyLifetime == Qualifiers::OCL_None) return;
76 Qualifiers::ObjCLifetime expectedLifetime
77 = getImpliedARCOwnership(propertyKind, property->getType());
78 if (!expectedLifetime) {
79 // We have a lifetime qualifier but no dominating property
80 // attribute. That's okay, but restore reasonable invariants by
81 // setting the property attribute according to the lifetime
83 ObjCPropertyDecl::PropertyAttributeKind attr;
84 if (propertyLifetime == Qualifiers::OCL_Strong) {
85 attr = ObjCPropertyDecl::OBJC_PR_strong;
86 } else if (propertyLifetime == Qualifiers::OCL_Weak) {
87 attr = ObjCPropertyDecl::OBJC_PR_weak;
89 assert(propertyLifetime == Qualifiers::OCL_ExplicitNone);
90 attr = ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
92 property->setPropertyAttributes(attr);
96 if (propertyLifetime == expectedLifetime) return;
98 property->setInvalidDecl();
99 S.Diag(property->getLocation(),
100 diag::err_arc_inconsistent_property_ownership)
101 << property->getDeclName()
106 static unsigned deduceWeakPropertyFromType(Sema &S, QualType T) {
107 if ((S.getLangOpts().getGC() != LangOptions::NonGC &&
109 (S.getLangOpts().ObjCAutoRefCount &&
110 T.getObjCLifetime() == Qualifiers::OCL_Weak))
111 return ObjCDeclSpec::DQ_PR_weak;
115 Decl *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
116 SourceLocation LParenLoc,
121 bool *isOverridingProperty,
122 tok::ObjCKeywordKind MethodImplKind,
123 DeclContext *lexicalDC) {
124 unsigned Attributes = ODS.getPropertyAttributes();
125 TypeSourceInfo *TSI = GetTypeForDeclarator(FD.D, S);
126 QualType T = TSI->getType();
127 Attributes |= deduceWeakPropertyFromType(*this, T);
129 bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
130 // default is readwrite!
131 !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
132 // property is defaulted to 'assign' if it is readwrite and is
133 // not retain or copy
134 bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
136 !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
137 !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
138 !(Attributes & ObjCDeclSpec::DQ_PR_copy) &&
139 !(Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) &&
140 !(Attributes & ObjCDeclSpec::DQ_PR_weak)));
142 // Proceed with constructing the ObjCPropertDecls.
143 ObjCContainerDecl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
144 if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
145 if (CDecl->IsClassExtension()) {
146 Decl *Res = HandlePropertyInClassExtension(S, AtLoc, LParenLoc,
147 FD, GetterSel, SetterSel,
148 isAssign, isReadWrite,
150 ODS.getPropertyAttributes(),
151 isOverridingProperty, TSI,
154 CheckObjCPropertyAttributes(Res, AtLoc, Attributes, false);
155 if (getLangOpts().ObjCAutoRefCount)
156 checkARCPropertyDecl(*this, cast<ObjCPropertyDecl>(Res));
158 ActOnDocumentableDecl(Res);
162 ObjCPropertyDecl *Res = CreatePropertyDecl(S, ClassDecl, AtLoc, LParenLoc, FD,
163 GetterSel, SetterSel,
164 isAssign, isReadWrite,
166 ODS.getPropertyAttributes(),
167 TSI, MethodImplKind);
169 Res->setLexicalDeclContext(lexicalDC);
171 // Validate the attributes on the @property.
172 CheckObjCPropertyAttributes(Res, AtLoc, Attributes,
173 (isa<ObjCInterfaceDecl>(ClassDecl) ||
174 isa<ObjCProtocolDecl>(ClassDecl)));
176 if (getLangOpts().ObjCAutoRefCount)
177 checkARCPropertyDecl(*this, Res);
179 ActOnDocumentableDecl(Res);
183 static ObjCPropertyDecl::PropertyAttributeKind
184 makePropertyAttributesAsWritten(unsigned Attributes) {
185 unsigned attributesAsWritten = 0;
186 if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
187 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readonly;
188 if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
189 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readwrite;
190 if (Attributes & ObjCDeclSpec::DQ_PR_getter)
191 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_getter;
192 if (Attributes & ObjCDeclSpec::DQ_PR_setter)
193 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_setter;
194 if (Attributes & ObjCDeclSpec::DQ_PR_assign)
195 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_assign;
196 if (Attributes & ObjCDeclSpec::DQ_PR_retain)
197 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_retain;
198 if (Attributes & ObjCDeclSpec::DQ_PR_strong)
199 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_strong;
200 if (Attributes & ObjCDeclSpec::DQ_PR_weak)
201 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_weak;
202 if (Attributes & ObjCDeclSpec::DQ_PR_copy)
203 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_copy;
204 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
205 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_unsafe_unretained;
206 if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
207 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_nonatomic;
208 if (Attributes & ObjCDeclSpec::DQ_PR_atomic)
209 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic;
211 return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten;
214 static bool LocPropertyAttribute( ASTContext &Context, const char *attrName,
215 SourceLocation LParenLoc, SourceLocation &Loc) {
216 if (LParenLoc.isMacroID())
219 SourceManager &SM = Context.getSourceManager();
220 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc);
221 // Try to load the file buffer.
222 bool invalidTemp = false;
223 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
226 const char *tokenBegin = file.data() + locInfo.second;
228 // Lex from the start of the given location.
229 Lexer lexer(SM.getLocForStartOfFile(locInfo.first),
230 Context.getLangOpts(),
231 file.begin(), tokenBegin, file.end());
234 lexer.LexFromRawLexer(Tok);
235 if (Tok.is(tok::raw_identifier) &&
236 StringRef(Tok.getRawIdentifierData(), Tok.getLength()) == attrName) {
237 Loc = Tok.getLocation();
240 } while (Tok.isNot(tok::r_paren));
245 static unsigned getOwnershipRule(unsigned attr) {
246 return attr & (ObjCPropertyDecl::OBJC_PR_assign |
247 ObjCPropertyDecl::OBJC_PR_retain |
248 ObjCPropertyDecl::OBJC_PR_copy |
249 ObjCPropertyDecl::OBJC_PR_weak |
250 ObjCPropertyDecl::OBJC_PR_strong |
251 ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
255 Sema::HandlePropertyInClassExtension(Scope *S,
256 SourceLocation AtLoc,
257 SourceLocation LParenLoc,
259 Selector GetterSel, Selector SetterSel,
261 const bool isReadWrite,
262 const unsigned Attributes,
263 const unsigned AttributesAsWritten,
264 bool *isOverridingProperty,
266 tok::ObjCKeywordKind MethodImplKind) {
267 ObjCCategoryDecl *CDecl = cast<ObjCCategoryDecl>(CurContext);
268 // Diagnose if this property is already in continuation class.
269 DeclContext *DC = CurContext;
270 IdentifierInfo *PropertyId = FD.D.getIdentifier();
271 ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface();
274 // Check for duplicate declaration of this property in current and
275 // other class extensions.
276 for (const ObjCCategoryDecl *ClsExtDecl =
277 CCPrimary->getFirstClassExtension();
278 ClsExtDecl; ClsExtDecl = ClsExtDecl->getNextClassExtension()) {
279 if (ObjCPropertyDecl *prevDecl =
280 ObjCPropertyDecl::findPropertyDecl(ClsExtDecl, PropertyId)) {
281 Diag(AtLoc, diag::err_duplicate_property);
282 Diag(prevDecl->getLocation(), diag::note_property_declare);
287 // Create a new ObjCPropertyDecl with the DeclContext being
288 // the class extension.
289 // FIXME. We should really be using CreatePropertyDecl for this.
290 ObjCPropertyDecl *PDecl =
291 ObjCPropertyDecl::Create(Context, DC, FD.D.getIdentifierLoc(),
292 PropertyId, AtLoc, LParenLoc, T);
293 PDecl->setPropertyAttributesAsWritten(
294 makePropertyAttributesAsWritten(AttributesAsWritten));
295 if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
296 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
297 if (Attributes & ObjCDeclSpec::DQ_PR_readwrite)
298 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
299 // Set setter/getter selector name. Needed later.
300 PDecl->setGetterName(GetterSel);
301 PDecl->setSetterName(SetterSel);
302 ProcessDeclAttributes(S, PDecl, FD.D);
305 // We need to look in the @interface to see if the @property was
308 Diag(CDecl->getLocation(), diag::err_continuation_class);
309 *isOverridingProperty = true;
313 // Find the property in continuation class's primary class only.
314 ObjCPropertyDecl *PIDecl =
315 CCPrimary->FindPropertyVisibleInPrimaryClass(PropertyId);
318 // No matching property found in the primary class. Just fall thru
319 // and add property to continuation class's primary class.
320 ObjCPropertyDecl *PrimaryPDecl =
321 CreatePropertyDecl(S, CCPrimary, AtLoc, LParenLoc,
322 FD, GetterSel, SetterSel, isAssign, isReadWrite,
323 Attributes,AttributesAsWritten, T, MethodImplKind, DC);
325 // A case of continuation class adding a new property in the class. This
326 // is not what it was meant for. However, gcc supports it and so should we.
327 // Make sure setter/getters are declared here.
328 ProcessPropertyDecl(PrimaryPDecl, CCPrimary, /* redeclaredProperty = */ 0,
329 /* lexicalDC = */ CDecl);
330 PDecl->setGetterMethodDecl(PrimaryPDecl->getGetterMethodDecl());
331 PDecl->setSetterMethodDecl(PrimaryPDecl->getSetterMethodDecl());
332 if (ASTMutationListener *L = Context.getASTMutationListener())
333 L->AddedObjCPropertyInClassExtension(PrimaryPDecl, /*OrigProp=*/0, CDecl);
336 if (!Context.hasSameType(PIDecl->getType(), PDecl->getType())) {
337 bool IncompatibleObjC = false;
338 QualType ConvertedType;
339 // Relax the strict type matching for property type in continuation class.
340 // Allow property object type of continuation class to be different as long
341 // as it narrows the object type in its primary class property. Note that
342 // this conversion is safe only because the wider type is for a 'readonly'
343 // property in primary class and 'narrowed' type for a 'readwrite' property
344 // in continuation class.
345 if (!isa<ObjCObjectPointerType>(PIDecl->getType()) ||
346 !isa<ObjCObjectPointerType>(PDecl->getType()) ||
347 (!isObjCPointerConversion(PDecl->getType(), PIDecl->getType(),
348 ConvertedType, IncompatibleObjC))
349 || IncompatibleObjC) {
351 diag::err_type_mismatch_continuation_class) << PDecl->getType();
352 Diag(PIDecl->getLocation(), diag::note_property_declare);
357 // The property 'PIDecl's readonly attribute will be over-ridden
358 // with continuation class's readwrite property attribute!
359 unsigned PIkind = PIDecl->getPropertyAttributesAsWritten();
360 if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
361 PIkind |= deduceWeakPropertyFromType(*this, PIDecl->getType());
362 unsigned ClassExtensionMemoryModel = getOwnershipRule(Attributes);
363 unsigned PrimaryClassMemoryModel = getOwnershipRule(PIkind);
364 if (PrimaryClassMemoryModel && ClassExtensionMemoryModel &&
365 (PrimaryClassMemoryModel != ClassExtensionMemoryModel)) {
366 Diag(AtLoc, diag::warn_property_attr_mismatch);
367 Diag(PIDecl->getLocation(), diag::note_property_declare);
369 DeclContext *DC = cast<DeclContext>(CCPrimary);
370 if (!ObjCPropertyDecl::findPropertyDecl(DC,
371 PIDecl->getDeclName().getAsIdentifierInfo())) {
372 // Protocol is not in the primary class. Must build one for it.
373 ObjCDeclSpec ProtocolPropertyODS;
374 // FIXME. Assuming that ObjCDeclSpec::ObjCPropertyAttributeKind
375 // and ObjCPropertyDecl::PropertyAttributeKind have identical
376 // values. Should consolidate both into one enum type.
378 setPropertyAttributes((ObjCDeclSpec::ObjCPropertyAttributeKind)
380 // Must re-establish the context from class extension to primary
382 ContextRAII SavedContext(*this, CCPrimary);
384 Decl *ProtocolPtrTy =
385 ActOnProperty(S, AtLoc, LParenLoc, FD, ProtocolPropertyODS,
386 PIDecl->getGetterName(),
387 PIDecl->getSetterName(),
388 isOverridingProperty,
390 /* lexicalDC = */ CDecl);
391 PIDecl = cast<ObjCPropertyDecl>(ProtocolPtrTy);
393 PIDecl->makeitReadWriteAttribute();
394 if (Attributes & ObjCDeclSpec::DQ_PR_retain)
395 PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
396 if (Attributes & ObjCDeclSpec::DQ_PR_strong)
397 PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
398 if (Attributes & ObjCDeclSpec::DQ_PR_copy)
399 PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
400 PIDecl->setSetterName(SetterSel);
402 // Tailor the diagnostics for the common case where a readwrite
403 // property is declared both in the @interface and the continuation.
404 // This is a common error where the user often intended the original
405 // declaration to be readonly.
407 (Attributes & ObjCDeclSpec::DQ_PR_readwrite) &&
408 (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite)
409 ? diag::err_use_continuation_class_redeclaration_readwrite
410 : diag::err_use_continuation_class;
412 << CCPrimary->getDeclName();
413 Diag(PIDecl->getLocation(), diag::note_property_declare);
416 *isOverridingProperty = true;
417 // Make sure setter decl is synthesized, and added to primary class's list.
418 ProcessPropertyDecl(PIDecl, CCPrimary, PDecl, CDecl);
419 PDecl->setGetterMethodDecl(PIDecl->getGetterMethodDecl());
420 PDecl->setSetterMethodDecl(PIDecl->getSetterMethodDecl());
421 if (ASTMutationListener *L = Context.getASTMutationListener())
422 L->AddedObjCPropertyInClassExtension(PDecl, PIDecl, CDecl);
426 ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S,
427 ObjCContainerDecl *CDecl,
428 SourceLocation AtLoc,
429 SourceLocation LParenLoc,
434 const bool isReadWrite,
435 const unsigned Attributes,
436 const unsigned AttributesAsWritten,
437 TypeSourceInfo *TInfo,
438 tok::ObjCKeywordKind MethodImplKind,
439 DeclContext *lexicalDC){
440 IdentifierInfo *PropertyId = FD.D.getIdentifier();
441 QualType T = TInfo->getType();
443 // Issue a warning if property is 'assign' as default and its object, which is
444 // gc'able conforms to NSCopying protocol
445 if (getLangOpts().getGC() != LangOptions::NonGC &&
446 isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign))
447 if (const ObjCObjectPointerType *ObjPtrTy =
448 T->getAs<ObjCObjectPointerType>()) {
449 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface();
451 if (ObjCProtocolDecl* PNSCopying =
452 LookupProtocol(&Context.Idents.get("NSCopying"), AtLoc))
453 if (IDecl->ClassImplementsProtocol(PNSCopying, true))
454 Diag(AtLoc, diag::warn_implements_nscopying) << PropertyId;
456 if (T->isObjCObjectType())
457 Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object);
459 DeclContext *DC = cast<DeclContext>(CDecl);
460 ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC,
461 FD.D.getIdentifierLoc(),
462 PropertyId, AtLoc, LParenLoc, TInfo);
464 if (ObjCPropertyDecl *prevDecl =
465 ObjCPropertyDecl::findPropertyDecl(DC, PropertyId)) {
466 Diag(PDecl->getLocation(), diag::err_duplicate_property);
467 Diag(prevDecl->getLocation(), diag::note_property_declare);
468 PDecl->setInvalidDecl();
473 PDecl->setLexicalDeclContext(lexicalDC);
476 if (T->isArrayType() || T->isFunctionType()) {
477 Diag(AtLoc, diag::err_property_type) << T;
478 PDecl->setInvalidDecl();
481 ProcessDeclAttributes(S, PDecl, FD.D);
483 // Regardless of setter/getter attribute, we save the default getter/setter
484 // selector names in anticipation of declaration of setter/getter methods.
485 PDecl->setGetterName(GetterSel);
486 PDecl->setSetterName(SetterSel);
487 PDecl->setPropertyAttributesAsWritten(
488 makePropertyAttributesAsWritten(AttributesAsWritten));
490 if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
491 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
493 if (Attributes & ObjCDeclSpec::DQ_PR_getter)
494 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
496 if (Attributes & ObjCDeclSpec::DQ_PR_setter)
497 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
500 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
502 if (Attributes & ObjCDeclSpec::DQ_PR_retain)
503 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
505 if (Attributes & ObjCDeclSpec::DQ_PR_strong)
506 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
508 if (Attributes & ObjCDeclSpec::DQ_PR_weak)
509 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
511 if (Attributes & ObjCDeclSpec::DQ_PR_copy)
512 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
514 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
515 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
518 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
520 // In the semantic attributes, one of nonatomic or atomic is always set.
521 if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
522 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
524 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic);
526 // 'unsafe_unretained' is alias for 'assign'.
527 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained)
528 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
530 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained);
532 if (MethodImplKind == tok::objc_required)
533 PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
534 else if (MethodImplKind == tok::objc_optional)
535 PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
540 static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc,
541 ObjCPropertyDecl *property,
542 ObjCIvarDecl *ivar) {
543 if (property->isInvalidDecl() || ivar->isInvalidDecl()) return;
545 QualType ivarType = ivar->getType();
546 Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
548 // The lifetime implied by the property's attributes.
549 Qualifiers::ObjCLifetime propertyLifetime =
550 getImpliedARCOwnership(property->getPropertyAttributes(),
551 property->getType());
553 // We're fine if they match.
554 if (propertyLifetime == ivarLifetime) return;
556 // These aren't valid lifetimes for object ivars; don't diagnose twice.
557 if (ivarLifetime == Qualifiers::OCL_None ||
558 ivarLifetime == Qualifiers::OCL_Autoreleasing)
561 // If the ivar is private, and it's implicitly __unsafe_unretained
562 // becaues of its type, then pretend it was actually implicitly
563 // __strong. This is only sound because we're processing the
564 // property implementation before parsing any method bodies.
565 if (ivarLifetime == Qualifiers::OCL_ExplicitNone &&
566 propertyLifetime == Qualifiers::OCL_Strong &&
567 ivar->getAccessControl() == ObjCIvarDecl::Private) {
568 SplitQualType split = ivarType.split();
569 if (split.Quals.hasObjCLifetime()) {
570 assert(ivarType->isObjCARCImplicitlyUnretainedType());
571 split.Quals.setObjCLifetime(Qualifiers::OCL_Strong);
572 ivarType = S.Context.getQualifiedType(split);
573 ivar->setType(ivarType);
578 switch (propertyLifetime) {
579 case Qualifiers::OCL_Strong:
580 S.Diag(propertyImplLoc, diag::err_arc_strong_property_ownership)
581 << property->getDeclName()
582 << ivar->getDeclName()
586 case Qualifiers::OCL_Weak:
587 S.Diag(propertyImplLoc, diag::error_weak_property)
588 << property->getDeclName()
589 << ivar->getDeclName();
592 case Qualifiers::OCL_ExplicitNone:
593 S.Diag(propertyImplLoc, diag::err_arc_assign_property_ownership)
594 << property->getDeclName()
595 << ivar->getDeclName()
596 << ((property->getPropertyAttributesAsWritten()
597 & ObjCPropertyDecl::OBJC_PR_assign) != 0);
600 case Qualifiers::OCL_Autoreleasing:
601 llvm_unreachable("properties cannot be autoreleasing");
603 case Qualifiers::OCL_None:
604 // Any other property should be ignored.
608 S.Diag(property->getLocation(), diag::note_property_declare);
611 /// setImpliedPropertyAttributeForReadOnlyProperty -
612 /// This routine evaludates life-time attributes for a 'readonly'
613 /// property with no known lifetime of its own, using backing
614 /// 'ivar's attribute, if any. If no backing 'ivar', property's
615 /// life-time is assumed 'strong'.
616 static void setImpliedPropertyAttributeForReadOnlyProperty(
617 ObjCPropertyDecl *property, ObjCIvarDecl *ivar) {
618 Qualifiers::ObjCLifetime propertyLifetime =
619 getImpliedARCOwnership(property->getPropertyAttributes(),
620 property->getType());
621 if (propertyLifetime != Qualifiers::OCL_None)
625 // if no backing ivar, make property 'strong'.
626 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
629 // property assumes owenership of backing ivar.
630 QualType ivarType = ivar->getType();
631 Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime();
632 if (ivarLifetime == Qualifiers::OCL_Strong)
633 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
634 else if (ivarLifetime == Qualifiers::OCL_Weak)
635 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak);
639 /// DiagnoseClassAndClassExtPropertyMismatch - diagnose inconsistant property
640 /// attribute declared in primary class and attributes overridden in any of its
641 /// class extensions.
643 DiagnoseClassAndClassExtPropertyMismatch(Sema &S, ObjCInterfaceDecl *ClassDecl,
644 ObjCPropertyDecl *property) {
645 unsigned Attributes = property->getPropertyAttributesAsWritten();
646 bool warn = (Attributes & ObjCDeclSpec::DQ_PR_readonly);
647 for (const ObjCCategoryDecl *CDecl = ClassDecl->getFirstClassExtension();
648 CDecl; CDecl = CDecl->getNextClassExtension()) {
649 ObjCPropertyDecl *ClassExtProperty = 0;
650 for (ObjCContainerDecl::prop_iterator P = CDecl->prop_begin(),
651 E = CDecl->prop_end(); P != E; ++P) {
652 if ((*P)->getIdentifier() == property->getIdentifier()) {
653 ClassExtProperty = *P;
657 if (ClassExtProperty) {
659 unsigned classExtPropertyAttr =
660 ClassExtProperty->getPropertyAttributesAsWritten();
661 // We are issuing the warning that we postponed because class extensions
662 // can override readonly->readwrite and 'setter' attributes originally
663 // placed on class's property declaration now make sense in the overridden
665 if (Attributes & ObjCDeclSpec::DQ_PR_readonly) {
666 if (!classExtPropertyAttr ||
667 (classExtPropertyAttr &
668 (ObjCDeclSpec::DQ_PR_readwrite|
669 ObjCDeclSpec::DQ_PR_assign |
670 ObjCDeclSpec::DQ_PR_unsafe_unretained |
671 ObjCDeclSpec::DQ_PR_copy |
672 ObjCDeclSpec::DQ_PR_retain |
673 ObjCDeclSpec::DQ_PR_strong)))
681 unsigned setterAttrs = (ObjCDeclSpec::DQ_PR_assign |
682 ObjCDeclSpec::DQ_PR_unsafe_unretained |
683 ObjCDeclSpec::DQ_PR_copy |
684 ObjCDeclSpec::DQ_PR_retain |
685 ObjCDeclSpec::DQ_PR_strong);
686 if (Attributes & setterAttrs) {
688 (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
690 (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) ?
691 "unsafe_unretained" :
692 (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
694 (Attributes & ObjCDeclSpec::DQ_PR_retain) ?
697 S.Diag(property->getLocation(),
698 diag::warn_objc_property_attr_mutually_exclusive)
699 << "readonly" << which;
706 /// ActOnPropertyImplDecl - This routine performs semantic checks and
707 /// builds the AST node for a property implementation declaration; declared
708 /// as \@synthesize or \@dynamic.
710 Decl *Sema::ActOnPropertyImplDecl(Scope *S,
711 SourceLocation AtLoc,
712 SourceLocation PropertyLoc,
714 IdentifierInfo *PropertyId,
715 IdentifierInfo *PropertyIvar,
716 SourceLocation PropertyIvarLoc) {
717 ObjCContainerDecl *ClassImpDecl =
718 dyn_cast<ObjCContainerDecl>(CurContext);
719 // Make sure we have a context for the property implementation declaration.
721 Diag(AtLoc, diag::error_missing_property_context);
724 if (PropertyIvarLoc.isInvalid())
725 PropertyIvarLoc = PropertyLoc;
726 SourceLocation PropertyDiagLoc = PropertyLoc;
727 if (PropertyDiagLoc.isInvalid())
728 PropertyDiagLoc = ClassImpDecl->getLocStart();
729 ObjCPropertyDecl *property = 0;
730 ObjCInterfaceDecl* IDecl = 0;
731 // Find the class or category class where this property must have
733 ObjCImplementationDecl *IC = 0;
734 ObjCCategoryImplDecl* CatImplClass = 0;
735 if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
736 IDecl = IC->getClassInterface();
737 // We always synthesize an interface for an implementation
738 // without an interface decl. So, IDecl is always non-zero.
740 "ActOnPropertyImplDecl - @implementation without @interface");
742 // Look for this property declaration in the @implementation's @interface
743 property = IDecl->FindPropertyDeclaration(PropertyId);
745 Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
748 unsigned PIkind = property->getPropertyAttributesAsWritten();
749 if ((PIkind & (ObjCPropertyDecl::OBJC_PR_atomic |
750 ObjCPropertyDecl::OBJC_PR_nonatomic) ) == 0) {
752 Diag(AtLoc, diag::warn_implicit_atomic_property);
754 Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property);
755 Diag(property->getLocation(), diag::note_property_declare);
758 if (const ObjCCategoryDecl *CD =
759 dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) {
760 if (!CD->IsClassExtension()) {
761 Diag(PropertyLoc, diag::error_category_property) << CD->getDeclName();
762 Diag(property->getLocation(), diag::note_property_declare);
768 (PIkind & ObjCPropertyDecl::OBJC_PR_readonly) &&
769 property->hasAttr<IBOutletAttr>() &&
771 Diag(IC->getLocation(), diag::warn_auto_readonly_iboutlet_property);
772 Diag(property->getLocation(), diag::note_property_declare);
773 SourceLocation readonlyLoc;
774 if (LocPropertyAttribute(Context, "readonly",
775 property->getLParenLoc(), readonlyLoc)) {
776 SourceLocation endLoc =
777 readonlyLoc.getLocWithOffset(strlen("readonly")-1);
778 SourceRange ReadonlySourceRange(readonlyLoc, endLoc);
779 Diag(property->getLocation(),
780 diag::note_auto_readonly_iboutlet_fixup_suggest) <<
781 FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite");
785 DiagnoseClassAndClassExtPropertyMismatch(*this, IDecl, property);
787 } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
789 Diag(AtLoc, diag::error_synthesize_category_decl);
792 IDecl = CatImplClass->getClassInterface();
794 Diag(AtLoc, diag::error_missing_property_interface);
797 ObjCCategoryDecl *Category =
798 IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
800 // If category for this implementation not found, it is an error which
801 // has already been reported eralier.
804 // Look for this property declaration in @implementation's category
805 property = Category->FindPropertyDeclaration(PropertyId);
807 Diag(PropertyLoc, diag::error_bad_category_property_decl)
808 << Category->getDeclName();
812 Diag(AtLoc, diag::error_bad_property_context);
815 ObjCIvarDecl *Ivar = 0;
816 bool CompleteTypeErr = false;
818 // Check that we have a valid, previously declared ivar for @synthesize
822 PropertyIvar = PropertyId;
823 // Check that this is a previously declared 'ivar' in 'IDecl' interface
824 ObjCInterfaceDecl *ClassDeclared;
825 Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared);
826 QualType PropType = property->getType();
827 QualType PropertyIvarType = PropType.getNonReferenceType();
829 if (RequireCompleteType(PropertyDiagLoc, PropertyIvarType,
830 diag::err_incomplete_synthesized_property,
831 property->getDeclName())) {
832 Diag(property->getLocation(), diag::note_property_declare);
833 CompleteTypeErr = true;
836 if (getLangOpts().ObjCAutoRefCount &&
837 (property->getPropertyAttributesAsWritten() &
838 ObjCPropertyDecl::OBJC_PR_readonly) &&
839 PropertyIvarType->isObjCRetainableType()) {
840 setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar);
843 ObjCPropertyDecl::PropertyAttributeKind kind
844 = property->getPropertyAttributes();
846 // Add GC __weak to the ivar type if the property is weak.
847 if ((kind & ObjCPropertyDecl::OBJC_PR_weak) &&
848 getLangOpts().getGC() != LangOptions::NonGC) {
849 assert(!getLangOpts().ObjCAutoRefCount);
850 if (PropertyIvarType.isObjCGCStrong()) {
851 Diag(PropertyDiagLoc, diag::err_gc_weak_property_strong_type);
852 Diag(property->getLocation(), diag::note_property_declare);
855 Context.getObjCGCQualType(PropertyIvarType, Qualifiers::Weak);
858 if (AtLoc.isInvalid()) {
859 // Check when default synthesizing a property that there is
860 // an ivar matching property name and issue warning; since this
861 // is the most common case of not using an ivar used for backing
862 // property in non-default synthesis case.
863 ObjCInterfaceDecl *ClassDeclared=0;
864 ObjCIvarDecl *originalIvar =
865 IDecl->lookupInstanceVariable(property->getIdentifier(),
868 Diag(PropertyDiagLoc,
869 diag::warn_autosynthesis_property_ivar_match)
870 << PropertyId << (Ivar == 0) << PropertyIvar
871 << originalIvar->getIdentifier();
872 Diag(property->getLocation(), diag::note_property_declare);
873 Diag(originalIvar->getLocation(), diag::note_ivar_decl);
878 // In ARC, give the ivar a lifetime qualifier based on the
879 // property attributes.
880 if (getLangOpts().ObjCAutoRefCount &&
881 !PropertyIvarType.getObjCLifetime() &&
882 PropertyIvarType->isObjCRetainableType()) {
884 // It's an error if we have to do this and the user didn't
885 // explicitly write an ownership attribute on the property.
886 if (!property->hasWrittenStorageAttribute() &&
887 !(kind & ObjCPropertyDecl::OBJC_PR_strong)) {
888 Diag(PropertyDiagLoc,
889 diag::err_arc_objc_property_default_assign_on_object);
890 Diag(property->getLocation(), diag::note_property_declare);
892 Qualifiers::ObjCLifetime lifetime =
893 getImpliedARCOwnership(kind, PropertyIvarType);
894 assert(lifetime && "no lifetime for property?");
895 if (lifetime == Qualifiers::OCL_Weak) {
897 if (const ObjCObjectPointerType *ObjT =
898 PropertyIvarType->getAs<ObjCObjectPointerType>()) {
899 const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl();
900 if (ObjI && ObjI->isArcWeakrefUnavailable()) {
901 Diag(PropertyDiagLoc, diag::err_arc_weak_unavailable_property);
902 Diag(property->getLocation(), diag::note_property_declare);
906 if (!err && !getLangOpts().ObjCARCWeak) {
907 Diag(PropertyDiagLoc, diag::err_arc_weak_no_runtime);
908 Diag(property->getLocation(), diag::note_property_declare);
913 qs.addObjCLifetime(lifetime);
914 PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs);
918 if (kind & ObjCPropertyDecl::OBJC_PR_weak &&
919 !getLangOpts().ObjCAutoRefCount &&
920 getLangOpts().getGC() == LangOptions::NonGC) {
921 Diag(PropertyDiagLoc, diag::error_synthesize_weak_non_arc_or_gc);
922 Diag(property->getLocation(), diag::note_property_declare);
925 Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl,
926 PropertyIvarLoc,PropertyIvarLoc, PropertyIvar,
927 PropertyIvarType, /*Dinfo=*/0,
928 ObjCIvarDecl::Private,
931 Ivar->setInvalidDecl();
932 ClassImpDecl->addDecl(Ivar);
933 IDecl->makeDeclVisibleInContext(Ivar);
935 if (getLangOpts().ObjCRuntime.isFragile())
936 Diag(PropertyDiagLoc, diag::error_missing_property_ivar_decl)
938 // Note! I deliberately want it to fall thru so, we have a
939 // a property implementation and to avoid future warnings.
940 } else if (getLangOpts().ObjCRuntime.isNonFragile() &&
941 !declaresSameEntity(ClassDeclared, IDecl)) {
942 Diag(PropertyDiagLoc, diag::error_ivar_in_superclass_use)
943 << property->getDeclName() << Ivar->getDeclName()
944 << ClassDeclared->getDeclName();
945 Diag(Ivar->getLocation(), diag::note_previous_access_declaration)
946 << Ivar << Ivar->getName();
947 // Note! I deliberately want it to fall thru so more errors are caught.
949 property->setPropertyIvarDecl(Ivar);
951 QualType IvarType = Context.getCanonicalType(Ivar->getType());
953 // Check that type of property and its ivar are type compatible.
954 if (!Context.hasSameType(PropertyIvarType, IvarType)) {
955 if (isa<ObjCObjectPointerType>(PropertyIvarType)
956 && isa<ObjCObjectPointerType>(IvarType))
958 Context.canAssignObjCInterfaces(
959 PropertyIvarType->getAs<ObjCObjectPointerType>(),
960 IvarType->getAs<ObjCObjectPointerType>());
962 compat = (CheckAssignmentConstraints(PropertyIvarLoc, PropertyIvarType,
967 Diag(PropertyDiagLoc, diag::error_property_ivar_type)
968 << property->getDeclName() << PropType
969 << Ivar->getDeclName() << IvarType;
970 Diag(Ivar->getLocation(), diag::note_ivar_decl);
971 // Note! I deliberately want it to fall thru so, we have a
972 // a property implementation and to avoid future warnings.
975 // FIXME! Rules for properties are somewhat different that those
976 // for assignments. Use a new routine to consolidate all cases;
977 // specifically for property redeclarations as well as for ivars.
978 QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
979 QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
980 if (lhsType != rhsType &&
981 lhsType->isArithmeticType()) {
982 Diag(PropertyDiagLoc, diag::error_property_ivar_type)
983 << property->getDeclName() << PropType
984 << Ivar->getDeclName() << IvarType;
985 Diag(Ivar->getLocation(), diag::note_ivar_decl);
986 // Fall thru - see previous comment
989 // __weak is explicit. So it works on Canonical type.
990 if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
991 getLangOpts().getGC() != LangOptions::NonGC)) {
992 Diag(PropertyDiagLoc, diag::error_weak_property)
993 << property->getDeclName() << Ivar->getDeclName();
994 Diag(Ivar->getLocation(), diag::note_ivar_decl);
995 // Fall thru - see previous comment
997 // Fall thru - see previous comment
998 if ((property->getType()->isObjCObjectPointerType() ||
999 PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
1000 getLangOpts().getGC() != LangOptions::NonGC) {
1001 Diag(PropertyDiagLoc, diag::error_strong_property)
1002 << property->getDeclName() << Ivar->getDeclName();
1003 // Fall thru - see previous comment
1006 if (getLangOpts().ObjCAutoRefCount)
1007 checkARCPropertyImpl(*this, PropertyLoc, property, Ivar);
1008 } else if (PropertyIvar)
1010 Diag(PropertyDiagLoc, diag::error_dynamic_property_ivar_decl);
1012 assert (property && "ActOnPropertyImplDecl - property declaration missing");
1013 ObjCPropertyImplDecl *PIDecl =
1014 ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
1017 ObjCPropertyImplDecl::Synthesize
1018 : ObjCPropertyImplDecl::Dynamic),
1019 Ivar, PropertyIvarLoc);
1021 if (CompleteTypeErr || !compat)
1022 PIDecl->setInvalidDecl();
1024 if (ObjCMethodDecl *getterMethod = property->getGetterMethodDecl()) {
1025 getterMethod->createImplicitParams(Context, IDecl);
1026 if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
1027 Ivar->getType()->isRecordType()) {
1028 // For Objective-C++, need to synthesize the AST for the IVAR object to be
1029 // returned by the getter as it must conform to C++'s copy-return rules.
1030 // FIXME. Eventually we want to do this for Objective-C as well.
1031 SynthesizedFunctionScope Scope(*this, getterMethod);
1032 ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl();
1033 DeclRefExpr *SelfExpr =
1034 new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
1035 VK_RValue, PropertyDiagLoc);
1036 MarkDeclRefReferenced(SelfExpr);
1038 new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), PropertyDiagLoc,
1039 SelfExpr, true, true);
1041 PerformCopyInitialization(InitializedEntity::InitializeResult(
1043 getterMethod->getResultType(),
1046 Owned(IvarRefExpr));
1047 if (!Res.isInvalid()) {
1048 Expr *ResExpr = Res.takeAs<Expr>();
1050 ResExpr = MaybeCreateExprWithCleanups(ResExpr);
1051 PIDecl->setGetterCXXConstructor(ResExpr);
1054 if (property->hasAttr<NSReturnsNotRetainedAttr>() &&
1055 !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) {
1056 Diag(getterMethod->getLocation(),
1057 diag::warn_property_getter_owning_mismatch);
1058 Diag(property->getLocation(), diag::note_property_declare);
1061 if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) {
1062 setterMethod->createImplicitParams(Context, IDecl);
1063 if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr &&
1064 Ivar->getType()->isRecordType()) {
1065 // FIXME. Eventually we want to do this for Objective-C as well.
1066 SynthesizedFunctionScope Scope(*this, setterMethod);
1067 ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl();
1068 DeclRefExpr *SelfExpr =
1069 new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(),
1070 VK_RValue, PropertyDiagLoc);
1071 MarkDeclRefReferenced(SelfExpr);
1073 new (Context) ObjCIvarRefExpr(Ivar, Ivar->getType(), PropertyDiagLoc,
1074 SelfExpr, true, true);
1075 ObjCMethodDecl::param_iterator P = setterMethod->param_begin();
1076 ParmVarDecl *Param = (*P);
1077 QualType T = Param->getType().getNonReferenceType();
1078 DeclRefExpr *rhs = new (Context) DeclRefExpr(Param, false, T,
1079 VK_LValue, PropertyDiagLoc);
1080 MarkDeclRefReferenced(rhs);
1081 ExprResult Res = BuildBinOp(S, PropertyDiagLoc,
1082 BO_Assign, lhs, rhs);
1083 if (property->getPropertyAttributes() &
1084 ObjCPropertyDecl::OBJC_PR_atomic) {
1085 Expr *callExpr = Res.takeAs<Expr>();
1086 if (const CXXOperatorCallExpr *CXXCE =
1087 dyn_cast_or_null<CXXOperatorCallExpr>(callExpr))
1088 if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee())
1089 if (!FuncDecl->isTrivial())
1090 if (property->getType()->isReferenceType()) {
1091 Diag(PropertyDiagLoc,
1092 diag::err_atomic_property_nontrivial_assign_op)
1093 << property->getType();
1094 Diag(FuncDecl->getLocStart(),
1095 diag::note_callee_decl) << FuncDecl;
1098 PIDecl->setSetterCXXAssignment(Res.takeAs<Expr>());
1104 if (ObjCPropertyImplDecl *PPIDecl =
1105 IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1106 Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1107 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1109 Diag(PPIDecl->getLocation(), diag::note_previous_use);
1112 if (ObjCPropertyImplDecl *PPIDecl
1113 = IC->FindPropertyImplDecl(PropertyId)) {
1114 Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1115 Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1118 IC->addPropertyImplementation(PIDecl);
1119 if (getLangOpts().ObjCDefaultSynthProperties &&
1120 getLangOpts().ObjCRuntime.isNonFragile() &&
1121 !IDecl->isObjCRequiresPropertyDefs()) {
1122 // Diagnose if an ivar was lazily synthesdized due to a previous
1123 // use and if 1) property is @dynamic or 2) property is synthesized
1124 // but it requires an ivar of different name.
1125 ObjCInterfaceDecl *ClassDeclared=0;
1126 ObjCIvarDecl *Ivar = 0;
1128 Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
1130 if (PropertyIvar && PropertyIvar != PropertyId)
1131 Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared);
1133 // Issue diagnostics only if Ivar belongs to current class.
1134 if (Ivar && Ivar->getSynthesize() &&
1135 declaresSameEntity(IC->getClassInterface(), ClassDeclared)) {
1136 Diag(Ivar->getLocation(), diag::err_undeclared_var_use)
1138 Ivar->setInvalidDecl();
1143 if (ObjCPropertyImplDecl *PPIDecl =
1144 CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1145 Diag(PropertyDiagLoc, diag::error_duplicate_ivar_use)
1146 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1148 Diag(PPIDecl->getLocation(), diag::note_previous_use);
1151 if (ObjCPropertyImplDecl *PPIDecl =
1152 CatImplClass->FindPropertyImplDecl(PropertyId)) {
1153 Diag(PropertyDiagLoc, diag::error_property_implemented) << PropertyId;
1154 Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1157 CatImplClass->addPropertyImplementation(PIDecl);
1163 //===----------------------------------------------------------------------===//
1165 //===----------------------------------------------------------------------===//
1167 /// DiagnosePropertyMismatch - Compares two properties for their
1168 /// attributes and types and warns on a variety of inconsistencies.
1171 Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
1172 ObjCPropertyDecl *SuperProperty,
1173 const IdentifierInfo *inheritedName) {
1174 ObjCPropertyDecl::PropertyAttributeKind CAttr =
1175 Property->getPropertyAttributes();
1176 ObjCPropertyDecl::PropertyAttributeKind SAttr =
1177 SuperProperty->getPropertyAttributes();
1178 if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
1179 && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
1180 Diag(Property->getLocation(), diag::warn_readonly_property)
1181 << Property->getDeclName() << inheritedName;
1182 if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
1183 != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
1184 Diag(Property->getLocation(), diag::warn_property_attribute)
1185 << Property->getDeclName() << "copy" << inheritedName;
1186 else if (!(SAttr & ObjCPropertyDecl::OBJC_PR_readonly)){
1187 unsigned CAttrRetain =
1189 (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
1190 unsigned SAttrRetain =
1192 (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong));
1193 bool CStrong = (CAttrRetain != 0);
1194 bool SStrong = (SAttrRetain != 0);
1195 if (CStrong != SStrong)
1196 Diag(Property->getLocation(), diag::warn_property_attribute)
1197 << Property->getDeclName() << "retain (or strong)" << inheritedName;
1200 if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
1201 != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
1202 Diag(Property->getLocation(), diag::warn_property_attribute)
1203 << Property->getDeclName() << "atomic" << inheritedName;
1204 if (Property->getSetterName() != SuperProperty->getSetterName())
1205 Diag(Property->getLocation(), diag::warn_property_attribute)
1206 << Property->getDeclName() << "setter" << inheritedName;
1207 if (Property->getGetterName() != SuperProperty->getGetterName())
1208 Diag(Property->getLocation(), diag::warn_property_attribute)
1209 << Property->getDeclName() << "getter" << inheritedName;
1212 Context.getCanonicalType(SuperProperty->getType());
1214 Context.getCanonicalType(Property->getType());
1216 if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) {
1217 // Do cases not handled in above.
1218 // FIXME. For future support of covariant property types, revisit this.
1219 bool IncompatibleObjC = false;
1220 QualType ConvertedType;
1221 if (!isObjCPointerConversion(RHSType, LHSType,
1222 ConvertedType, IncompatibleObjC) ||
1224 Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
1225 << Property->getType() << SuperProperty->getType() << inheritedName;
1226 Diag(SuperProperty->getLocation(), diag::note_property_declare);
1231 bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property,
1232 ObjCMethodDecl *GetterMethod,
1233 SourceLocation Loc) {
1236 QualType GetterType = GetterMethod->getResultType().getNonReferenceType();
1237 QualType PropertyIvarType = property->getType().getNonReferenceType();
1238 bool compat = Context.hasSameType(PropertyIvarType, GetterType);
1240 if (isa<ObjCObjectPointerType>(PropertyIvarType) &&
1241 isa<ObjCObjectPointerType>(GetterType))
1243 Context.canAssignObjCInterfaces(
1244 GetterType->getAs<ObjCObjectPointerType>(),
1245 PropertyIvarType->getAs<ObjCObjectPointerType>());
1246 else if (CheckAssignmentConstraints(Loc, GetterType, PropertyIvarType)
1248 Diag(Loc, diag::error_property_accessor_type)
1249 << property->getDeclName() << PropertyIvarType
1250 << GetterMethod->getSelector() << GetterType;
1251 Diag(GetterMethod->getLocation(), diag::note_declared_at);
1255 QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType();
1256 QualType rhsType =Context.getCanonicalType(GetterType).getUnqualifiedType();
1257 if (lhsType != rhsType && lhsType->isArithmeticType())
1263 Diag(Loc, diag::warn_accessor_property_type_mismatch)
1264 << property->getDeclName()
1265 << GetterMethod->getSelector();
1266 Diag(GetterMethod->getLocation(), diag::note_declared_at);
1273 /// ComparePropertiesInBaseAndSuper - This routine compares property
1274 /// declarations in base and its super class, if any, and issues
1275 /// diagnostics in a variety of inconsistent situations.
1277 void Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
1278 ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
1282 for (ObjCInterfaceDecl::prop_iterator S = SDecl->prop_begin(),
1283 E = SDecl->prop_end(); S != E; ++S) {
1284 ObjCPropertyDecl *SuperPDecl = *S;
1285 // Does property in super class has declaration in current class?
1286 for (ObjCInterfaceDecl::prop_iterator I = IDecl->prop_begin(),
1287 E = IDecl->prop_end(); I != E; ++I) {
1288 ObjCPropertyDecl *PDecl = *I;
1289 if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
1290 DiagnosePropertyMismatch(PDecl, SuperPDecl,
1291 SDecl->getIdentifier());
1296 /// MatchOneProtocolPropertiesInClass - This routine goes thru the list
1297 /// of properties declared in a protocol and compares their attribute against
1298 /// the same property declared in the class or category.
1300 Sema::MatchOneProtocolPropertiesInClass(Decl *CDecl,
1301 ObjCProtocolDecl *PDecl) {
1302 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
1305 ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
1306 assert (CatDecl && "MatchOneProtocolPropertiesInClass");
1307 if (!CatDecl->IsClassExtension())
1308 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1309 E = PDecl->prop_end(); P != E; ++P) {
1310 ObjCPropertyDecl *Pr = *P;
1311 ObjCCategoryDecl::prop_iterator CP, CE;
1312 // Is this property already in category's list of properties?
1313 for (CP = CatDecl->prop_begin(), CE = CatDecl->prop_end(); CP!=CE; ++CP)
1314 if (CP->getIdentifier() == Pr->getIdentifier())
1317 // Property protocol already exist in class. Diagnose any mismatch.
1318 DiagnosePropertyMismatch(*CP, Pr, PDecl->getIdentifier());
1322 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1323 E = PDecl->prop_end(); P != E; ++P) {
1324 ObjCPropertyDecl *Pr = *P;
1325 ObjCInterfaceDecl::prop_iterator CP, CE;
1326 // Is this property already in class's list of properties?
1327 for (CP = IDecl->prop_begin(), CE = IDecl->prop_end(); CP != CE; ++CP)
1328 if (CP->getIdentifier() == Pr->getIdentifier())
1331 // Property protocol already exist in class. Diagnose any mismatch.
1332 DiagnosePropertyMismatch(*CP, Pr, PDecl->getIdentifier());
1336 /// CompareProperties - This routine compares properties
1337 /// declared in 'ClassOrProtocol' objects (which can be a class or an
1338 /// inherited protocol with the list of properties for class/category 'CDecl'
1340 void Sema::CompareProperties(Decl *CDecl, Decl *ClassOrProtocol) {
1341 Decl *ClassDecl = ClassOrProtocol;
1342 ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
1346 ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
1347 assert (CatDecl && "CompareProperties");
1348 if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1349 for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
1350 E = MDecl->protocol_end(); P != E; ++P)
1351 // Match properties of category with those of protocol (*P)
1352 MatchOneProtocolPropertiesInClass(CatDecl, *P);
1354 // Go thru the list of protocols for this category and recursively match
1355 // their properties with those in the category.
1356 for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
1357 E = CatDecl->protocol_end(); P != E; ++P)
1358 CompareProperties(CatDecl, *P);
1360 ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
1361 for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
1362 E = MD->protocol_end(); P != E; ++P)
1363 MatchOneProtocolPropertiesInClass(CatDecl, *P);
1368 if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1369 for (ObjCInterfaceDecl::all_protocol_iterator
1370 P = MDecl->all_referenced_protocol_begin(),
1371 E = MDecl->all_referenced_protocol_end(); P != E; ++P)
1372 // Match properties of class IDecl with those of protocol (*P).
1373 MatchOneProtocolPropertiesInClass(IDecl, *P);
1375 // Go thru the list of protocols for this class and recursively match
1376 // their properties with those declared in the class.
1377 for (ObjCInterfaceDecl::all_protocol_iterator
1378 P = IDecl->all_referenced_protocol_begin(),
1379 E = IDecl->all_referenced_protocol_end(); P != E; ++P)
1380 CompareProperties(IDecl, *P);
1382 ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
1383 for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
1384 E = MD->protocol_end(); P != E; ++P)
1385 MatchOneProtocolPropertiesInClass(IDecl, *P);
1389 /// isPropertyReadonly - Return true if property is readonly, by searching
1390 /// for the property in the class and in its categories and implementations
1392 bool Sema::isPropertyReadonly(ObjCPropertyDecl *PDecl,
1393 ObjCInterfaceDecl *IDecl) {
1394 // by far the most common case.
1395 if (!PDecl->isReadOnly())
1397 // Even if property is ready only, if interface has a user defined setter,
1398 // it is not considered read only.
1399 if (IDecl->getInstanceMethod(PDecl->getSetterName()))
1402 // Main class has the property as 'readonly'. Must search
1403 // through the category list to see if the property's
1404 // attribute has been over-ridden to 'readwrite'.
1405 for (ObjCCategoryDecl *Category = IDecl->getCategoryList();
1406 Category; Category = Category->getNextClassCategory()) {
1407 // Even if property is ready only, if a category has a user defined setter,
1408 // it is not considered read only.
1409 if (Category->getInstanceMethod(PDecl->getSetterName()))
1411 ObjCPropertyDecl *P =
1412 Category->FindPropertyDeclaration(PDecl->getIdentifier());
1413 if (P && !P->isReadOnly())
1417 // Also, check for definition of a setter method in the implementation if
1419 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurContext)) {
1420 if (ObjCImplementationDecl *IMD =
1421 dyn_cast<ObjCImplementationDecl>(OMD->getDeclContext())) {
1422 if (IMD->getInstanceMethod(PDecl->getSetterName()))
1424 } else if (ObjCCategoryImplDecl *CIMD =
1425 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1426 if (CIMD->getInstanceMethod(PDecl->getSetterName()))
1430 // Lastly, look through the implementation (if one is in scope).
1431 if (ObjCImplementationDecl *ImpDecl = IDecl->getImplementation())
1432 if (ImpDecl->getInstanceMethod(PDecl->getSetterName()))
1434 // If all fails, look at the super class.
1435 if (ObjCInterfaceDecl *SIDecl = IDecl->getSuperClass())
1436 return isPropertyReadonly(PDecl, SIDecl);
1440 /// CollectImmediateProperties - This routine collects all properties in
1441 /// the class and its conforming protocols; but not those it its super class.
1442 void Sema::CollectImmediateProperties(ObjCContainerDecl *CDecl,
1443 ObjCContainerDecl::PropertyMap &PropMap,
1444 ObjCContainerDecl::PropertyMap &SuperPropMap) {
1445 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1446 for (ObjCContainerDecl::prop_iterator P = IDecl->prop_begin(),
1447 E = IDecl->prop_end(); P != E; ++P) {
1448 ObjCPropertyDecl *Prop = *P;
1449 PropMap[Prop->getIdentifier()] = Prop;
1451 // scan through class's protocols.
1452 for (ObjCInterfaceDecl::all_protocol_iterator
1453 PI = IDecl->all_referenced_protocol_begin(),
1454 E = IDecl->all_referenced_protocol_end(); PI != E; ++PI)
1455 CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1457 if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1458 if (!CATDecl->IsClassExtension())
1459 for (ObjCContainerDecl::prop_iterator P = CATDecl->prop_begin(),
1460 E = CATDecl->prop_end(); P != E; ++P) {
1461 ObjCPropertyDecl *Prop = *P;
1462 PropMap[Prop->getIdentifier()] = Prop;
1464 // scan through class's protocols.
1465 for (ObjCCategoryDecl::protocol_iterator PI = CATDecl->protocol_begin(),
1466 E = CATDecl->protocol_end(); PI != E; ++PI)
1467 CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1469 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) {
1470 for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
1471 E = PDecl->prop_end(); P != E; ++P) {
1472 ObjCPropertyDecl *Prop = *P;
1473 ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[Prop->getIdentifier()];
1474 // Exclude property for protocols which conform to class's super-class,
1475 // as super-class has to implement the property.
1476 if (!PropertyFromSuper ||
1477 PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) {
1478 ObjCPropertyDecl *&PropEntry = PropMap[Prop->getIdentifier()];
1483 // scan through protocol's protocols.
1484 for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1485 E = PDecl->protocol_end(); PI != E; ++PI)
1486 CollectImmediateProperties((*PI), PropMap, SuperPropMap);
1490 /// CollectSuperClassPropertyImplementations - This routine collects list of
1491 /// properties to be implemented in super class(s) and also coming from their
1492 /// conforming protocols.
1493 static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl,
1494 ObjCInterfaceDecl::PropertyMap &PropMap) {
1495 if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) {
1497 SDecl->collectPropertiesToImplement(PropMap);
1498 SDecl = SDecl->getSuperClass();
1503 /// \brief Default synthesizes all properties which must be synthesized
1504 /// in class's \@implementation.
1505 void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl* IMPDecl,
1506 ObjCInterfaceDecl *IDecl) {
1508 ObjCInterfaceDecl::PropertyMap PropMap;
1509 IDecl->collectPropertiesToImplement(PropMap);
1510 if (PropMap.empty())
1512 ObjCInterfaceDecl::PropertyMap SuperPropMap;
1513 CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
1515 for (ObjCInterfaceDecl::PropertyMap::iterator
1516 P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
1517 ObjCPropertyDecl *Prop = P->second;
1518 // If property to be implemented in the super class, ignore.
1519 if (SuperPropMap[Prop->getIdentifier()])
1521 // Is there a matching property synthesize/dynamic?
1522 if (Prop->isInvalidDecl() ||
1523 Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
1524 IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier()))
1526 // Property may have been synthesized by user.
1527 if (IMPDecl->FindPropertyImplDecl(Prop->getIdentifier()))
1529 if (IMPDecl->getInstanceMethod(Prop->getGetterName())) {
1530 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly)
1532 if (IMPDecl->getInstanceMethod(Prop->getSetterName()))
1535 if (isa<ObjCProtocolDecl>(Prop->getDeclContext())) {
1536 // We won't auto-synthesize properties declared in protocols.
1537 Diag(IMPDecl->getLocation(),
1538 diag::warn_auto_synthesizing_protocol_property);
1539 Diag(Prop->getLocation(), diag::note_property_declare);
1543 // We use invalid SourceLocations for the synthesized ivars since they
1544 // aren't really synthesized at a particular location; they just exist.
1545 // Saying that they are located at the @implementation isn't really going
1547 ObjCPropertyImplDecl *PIDecl = dyn_cast_or_null<ObjCPropertyImplDecl>(
1548 ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(),
1550 /* property = */ Prop->getIdentifier(),
1551 /* ivar = */ Prop->getDefaultSynthIvarName(Context),
1552 Prop->getLocation()));
1554 Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis);
1555 Diag(IMPDecl->getLocation(), diag::note_while_in_implementation);
1560 void Sema::DefaultSynthesizeProperties(Scope *S, Decl *D) {
1561 if (!LangOpts.ObjCDefaultSynthProperties || LangOpts.ObjCRuntime.isFragile())
1563 ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D);
1566 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
1567 if (!IDecl->isObjCRequiresPropertyDefs())
1568 DefaultSynthesizeProperties(S, IC, IDecl);
1571 void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl,
1572 ObjCContainerDecl *CDecl,
1573 const SelectorSet &InsMap) {
1574 ObjCContainerDecl::PropertyMap SuperPropMap;
1575 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl))
1576 CollectSuperClassPropertyImplementations(IDecl, SuperPropMap);
1578 ObjCContainerDecl::PropertyMap PropMap;
1579 CollectImmediateProperties(CDecl, PropMap, SuperPropMap);
1580 if (PropMap.empty())
1583 llvm::DenseSet<ObjCPropertyDecl *> PropImplMap;
1584 for (ObjCImplDecl::propimpl_iterator
1585 I = IMPDecl->propimpl_begin(),
1586 EI = IMPDecl->propimpl_end(); I != EI; ++I)
1587 PropImplMap.insert(I->getPropertyDecl());
1589 for (ObjCContainerDecl::PropertyMap::iterator
1590 P = PropMap.begin(), E = PropMap.end(); P != E; ++P) {
1591 ObjCPropertyDecl *Prop = P->second;
1592 // Is there a matching propery synthesize/dynamic?
1593 if (Prop->isInvalidDecl() ||
1594 Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional ||
1595 PropImplMap.count(Prop) || Prop->hasAttr<UnavailableAttr>())
1597 if (!InsMap.count(Prop->getGetterName())) {
1598 Diag(IMPDecl->getLocation(),
1599 isa<ObjCCategoryDecl>(CDecl) ?
1600 diag::warn_setter_getter_impl_required_in_category :
1601 diag::warn_setter_getter_impl_required)
1602 << Prop->getDeclName() << Prop->getGetterName();
1603 Diag(Prop->getLocation(),
1604 diag::note_property_declare);
1605 if (LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCRuntime.isNonFragile())
1606 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl))
1607 if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs())
1608 Diag(RID->getLocation(), diag::note_suppressed_class_declare);
1612 if (!Prop->isReadOnly() && !InsMap.count(Prop->getSetterName())) {
1613 Diag(IMPDecl->getLocation(),
1614 isa<ObjCCategoryDecl>(CDecl) ?
1615 diag::warn_setter_getter_impl_required_in_category :
1616 diag::warn_setter_getter_impl_required)
1617 << Prop->getDeclName() << Prop->getSetterName();
1618 Diag(Prop->getLocation(),
1619 diag::note_property_declare);
1620 if (LangOpts.ObjCDefaultSynthProperties && LangOpts.ObjCRuntime.isNonFragile())
1621 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl))
1622 if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs())
1623 Diag(RID->getLocation(), diag::note_suppressed_class_declare);
1629 Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl,
1630 ObjCContainerDecl* IDecl) {
1631 // Rules apply in non-GC mode only
1632 if (getLangOpts().getGC() != LangOptions::NonGC)
1634 for (ObjCContainerDecl::prop_iterator I = IDecl->prop_begin(),
1635 E = IDecl->prop_end();
1637 ObjCPropertyDecl *Property = *I;
1638 ObjCMethodDecl *GetterMethod = 0;
1639 ObjCMethodDecl *SetterMethod = 0;
1640 bool LookedUpGetterSetter = false;
1642 unsigned Attributes = Property->getPropertyAttributes();
1643 unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten();
1645 if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic) &&
1646 !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_nonatomic)) {
1647 GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
1648 SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
1649 LookedUpGetterSetter = true;
1651 Diag(GetterMethod->getLocation(),
1652 diag::warn_default_atomic_custom_getter_setter)
1653 << Property->getIdentifier() << 0;
1654 Diag(Property->getLocation(), diag::note_property_declare);
1657 Diag(SetterMethod->getLocation(),
1658 diag::warn_default_atomic_custom_getter_setter)
1659 << Property->getIdentifier() << 1;
1660 Diag(Property->getLocation(), diag::note_property_declare);
1664 // We only care about readwrite atomic property.
1665 if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) ||
1666 !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite))
1668 if (const ObjCPropertyImplDecl *PIDecl
1669 = IMPDecl->FindPropertyImplDecl(Property->getIdentifier())) {
1670 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
1672 if (!LookedUpGetterSetter) {
1673 GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName());
1674 SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName());
1675 LookedUpGetterSetter = true;
1677 if ((GetterMethod && !SetterMethod) || (!GetterMethod && SetterMethod)) {
1678 SourceLocation MethodLoc =
1679 (GetterMethod ? GetterMethod->getLocation()
1680 : SetterMethod->getLocation());
1681 Diag(MethodLoc, diag::warn_atomic_property_rule)
1682 << Property->getIdentifier() << (GetterMethod != 0)
1683 << (SetterMethod != 0);
1685 if (!AttributesAsWritten) {
1686 if (Property->getLParenLoc().isValid()) {
1687 // @property () ... case.
1688 SourceRange PropSourceRange(Property->getAtLoc(),
1689 Property->getLParenLoc());
1690 Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
1691 FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic");
1695 SourceLocation endLoc =
1696 Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc();
1697 endLoc = endLoc.getLocWithOffset(-1);
1698 SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
1699 Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
1700 FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic) ");
1703 else if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic)) {
1704 // @property () ... case.
1705 SourceLocation endLoc = Property->getLParenLoc();
1706 SourceRange PropSourceRange(Property->getAtLoc(), endLoc);
1707 Diag(Property->getLocation(), diag::note_atomic_property_fixup_suggest) <<
1708 FixItHint::CreateReplacement(PropSourceRange, "@property (nonatomic, ");
1711 Diag(MethodLoc, diag::note_atomic_property_fixup_suggest);
1712 Diag(Property->getLocation(), diag::note_property_declare);
1718 void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D) {
1719 if (getLangOpts().getGC() == LangOptions::GCOnly)
1722 for (ObjCImplementationDecl::propimpl_iterator
1723 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
1724 ObjCPropertyImplDecl *PID = *i;
1725 if (PID->getPropertyImplementation() != ObjCPropertyImplDecl::Synthesize)
1728 const ObjCPropertyDecl *PD = PID->getPropertyDecl();
1729 if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() &&
1730 !D->getInstanceMethod(PD->getGetterName())) {
1731 ObjCMethodDecl *method = PD->getGetterMethodDecl();
1734 ObjCMethodFamily family = method->getMethodFamily();
1735 if (family == OMF_alloc || family == OMF_copy ||
1736 family == OMF_mutableCopy || family == OMF_new) {
1737 if (getLangOpts().ObjCAutoRefCount)
1738 Diag(PID->getLocation(), diag::err_ownin_getter_rule);
1740 Diag(PID->getLocation(), diag::warn_owning_getter_rule);
1741 Diag(PD->getLocation(), diag::note_property_declare);
1747 /// AddPropertyAttrs - Propagates attributes from a property to the
1748 /// implicitly-declared getter or setter for that property.
1749 static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod,
1750 ObjCPropertyDecl *Property) {
1751 // Should we just clone all attributes over?
1752 for (Decl::attr_iterator A = Property->attr_begin(),
1753 AEnd = Property->attr_end();
1755 if (isa<DeprecatedAttr>(*A) ||
1756 isa<UnavailableAttr>(*A) ||
1757 isa<AvailabilityAttr>(*A))
1758 PropertyMethod->addAttr((*A)->clone(S.Context));
1762 /// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1763 /// have the property type and issue diagnostics if they don't.
1764 /// Also synthesize a getter/setter method if none exist (and update the
1765 /// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1766 /// methods is the "right" thing to do.
1767 void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1768 ObjCContainerDecl *CD,
1769 ObjCPropertyDecl *redeclaredProperty,
1770 ObjCContainerDecl *lexicalDC) {
1772 ObjCMethodDecl *GetterMethod, *SetterMethod;
1774 GetterMethod = CD->getInstanceMethod(property->getGetterName());
1775 SetterMethod = CD->getInstanceMethod(property->getSetterName());
1776 DiagnosePropertyAccessorMismatch(property, GetterMethod,
1777 property->getLocation());
1780 ObjCPropertyDecl::PropertyAttributeKind CAttr =
1781 property->getPropertyAttributes();
1782 if ((!(CAttr & ObjCPropertyDecl::OBJC_PR_readonly)) &&
1783 Context.getCanonicalType(SetterMethod->getResultType()) !=
1785 Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1786 if (SetterMethod->param_size() != 1 ||
1787 !Context.hasSameUnqualifiedType(
1788 (*SetterMethod->param_begin())->getType().getNonReferenceType(),
1789 property->getType().getNonReferenceType())) {
1790 Diag(property->getLocation(),
1791 diag::warn_accessor_property_type_mismatch)
1792 << property->getDeclName()
1793 << SetterMethod->getSelector();
1794 Diag(SetterMethod->getLocation(), diag::note_declared_at);
1798 // Synthesize getter/setter methods if none exist.
1799 // Find the default getter and if one not found, add one.
1800 // FIXME: The synthesized property we set here is misleading. We almost always
1801 // synthesize these methods unless the user explicitly provided prototypes
1802 // (which is odd, but allowed). Sema should be typechecking that the
1803 // declarations jive in that situation (which it is not currently).
1804 if (!GetterMethod) {
1805 // No instance method of same name as property getter name was found.
1806 // Declare a getter method and add it to the list of methods
1808 SourceLocation Loc = redeclaredProperty ?
1809 redeclaredProperty->getLocation() :
1810 property->getLocation();
1812 GetterMethod = ObjCMethodDecl::Create(Context, Loc, Loc,
1813 property->getGetterName(),
1814 property->getType(), 0, CD, /*isInstance=*/true,
1815 /*isVariadic=*/false, /*isPropertyAccessor=*/true,
1816 /*isImplicitlyDeclared=*/true, /*isDefined=*/false,
1817 (property->getPropertyImplementation() ==
1818 ObjCPropertyDecl::Optional) ?
1819 ObjCMethodDecl::Optional :
1820 ObjCMethodDecl::Required);
1821 CD->addDecl(GetterMethod);
1823 AddPropertyAttrs(*this, GetterMethod, property);
1825 // FIXME: Eventually this shouldn't be needed, as the lexical context
1826 // and the real context should be the same.
1828 GetterMethod->setLexicalDeclContext(lexicalDC);
1829 if (property->hasAttr<NSReturnsNotRetainedAttr>())
1830 GetterMethod->addAttr(
1831 ::new (Context) NSReturnsNotRetainedAttr(Loc, Context));
1833 // A user declared getter will be synthesize when @synthesize of
1834 // the property with the same name is seen in the @implementation
1835 GetterMethod->setPropertyAccessor(true);
1836 property->setGetterMethodDecl(GetterMethod);
1838 // Skip setter if property is read-only.
1839 if (!property->isReadOnly()) {
1840 // Find the default setter and if one not found, add one.
1841 if (!SetterMethod) {
1842 // No instance method of same name as property setter name was found.
1843 // Declare a setter method and add it to the list of methods
1845 SourceLocation Loc = redeclaredProperty ?
1846 redeclaredProperty->getLocation() :
1847 property->getLocation();
1850 ObjCMethodDecl::Create(Context, Loc, Loc,
1851 property->getSetterName(), Context.VoidTy, 0,
1852 CD, /*isInstance=*/true, /*isVariadic=*/false,
1853 /*isPropertyAccessor=*/true,
1854 /*isImplicitlyDeclared=*/true,
1855 /*isDefined=*/false,
1856 (property->getPropertyImplementation() ==
1857 ObjCPropertyDecl::Optional) ?
1858 ObjCMethodDecl::Optional :
1859 ObjCMethodDecl::Required);
1861 // Invent the arguments for the setter. We don't bother making a
1862 // nice name for the argument.
1863 ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
1865 property->getIdentifier(),
1866 property->getType().getUnqualifiedType(),
1871 SetterMethod->setMethodParams(Context, Argument,
1872 ArrayRef<SourceLocation>());
1874 AddPropertyAttrs(*this, SetterMethod, property);
1876 CD->addDecl(SetterMethod);
1877 // FIXME: Eventually this shouldn't be needed, as the lexical context
1878 // and the real context should be the same.
1880 SetterMethod->setLexicalDeclContext(lexicalDC);
1882 // A user declared setter will be synthesize when @synthesize of
1883 // the property with the same name is seen in the @implementation
1884 SetterMethod->setPropertyAccessor(true);
1885 property->setSetterMethodDecl(SetterMethod);
1887 // Add any synthesized methods to the global pool. This allows us to
1888 // handle the following, which is supported by GCC (and part of the design).
1891 // @property double bar;
1894 // void thisIsUnfortunate() {
1896 // double bar = [foo bar];
1900 AddInstanceMethodToGlobalPool(GetterMethod);
1902 AddInstanceMethodToGlobalPool(SetterMethod);
1904 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(CD);
1905 if (!CurrentClass) {
1906 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CD))
1907 CurrentClass = Cat->getClassInterface();
1908 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(CD))
1909 CurrentClass = Impl->getClassInterface();
1912 CheckObjCMethodOverrides(GetterMethod, CurrentClass, Sema::RTC_Unknown);
1914 CheckObjCMethodOverrides(SetterMethod, CurrentClass, Sema::RTC_Unknown);
1917 void Sema::CheckObjCPropertyAttributes(Decl *PDecl,
1919 unsigned &Attributes,
1920 bool propertyInPrimaryClass) {
1921 // FIXME: Improve the reported location.
1922 if (!PDecl || PDecl->isInvalidDecl())
1925 ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl);
1926 QualType PropertyTy = PropertyDecl->getType();
1928 if (getLangOpts().ObjCAutoRefCount &&
1929 (Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1930 PropertyTy->isObjCRetainableType()) {
1931 // 'readonly' property with no obvious lifetime.
1932 // its life time will be determined by its backing ivar.
1933 unsigned rel = (ObjCDeclSpec::DQ_PR_unsafe_unretained |
1934 ObjCDeclSpec::DQ_PR_copy |
1935 ObjCDeclSpec::DQ_PR_retain |
1936 ObjCDeclSpec::DQ_PR_strong |
1937 ObjCDeclSpec::DQ_PR_weak |
1938 ObjCDeclSpec::DQ_PR_assign);
1939 if ((Attributes & rel) == 0)
1943 if (propertyInPrimaryClass) {
1944 // we postpone most property diagnosis until class's implementation
1945 // because, its readonly attribute may be overridden in its class
1946 // extensions making other attributes, which make no sense, to make sense.
1947 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1948 (Attributes & ObjCDeclSpec::DQ_PR_readwrite))
1949 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1950 << "readonly" << "readwrite";
1952 // readonly and readwrite/assign/retain/copy conflict.
1953 else if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1954 (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1955 ObjCDeclSpec::DQ_PR_assign |
1956 ObjCDeclSpec::DQ_PR_unsafe_unretained |
1957 ObjCDeclSpec::DQ_PR_copy |
1958 ObjCDeclSpec::DQ_PR_retain |
1959 ObjCDeclSpec::DQ_PR_strong))) {
1960 const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1962 (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1964 (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) ?
1965 "unsafe_unretained" :
1966 (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
1969 Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
1970 diag::err_objc_property_attr_mutually_exclusive :
1971 diag::warn_objc_property_attr_mutually_exclusive)
1972 << "readonly" << which;
1975 // Check for copy or retain on non-object types.
1976 if ((Attributes & (ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy |
1977 ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong)) &&
1978 !PropertyTy->isObjCRetainableType() &&
1979 !PropertyDecl->getAttr<ObjCNSObjectAttr>()) {
1980 Diag(Loc, diag::err_objc_property_requires_object)
1981 << (Attributes & ObjCDeclSpec::DQ_PR_weak ? "weak" :
1982 Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or strong)");
1983 Attributes &= ~(ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy |
1984 ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong);
1985 PropertyDecl->setInvalidDecl();
1988 // Check for more than one of { assign, copy, retain }.
1989 if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
1990 if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1991 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1992 << "assign" << "copy";
1993 Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1995 if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1996 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1997 << "assign" << "retain";
1998 Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2000 if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
2001 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2002 << "assign" << "strong";
2003 Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
2005 if (getLangOpts().ObjCAutoRefCount &&
2006 (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2007 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2008 << "assign" << "weak";
2009 Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2011 } else if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) {
2012 if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
2013 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2014 << "unsafe_unretained" << "copy";
2015 Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
2017 if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
2018 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2019 << "unsafe_unretained" << "retain";
2020 Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2022 if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
2023 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2024 << "unsafe_unretained" << "strong";
2025 Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
2027 if (getLangOpts().ObjCAutoRefCount &&
2028 (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2029 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2030 << "unsafe_unretained" << "weak";
2031 Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2033 } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
2034 if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
2035 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2036 << "copy" << "retain";
2037 Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2039 if (Attributes & ObjCDeclSpec::DQ_PR_strong) {
2040 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2041 << "copy" << "strong";
2042 Attributes &= ~ObjCDeclSpec::DQ_PR_strong;
2044 if (Attributes & ObjCDeclSpec::DQ_PR_weak) {
2045 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2046 << "copy" << "weak";
2047 Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2050 else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
2051 (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2052 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2053 << "retain" << "weak";
2054 Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
2056 else if ((Attributes & ObjCDeclSpec::DQ_PR_strong) &&
2057 (Attributes & ObjCDeclSpec::DQ_PR_weak)) {
2058 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2059 << "strong" << "weak";
2060 Attributes &= ~ObjCDeclSpec::DQ_PR_weak;
2063 if ((Attributes & ObjCDeclSpec::DQ_PR_atomic) &&
2064 (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)) {
2065 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
2066 << "atomic" << "nonatomic";
2067 Attributes &= ~ObjCDeclSpec::DQ_PR_atomic;
2070 // Warn if user supplied no assignment attribute, property is
2071 // readwrite, and this is an object type.
2072 if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
2073 ObjCDeclSpec::DQ_PR_unsafe_unretained |
2074 ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong |
2075 ObjCDeclSpec::DQ_PR_weak)) &&
2076 PropertyTy->isObjCObjectPointerType()) {
2077 if (getLangOpts().ObjCAutoRefCount)
2078 // With arc, @property definitions should default to (strong) when
2079 // not specified; including when property is 'readonly'.
2080 PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong);
2081 else if (!(Attributes & ObjCDeclSpec::DQ_PR_readonly)) {
2083 (PropertyTy->isObjCClassType() ||
2084 PropertyTy->isObjCQualifiedClassType());
2085 // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to
2086 // issue any warning.
2087 if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC)
2089 else if (propertyInPrimaryClass) {
2090 // Don't issue warning on property with no life time in class
2091 // extension as it is inherited from property in primary class.
2092 // Skip this warning in gc-only mode.
2093 if (getLangOpts().getGC() != LangOptions::GCOnly)
2094 Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
2096 // If non-gc code warn that this is likely inappropriate.
2097 if (getLangOpts().getGC() == LangOptions::NonGC)
2098 Diag(Loc, diag::warn_objc_property_default_assign_on_object);
2102 // FIXME: Implement warning dependent on NSCopying being
2103 // implemented. See also:
2104 // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
2105 // (please trim this list while you are at it).
2108 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy)
2109 &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly)
2110 && getLangOpts().getGC() == LangOptions::GCOnly
2111 && PropertyTy->isBlockPointerType())
2112 Diag(Loc, diag::warn_objc_property_copy_missing_on_block);
2113 else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) &&
2114 !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2115 !(Attributes & ObjCDeclSpec::DQ_PR_strong) &&
2116 PropertyTy->isBlockPointerType())
2117 Diag(Loc, diag::warn_objc_property_retain_of_block);
2119 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
2120 (Attributes & ObjCDeclSpec::DQ_PR_setter))
2121 Diag(Loc, diag::warn_objc_readonly_property_has_setter);