1//===--- SemaObjCProperty.cpp - Semantic Analysis for ObjC @property ------===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements semantic analysis for Objective C @property and 11// @synthesize declarations. 12// 13//===----------------------------------------------------------------------===// 14 15#include "clang/Sema/SemaInternal.h" 16#include "clang/AST/ASTMutationListener.h" 17#include "clang/AST/DeclObjC.h" 18#include "clang/AST/ExprCXX.h" 19#include "clang/AST/ExprObjC.h" 20#include "clang/Basic/SourceManager.h" 21#include "clang/Lex/Lexer.h" 22#include "clang/Lex/Preprocessor.h" 23#include "clang/Sema/Initialization.h" 24#include "llvm/ADT/DenseSet.h" 25#include "llvm/ADT/SmallString.h" 26 27using namespace clang; 28 29//===----------------------------------------------------------------------===// 30// Grammar actions. 31//===----------------------------------------------------------------------===// 32 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. 36/// 37/// Returns OCL_None if the attributes as stated do not imply an ownership. 38/// Never returns OCL_Autoreleasing. 39static Qualifiers::ObjCLifetime getImpliedARCOwnership( 40 ObjCPropertyDecl::PropertyAttributeKind attrs, 41 QualType type) { 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; 52 } 53 54 // assign can appear on other types, so we have to check the 55 // property type. 56 if (attrs & ObjCPropertyDecl::OBJC_PR_assign && 57 type->isObjCRetainableType()) { 58 return Qualifiers::OCL_ExplicitNone; 59 } 60 61 return Qualifiers::OCL_None; 62} 63 64/// Check the internal consistency of a property declaration with 65/// an explicit ownership qualifier. 66static void checkPropertyDeclWithOwnership(Sema &S, 67 ObjCPropertyDecl *property) { 68 if (property->isInvalidDecl()) return; 69 70 ObjCPropertyDecl::PropertyAttributeKind propertyKind 71 = property->getPropertyAttributes(); 72 Qualifiers::ObjCLifetime propertyLifetime 73 = property->getType().getObjCLifetime(); 74 75 assert(propertyLifetime != Qualifiers::OCL_None); 76 77 Qualifiers::ObjCLifetime expectedLifetime 78 = getImpliedARCOwnership(propertyKind, property->getType()); 79 if (!expectedLifetime) { 80 // We have a lifetime qualifier but no dominating property 81 // attribute. That's okay, but restore reasonable invariants by 82 // setting the property attribute according to the lifetime 83 // qualifier. 84 ObjCPropertyDecl::PropertyAttributeKind attr; 85 if (propertyLifetime == Qualifiers::OCL_Strong) { 86 attr = ObjCPropertyDecl::OBJC_PR_strong; 87 } else if (propertyLifetime == Qualifiers::OCL_Weak) { 88 attr = ObjCPropertyDecl::OBJC_PR_weak; 89 } else { 90 assert(propertyLifetime == Qualifiers::OCL_ExplicitNone); 91 attr = ObjCPropertyDecl::OBJC_PR_unsafe_unretained; 92 } 93 property->setPropertyAttributes(attr); 94 return; 95 } 96 97 if (propertyLifetime == expectedLifetime) return; 98 99 property->setInvalidDecl(); 100 S.Diag(property->getLocation(), 101 diag::err_arc_inconsistent_property_ownership) 102 << property->getDeclName() 103 << expectedLifetime 104 << propertyLifetime; 105} 106 107/// \brief Check this Objective-C property against a property declared in the 108/// given protocol. 109static void 110CheckPropertyAgainstProtocol(Sema &S, ObjCPropertyDecl *Prop, 111 ObjCProtocolDecl *Proto, 112 llvm::SmallPtrSetImpl<ObjCProtocolDecl *> &Known) { 113 // Have we seen this protocol before? 114 if (!Known.insert(Proto).second) 115 return; 116 117 // Look for a property with the same name. 118 DeclContext::lookup_result R = Proto->lookup(Prop->getDeclName()); 119 for (unsigned I = 0, N = R.size(); I != N; ++I) { 120 if (ObjCPropertyDecl *ProtoProp = dyn_cast<ObjCPropertyDecl>(R[I])) { 121 S.DiagnosePropertyMismatch(Prop, ProtoProp, Proto->getIdentifier(), true); 122 return; 123 } 124 } 125 126 // Check this property against any protocols we inherit. 127 for (auto *P : Proto->protocols()) 128 CheckPropertyAgainstProtocol(S, Prop, P, Known); 129} 130 131static unsigned deducePropertyOwnershipFromType(Sema &S, QualType T) { 132 // In GC mode, just look for the __weak qualifier. 133 if (S.getLangOpts().getGC() != LangOptions::NonGC) { 134 if (T.isObjCGCWeak()) return ObjCDeclSpec::DQ_PR_weak; 135 136 // In ARC/MRC, look for an explicit ownership qualifier. 137 // For some reason, this only applies to __weak. 138 } else if (auto ownership = T.getObjCLifetime()) { 139 switch (ownership) { 140 case Qualifiers::OCL_Weak: 141 return ObjCDeclSpec::DQ_PR_weak; 142 case Qualifiers::OCL_Strong: 143 return ObjCDeclSpec::DQ_PR_strong; 144 case Qualifiers::OCL_ExplicitNone: 145 return ObjCDeclSpec::DQ_PR_unsafe_unretained; 146 case Qualifiers::OCL_Autoreleasing: 147 case Qualifiers::OCL_None: 148 return 0; 149 } 150 llvm_unreachable("bad qualifier"); 151 } 152 153 return 0; 154} 155 156static const unsigned OwnershipMask = 157 (ObjCPropertyDecl::OBJC_PR_assign | 158 ObjCPropertyDecl::OBJC_PR_retain | 159 ObjCPropertyDecl::OBJC_PR_copy | 160 ObjCPropertyDecl::OBJC_PR_weak | 161 ObjCPropertyDecl::OBJC_PR_strong | 162 ObjCPropertyDecl::OBJC_PR_unsafe_unretained); 163 164static unsigned getOwnershipRule(unsigned attr) { 165 unsigned result = attr & OwnershipMask; 166 167 // From an ownership perspective, assign and unsafe_unretained are 168 // identical; make sure one also implies the other. 169 if (result & (ObjCPropertyDecl::OBJC_PR_assign | 170 ObjCPropertyDecl::OBJC_PR_unsafe_unretained)) { 171 result |= ObjCPropertyDecl::OBJC_PR_assign | 172 ObjCPropertyDecl::OBJC_PR_unsafe_unretained; 173 } 174 175 return result; 176} 177 178Decl *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc, 179 SourceLocation LParenLoc, 180 FieldDeclarator &FD, 181 ObjCDeclSpec &ODS, 182 Selector GetterSel, 183 Selector SetterSel, 184 tok::ObjCKeywordKind MethodImplKind, 185 DeclContext *lexicalDC) { 186 unsigned Attributes = ODS.getPropertyAttributes(); 187 FD.D.setObjCWeakProperty((Attributes & ObjCDeclSpec::DQ_PR_weak) != 0); 188 TypeSourceInfo *TSI = GetTypeForDeclarator(FD.D, S); 189 QualType T = TSI->getType(); 190 if (!getOwnershipRule(Attributes)) { 191 Attributes |= deducePropertyOwnershipFromType(*this, T); 192 } 193 bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) || 194 // default is readwrite! 195 !(Attributes & ObjCDeclSpec::DQ_PR_readonly)); 196 197 // Proceed with constructing the ObjCPropertyDecls. 198 ObjCContainerDecl *ClassDecl = cast<ObjCContainerDecl>(CurContext); 199 ObjCPropertyDecl *Res = nullptr; 200 if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 201 if (CDecl->IsClassExtension()) { 202 Res = HandlePropertyInClassExtension(S, AtLoc, LParenLoc, 203 FD, GetterSel, SetterSel, 204 isReadWrite, 205 Attributes, 206 ODS.getPropertyAttributes(), 207 T, TSI, MethodImplKind); 208 if (!Res) 209 return nullptr; 210 } 211 } 212 213 if (!Res) { 214 Res = CreatePropertyDecl(S, ClassDecl, AtLoc, LParenLoc, FD, 215 GetterSel, SetterSel, isReadWrite, 216 Attributes, ODS.getPropertyAttributes(), 217 T, TSI, MethodImplKind); 218 if (lexicalDC) 219 Res->setLexicalDeclContext(lexicalDC); 220 } 221 222 // Validate the attributes on the @property. 223 CheckObjCPropertyAttributes(Res, AtLoc, Attributes, 224 (isa<ObjCInterfaceDecl>(ClassDecl) || 225 isa<ObjCProtocolDecl>(ClassDecl))); 226 227 // Check consistency if the type has explicit ownership qualification. 228 if (Res->getType().getObjCLifetime()) 229 checkPropertyDeclWithOwnership(*this, Res); 230 231 llvm::SmallPtrSet<ObjCProtocolDecl *, 16> KnownProtos; 232 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) { 233 // For a class, compare the property against a property in our superclass. 234 bool FoundInSuper = false; 235 ObjCInterfaceDecl *CurrentInterfaceDecl = IFace; 236 while (ObjCInterfaceDecl *Super = CurrentInterfaceDecl->getSuperClass()) { 237 DeclContext::lookup_result R = Super->lookup(Res->getDeclName()); 238 for (unsigned I = 0, N = R.size(); I != N; ++I) { 239 if (ObjCPropertyDecl *SuperProp = dyn_cast<ObjCPropertyDecl>(R[I])) { 240 DiagnosePropertyMismatch(Res, SuperProp, Super->getIdentifier(), false); 241 FoundInSuper = true; 242 break; 243 } 244 } 245 if (FoundInSuper) 246 break; 247 else 248 CurrentInterfaceDecl = Super; 249 } 250 251 if (FoundInSuper) { 252 // Also compare the property against a property in our protocols. 253 for (auto *P : CurrentInterfaceDecl->protocols()) { 254 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 255 } 256 } else { 257 // Slower path: look in all protocols we referenced. 258 for (auto *P : IFace->all_referenced_protocols()) { 259 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 260 } 261 } 262 } else if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl)) { 263 // We don't check if class extension. Because properties in class extension 264 // are meant to override some of the attributes and checking has already done 265 // when property in class extension is constructed. 266 if (!Cat->IsClassExtension()) 267 for (auto *P : Cat->protocols()) 268 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 269 } else { 270 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(ClassDecl); 271 for (auto *P : Proto->protocols()) 272 CheckPropertyAgainstProtocol(*this, Res, P, KnownProtos); 273 } 274 275 ActOnDocumentableDecl(Res); 276 return Res; 277} 278 279static ObjCPropertyDecl::PropertyAttributeKind 280makePropertyAttributesAsWritten(unsigned Attributes) { 281 unsigned attributesAsWritten = 0; 282 if (Attributes & ObjCDeclSpec::DQ_PR_readonly) 283 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readonly; 284 if (Attributes & ObjCDeclSpec::DQ_PR_readwrite) 285 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_readwrite; 286 if (Attributes & ObjCDeclSpec::DQ_PR_getter) 287 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_getter; 288 if (Attributes & ObjCDeclSpec::DQ_PR_setter) 289 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_setter; 290 if (Attributes & ObjCDeclSpec::DQ_PR_assign) 291 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_assign; 292 if (Attributes & ObjCDeclSpec::DQ_PR_retain) 293 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_retain; 294 if (Attributes & ObjCDeclSpec::DQ_PR_strong) 295 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_strong; 296 if (Attributes & ObjCDeclSpec::DQ_PR_weak) 297 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_weak; 298 if (Attributes & ObjCDeclSpec::DQ_PR_copy) 299 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_copy; 300 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) 301 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_unsafe_unretained; 302 if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic) 303 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_nonatomic; 304 if (Attributes & ObjCDeclSpec::DQ_PR_atomic) 305 attributesAsWritten |= ObjCPropertyDecl::OBJC_PR_atomic; 306 307 return (ObjCPropertyDecl::PropertyAttributeKind)attributesAsWritten; 308} 309 310static bool LocPropertyAttribute( ASTContext &Context, const char *attrName, 311 SourceLocation LParenLoc, SourceLocation &Loc) { 312 if (LParenLoc.isMacroID()) 313 return false; 314 315 SourceManager &SM = Context.getSourceManager(); 316 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(LParenLoc); 317 // Try to load the file buffer. 318 bool invalidTemp = false; 319 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp); 320 if (invalidTemp) 321 return false; 322 const char *tokenBegin = file.data() + locInfo.second; 323 324 // Lex from the start of the given location. 325 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), 326 Context.getLangOpts(), 327 file.begin(), tokenBegin, file.end()); 328 Token Tok; 329 do { 330 lexer.LexFromRawLexer(Tok); 331 if (Tok.is(tok::raw_identifier) && Tok.getRawIdentifier() == attrName) { 332 Loc = Tok.getLocation(); 333 return true; 334 } 335 } while (Tok.isNot(tok::r_paren)); 336 return false; 337 338} 339 340/// Check for a mismatch in the atomicity of the given properties. 341static void checkAtomicPropertyMismatch(Sema &S, 342 ObjCPropertyDecl *OldProperty, 343 ObjCPropertyDecl *NewProperty, 344 bool PropagateAtomicity) { 345 // If the atomicity of both matches, we're done. 346 bool OldIsAtomic = 347 (OldProperty->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 348 == 0; 349 bool NewIsAtomic = 350 (NewProperty->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_nonatomic) 351 == 0; 352 if (OldIsAtomic == NewIsAtomic) return; 353 354 // Determine whether the given property is readonly and implicitly 355 // atomic. 356 auto isImplicitlyReadonlyAtomic = [](ObjCPropertyDecl *Property) -> bool { 357 // Is it readonly? 358 auto Attrs = Property->getPropertyAttributes(); 359 if ((Attrs & ObjCPropertyDecl::OBJC_PR_readonly) == 0) return false; 360 361 // Is it nonatomic? 362 if (Attrs & ObjCPropertyDecl::OBJC_PR_nonatomic) return false; 363 364 // Was 'atomic' specified directly? 365 if (Property->getPropertyAttributesAsWritten() & 366 ObjCPropertyDecl::OBJC_PR_atomic) 367 return false; 368 369 return true; 370 }; 371 372 // If we're allowed to propagate atomicity, and the new property did 373 // not specify atomicity at all, propagate. 374 const unsigned AtomicityMask = 375 (ObjCPropertyDecl::OBJC_PR_atomic | ObjCPropertyDecl::OBJC_PR_nonatomic); 376 if (PropagateAtomicity && 377 ((NewProperty->getPropertyAttributesAsWritten() & AtomicityMask) == 0)) { 378 unsigned Attrs = NewProperty->getPropertyAttributes(); 379 Attrs = Attrs & ~AtomicityMask; 380 if (OldIsAtomic) 381 Attrs |= ObjCPropertyDecl::OBJC_PR_atomic; 382 else 383 Attrs |= ObjCPropertyDecl::OBJC_PR_nonatomic; 384 385 NewProperty->overwritePropertyAttributes(Attrs); 386 return; 387 } 388 389 // One of the properties is atomic; if it's a readonly property, and 390 // 'atomic' wasn't explicitly specified, we're okay. 391 if ((OldIsAtomic && isImplicitlyReadonlyAtomic(OldProperty)) || 392 (NewIsAtomic && isImplicitlyReadonlyAtomic(NewProperty))) 393 return; 394 395 // Diagnose the conflict. 396 const IdentifierInfo *OldContextName; 397 auto *OldDC = OldProperty->getDeclContext(); 398 if (auto Category = dyn_cast<ObjCCategoryDecl>(OldDC)) 399 OldContextName = Category->getClassInterface()->getIdentifier(); 400 else 401 OldContextName = cast<ObjCContainerDecl>(OldDC)->getIdentifier(); 402 403 S.Diag(NewProperty->getLocation(), diag::warn_property_attribute) 404 << NewProperty->getDeclName() << "atomic" 405 << OldContextName; 406 S.Diag(OldProperty->getLocation(), diag::note_property_declare); 407} 408 409ObjCPropertyDecl * 410Sema::HandlePropertyInClassExtension(Scope *S, 411 SourceLocation AtLoc, 412 SourceLocation LParenLoc, 413 FieldDeclarator &FD, 414 Selector GetterSel, Selector SetterSel, 415 const bool isReadWrite, 416 unsigned &Attributes, 417 const unsigned AttributesAsWritten, 418 QualType T, 419 TypeSourceInfo *TSI, 420 tok::ObjCKeywordKind MethodImplKind) { 421 ObjCCategoryDecl *CDecl = cast<ObjCCategoryDecl>(CurContext); 422 // Diagnose if this property is already in continuation class. 423 DeclContext *DC = CurContext; 424 IdentifierInfo *PropertyId = FD.D.getIdentifier(); 425 ObjCInterfaceDecl *CCPrimary = CDecl->getClassInterface(); 426 427 // We need to look in the @interface to see if the @property was 428 // already declared. 429 if (!CCPrimary) { 430 Diag(CDecl->getLocation(), diag::err_continuation_class); 431 return nullptr; 432 } 433 434 // Find the property in the extended class's primary class or 435 // extensions. 436 ObjCPropertyDecl *PIDecl = 437 CCPrimary->FindPropertyVisibleInPrimaryClass(PropertyId); 438 439 // If we found a property in an extension, complain. 440 if (PIDecl && isa<ObjCCategoryDecl>(PIDecl->getDeclContext())) { 441 Diag(AtLoc, diag::err_duplicate_property); 442 Diag(PIDecl->getLocation(), diag::note_property_declare); 443 return nullptr; 444 } 445 446 // Check for consistency with the previous declaration, if there is one. 447 if (PIDecl) { 448 // A readonly property declared in the primary class can be refined 449 // by adding a readwrite property within an extension. 450 // Anything else is an error. 451 if (!(PIDecl->isReadOnly() && isReadWrite)) { 452 // Tailor the diagnostics for the common case where a readwrite 453 // property is declared both in the @interface and the continuation. 454 // This is a common error where the user often intended the original 455 // declaration to be readonly. 456 unsigned diag = 457 (Attributes & ObjCDeclSpec::DQ_PR_readwrite) && 458 (PIDecl->getPropertyAttributesAsWritten() & 459 ObjCPropertyDecl::OBJC_PR_readwrite) 460 ? diag::err_use_continuation_class_redeclaration_readwrite 461 : diag::err_use_continuation_class; 462 Diag(AtLoc, diag) 463 << CCPrimary->getDeclName(); 464 Diag(PIDecl->getLocation(), diag::note_property_declare); 465 return nullptr; 466 } 467 468 // Check for consistency of getters. 469 if (PIDecl->getGetterName() != GetterSel) { 470 // If the getter was written explicitly, complain. 471 if (AttributesAsWritten & ObjCDeclSpec::DQ_PR_getter) { 472 Diag(AtLoc, diag::warn_property_redecl_getter_mismatch) 473 << PIDecl->getGetterName() << GetterSel; 474 Diag(PIDecl->getLocation(), diag::note_property_declare); 475 } 476 477 // Always adopt the getter from the original declaration. 478 GetterSel = PIDecl->getGetterName(); 479 Attributes |= ObjCDeclSpec::DQ_PR_getter; 480 } 481 482 // Check consistency of ownership. 483 unsigned ExistingOwnership 484 = getOwnershipRule(PIDecl->getPropertyAttributes()); 485 unsigned NewOwnership = getOwnershipRule(Attributes); 486 if (ExistingOwnership && NewOwnership != ExistingOwnership) { 487 // If the ownership was written explicitly, complain. 488 if (getOwnershipRule(AttributesAsWritten)) { 489 Diag(AtLoc, diag::warn_property_attr_mismatch); 490 Diag(PIDecl->getLocation(), diag::note_property_declare); 491 } 492 493 // Take the ownership from the original property. 494 Attributes = (Attributes & ~OwnershipMask) | ExistingOwnership; 495 } 496 497 // If the redeclaration is 'weak' but the original property is not, 498 if ((Attributes & ObjCPropertyDecl::OBJC_PR_weak) && 499 !(PIDecl->getPropertyAttributesAsWritten() 500 & ObjCPropertyDecl::OBJC_PR_weak) && 501 PIDecl->getType()->getAs<ObjCObjectPointerType>() && 502 PIDecl->getType().getObjCLifetime() == Qualifiers::OCL_None) { 503 Diag(AtLoc, diag::warn_property_implicitly_mismatched); 504 Diag(PIDecl->getLocation(), diag::note_property_declare); 505 } 506 } 507 508 // Create a new ObjCPropertyDecl with the DeclContext being 509 // the class extension. 510 ObjCPropertyDecl *PDecl = CreatePropertyDecl(S, CDecl, AtLoc, LParenLoc, 511 FD, GetterSel, SetterSel, 512 isReadWrite, 513 Attributes, AttributesAsWritten, 514 T, TSI, MethodImplKind, DC); 515 516 // If there was no declaration of a property with the same name in 517 // the primary class, we're done. 518 if (!PIDecl) { 519 ProcessPropertyDecl(PDecl); 520 return PDecl; 521 } 522 523 if (!Context.hasSameType(PIDecl->getType(), PDecl->getType())) { 524 bool IncompatibleObjC = false; 525 QualType ConvertedType; 526 // Relax the strict type matching for property type in continuation class. 527 // Allow property object type of continuation class to be different as long 528 // as it narrows the object type in its primary class property. Note that 529 // this conversion is safe only because the wider type is for a 'readonly' 530 // property in primary class and 'narrowed' type for a 'readwrite' property 531 // in continuation class. 532 QualType PrimaryClassPropertyT = Context.getCanonicalType(PIDecl->getType()); 533 QualType ClassExtPropertyT = Context.getCanonicalType(PDecl->getType()); 534 if (!isa<ObjCObjectPointerType>(PrimaryClassPropertyT) || 535 !isa<ObjCObjectPointerType>(ClassExtPropertyT) || 536 (!isObjCPointerConversion(ClassExtPropertyT, PrimaryClassPropertyT, 537 ConvertedType, IncompatibleObjC)) 538 || IncompatibleObjC) { 539 Diag(AtLoc, 540 diag::err_type_mismatch_continuation_class) << PDecl->getType(); 541 Diag(PIDecl->getLocation(), diag::note_property_declare); 542 return nullptr; 543 } 544 } 545 546 // Check that atomicity of property in class extension matches the previous 547 // declaration. 548 checkAtomicPropertyMismatch(*this, PIDecl, PDecl, true); 549 550 // Make sure getter/setter are appropriately synthesized. 551 ProcessPropertyDecl(PDecl); 552 return PDecl; 553} 554 555ObjCPropertyDecl *Sema::CreatePropertyDecl(Scope *S, 556 ObjCContainerDecl *CDecl, 557 SourceLocation AtLoc, 558 SourceLocation LParenLoc, 559 FieldDeclarator &FD, 560 Selector GetterSel, 561 Selector SetterSel, 562 const bool isReadWrite, 563 const unsigned Attributes, 564 const unsigned AttributesAsWritten, 565 QualType T, 566 TypeSourceInfo *TInfo, 567 tok::ObjCKeywordKind MethodImplKind, 568 DeclContext *lexicalDC){ 569 IdentifierInfo *PropertyId = FD.D.getIdentifier(); 570 571 // Property defaults to 'assign' if it is readwrite, unless this is ARC 572 // and the type is retainable. 573 bool isAssign; 574 if (Attributes & (ObjCDeclSpec::DQ_PR_assign | 575 ObjCDeclSpec::DQ_PR_unsafe_unretained)) { 576 isAssign = true; 577 } else if (getOwnershipRule(Attributes) || !isReadWrite) { 578 isAssign = false; 579 } else { 580 isAssign = (!getLangOpts().ObjCAutoRefCount || 581 !T->isObjCRetainableType()); 582 } 583 584 // Issue a warning if property is 'assign' as default and its 585 // object, which is gc'able conforms to NSCopying protocol 586 if (getLangOpts().getGC() != LangOptions::NonGC && 587 isAssign && !(Attributes & ObjCDeclSpec::DQ_PR_assign)) { 588 if (const ObjCObjectPointerType *ObjPtrTy = 589 T->getAs<ObjCObjectPointerType>()) { 590 ObjCInterfaceDecl *IDecl = ObjPtrTy->getObjectType()->getInterface(); 591 if (IDecl) 592 if (ObjCProtocolDecl* PNSCopying = 593 LookupProtocol(&Context.Idents.get("NSCopying"), AtLoc)) 594 if (IDecl->ClassImplementsProtocol(PNSCopying, true)) 595 Diag(AtLoc, diag::warn_implements_nscopying) << PropertyId; 596 } 597 } 598 599 if (T->isObjCObjectType()) { 600 SourceLocation StarLoc = TInfo->getTypeLoc().getLocEnd(); 601 StarLoc = getLocForEndOfToken(StarLoc); 602 Diag(FD.D.getIdentifierLoc(), diag::err_statically_allocated_object) 603 << FixItHint::CreateInsertion(StarLoc, "*"); 604 T = Context.getObjCObjectPointerType(T); 605 SourceLocation TLoc = TInfo->getTypeLoc().getLocStart(); 606 TInfo = Context.getTrivialTypeSourceInfo(T, TLoc); 607 } 608 609 DeclContext *DC = cast<DeclContext>(CDecl); 610 ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC, 611 FD.D.getIdentifierLoc(), 612 PropertyId, AtLoc, 613 LParenLoc, T, TInfo); 614 615 if (ObjCPropertyDecl *prevDecl = 616 ObjCPropertyDecl::findPropertyDecl(DC, PropertyId)) { 617 Diag(PDecl->getLocation(), diag::err_duplicate_property); 618 Diag(prevDecl->getLocation(), diag::note_property_declare); 619 PDecl->setInvalidDecl(); 620 } 621 else { 622 DC->addDecl(PDecl); 623 if (lexicalDC) 624 PDecl->setLexicalDeclContext(lexicalDC); 625 } 626 627 if (T->isArrayType() || T->isFunctionType()) { 628 Diag(AtLoc, diag::err_property_type) << T; 629 PDecl->setInvalidDecl(); 630 } 631 632 ProcessDeclAttributes(S, PDecl, FD.D); 633 634 // Regardless of setter/getter attribute, we save the default getter/setter 635 // selector names in anticipation of declaration of setter/getter methods. 636 PDecl->setGetterName(GetterSel); 637 PDecl->setSetterName(SetterSel); 638 PDecl->setPropertyAttributesAsWritten( 639 makePropertyAttributesAsWritten(AttributesAsWritten)); 640 641 if (Attributes & ObjCDeclSpec::DQ_PR_readonly) 642 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly); 643 644 if (Attributes & ObjCDeclSpec::DQ_PR_getter) 645 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter); 646 647 if (Attributes & ObjCDeclSpec::DQ_PR_setter) 648 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter); 649 650 if (isReadWrite) 651 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite); 652 653 if (Attributes & ObjCDeclSpec::DQ_PR_retain) 654 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain); 655 656 if (Attributes & ObjCDeclSpec::DQ_PR_strong) 657 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 658 659 if (Attributes & ObjCDeclSpec::DQ_PR_weak) 660 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak); 661 662 if (Attributes & ObjCDeclSpec::DQ_PR_copy) 663 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy); 664 665 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) 666 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained); 667 668 if (isAssign) 669 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign); 670 671 // In the semantic attributes, one of nonatomic or atomic is always set. 672 if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic) 673 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic); 674 else 675 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_atomic); 676 677 // 'unsafe_unretained' is alias for 'assign'. 678 if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) 679 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign); 680 if (isAssign) 681 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_unsafe_unretained); 682 683 if (MethodImplKind == tok::objc_required) 684 PDecl->setPropertyImplementation(ObjCPropertyDecl::Required); 685 else if (MethodImplKind == tok::objc_optional) 686 PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional); 687 688 if (Attributes & ObjCDeclSpec::DQ_PR_nullability) 689 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nullability); 690 691 if (Attributes & ObjCDeclSpec::DQ_PR_null_resettable) 692 PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_null_resettable); 693 694 return PDecl; 695} 696 697static void checkARCPropertyImpl(Sema &S, SourceLocation propertyImplLoc, 698 ObjCPropertyDecl *property, 699 ObjCIvarDecl *ivar) { 700 if (property->isInvalidDecl() || ivar->isInvalidDecl()) return; 701 702 QualType ivarType = ivar->getType(); 703 Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime(); 704 705 // The lifetime implied by the property's attributes. 706 Qualifiers::ObjCLifetime propertyLifetime = 707 getImpliedARCOwnership(property->getPropertyAttributes(), 708 property->getType()); 709 710 // We're fine if they match. 711 if (propertyLifetime == ivarLifetime) return; 712 713 // None isn't a valid lifetime for an object ivar in ARC, and 714 // __autoreleasing is never valid; don't diagnose twice. 715 if ((ivarLifetime == Qualifiers::OCL_None && 716 S.getLangOpts().ObjCAutoRefCount) || 717 ivarLifetime == Qualifiers::OCL_Autoreleasing) 718 return; 719 720 // If the ivar is private, and it's implicitly __unsafe_unretained 721 // becaues of its type, then pretend it was actually implicitly 722 // __strong. This is only sound because we're processing the 723 // property implementation before parsing any method bodies. 724 if (ivarLifetime == Qualifiers::OCL_ExplicitNone && 725 propertyLifetime == Qualifiers::OCL_Strong && 726 ivar->getAccessControl() == ObjCIvarDecl::Private) { 727 SplitQualType split = ivarType.split(); 728 if (split.Quals.hasObjCLifetime()) { 729 assert(ivarType->isObjCARCImplicitlyUnretainedType()); 730 split.Quals.setObjCLifetime(Qualifiers::OCL_Strong); 731 ivarType = S.Context.getQualifiedType(split); 732 ivar->setType(ivarType); 733 return; 734 } 735 } 736 737 switch (propertyLifetime) { 738 case Qualifiers::OCL_Strong: 739 S.Diag(ivar->getLocation(), diag::err_arc_strong_property_ownership) 740 << property->getDeclName() 741 << ivar->getDeclName() 742 << ivarLifetime; 743 break; 744 745 case Qualifiers::OCL_Weak: 746 S.Diag(ivar->getLocation(), diag::error_weak_property) 747 << property->getDeclName() 748 << ivar->getDeclName(); 749 break; 750 751 case Qualifiers::OCL_ExplicitNone: 752 S.Diag(ivar->getLocation(), diag::err_arc_assign_property_ownership) 753 << property->getDeclName() 754 << ivar->getDeclName() 755 << ((property->getPropertyAttributesAsWritten() 756 & ObjCPropertyDecl::OBJC_PR_assign) != 0); 757 break; 758 759 case Qualifiers::OCL_Autoreleasing: 760 llvm_unreachable("properties cannot be autoreleasing"); 761 762 case Qualifiers::OCL_None: 763 // Any other property should be ignored. 764 return; 765 } 766 767 S.Diag(property->getLocation(), diag::note_property_declare); 768 if (propertyImplLoc.isValid()) 769 S.Diag(propertyImplLoc, diag::note_property_synthesize); 770} 771 772/// setImpliedPropertyAttributeForReadOnlyProperty - 773/// This routine evaludates life-time attributes for a 'readonly' 774/// property with no known lifetime of its own, using backing 775/// 'ivar's attribute, if any. If no backing 'ivar', property's 776/// life-time is assumed 'strong'. 777static void setImpliedPropertyAttributeForReadOnlyProperty( 778 ObjCPropertyDecl *property, ObjCIvarDecl *ivar) { 779 Qualifiers::ObjCLifetime propertyLifetime = 780 getImpliedARCOwnership(property->getPropertyAttributes(), 781 property->getType()); 782 if (propertyLifetime != Qualifiers::OCL_None) 783 return; 784 785 if (!ivar) { 786 // if no backing ivar, make property 'strong'. 787 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 788 return; 789 } 790 // property assumes owenership of backing ivar. 791 QualType ivarType = ivar->getType(); 792 Qualifiers::ObjCLifetime ivarLifetime = ivarType.getObjCLifetime(); 793 if (ivarLifetime == Qualifiers::OCL_Strong) 794 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 795 else if (ivarLifetime == Qualifiers::OCL_Weak) 796 property->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_weak); 797 return; 798} 799 800/// DiagnosePropertyMismatchDeclInProtocols - diagnose properties declared 801/// in inherited protocols with mismatched types. Since any of them can 802/// be candidate for synthesis. 803static void 804DiagnosePropertyMismatchDeclInProtocols(Sema &S, SourceLocation AtLoc, 805 ObjCInterfaceDecl *ClassDecl, 806 ObjCPropertyDecl *Property) { 807 ObjCInterfaceDecl::ProtocolPropertyMap PropMap; 808 for (const auto *PI : ClassDecl->all_referenced_protocols()) { 809 if (const ObjCProtocolDecl *PDecl = PI->getDefinition()) 810 PDecl->collectInheritedProtocolProperties(Property, PropMap); 811 } 812 if (ObjCInterfaceDecl *SDecl = ClassDecl->getSuperClass()) 813 while (SDecl) { 814 for (const auto *PI : SDecl->all_referenced_protocols()) { 815 if (const ObjCProtocolDecl *PDecl = PI->getDefinition()) 816 PDecl->collectInheritedProtocolProperties(Property, PropMap); 817 } 818 SDecl = SDecl->getSuperClass(); 819 } 820 821 if (PropMap.empty()) 822 return; 823 824 QualType RHSType = S.Context.getCanonicalType(Property->getType()); 825 bool FirsTime = true; 826 for (ObjCInterfaceDecl::ProtocolPropertyMap::iterator 827 I = PropMap.begin(), E = PropMap.end(); I != E; I++) { 828 ObjCPropertyDecl *Prop = I->second; 829 QualType LHSType = S.Context.getCanonicalType(Prop->getType()); 830 if (!S.Context.propertyTypesAreCompatible(LHSType, RHSType)) { 831 bool IncompatibleObjC = false; 832 QualType ConvertedType; 833 if (!S.isObjCPointerConversion(RHSType, LHSType, ConvertedType, IncompatibleObjC) 834 || IncompatibleObjC) { 835 if (FirsTime) { 836 S.Diag(Property->getLocation(), diag::warn_protocol_property_mismatch) 837 << Property->getType(); 838 FirsTime = false; 839 } 840 S.Diag(Prop->getLocation(), diag::note_protocol_property_declare) 841 << Prop->getType(); 842 } 843 } 844 } 845 if (!FirsTime && AtLoc.isValid()) 846 S.Diag(AtLoc, diag::note_property_synthesize); 847} 848 849/// Determine whether any storage attributes were written on the property. 850static bool hasWrittenStorageAttribute(ObjCPropertyDecl *Prop) { 851 if (Prop->getPropertyAttributesAsWritten() & OwnershipMask) return true; 852 853 // If this is a readwrite property in a class extension that refines 854 // a readonly property in the original class definition, check it as 855 // well. 856 857 // If it's a readonly property, we're not interested. 858 if (Prop->isReadOnly()) return false; 859 860 // Is it declared in an extension? 861 auto Category = dyn_cast<ObjCCategoryDecl>(Prop->getDeclContext()); 862 if (!Category || !Category->IsClassExtension()) return false; 863 864 // Find the corresponding property in the primary class definition. 865 auto OrigClass = Category->getClassInterface(); 866 for (auto Found : OrigClass->lookup(Prop->getDeclName())) { 867 if (ObjCPropertyDecl *OrigProp = dyn_cast<ObjCPropertyDecl>(Found)) 868 return OrigProp->getPropertyAttributesAsWritten() & OwnershipMask; 869 } 870 871 // Look through all of the protocols. 872 for (const auto *Proto : OrigClass->all_referenced_protocols()) { 873 if (ObjCPropertyDecl *OrigProp = 874 Proto->FindPropertyDeclaration(Prop->getIdentifier())) 875 return OrigProp->getPropertyAttributesAsWritten() & OwnershipMask; 876 } 877 878 return false; 879} 880 881/// ActOnPropertyImplDecl - This routine performs semantic checks and 882/// builds the AST node for a property implementation declaration; declared 883/// as \@synthesize or \@dynamic. 884/// 885Decl *Sema::ActOnPropertyImplDecl(Scope *S, 886 SourceLocation AtLoc, 887 SourceLocation PropertyLoc, 888 bool Synthesize, 889 IdentifierInfo *PropertyId, 890 IdentifierInfo *PropertyIvar, 891 SourceLocation PropertyIvarLoc) { 892 ObjCContainerDecl *ClassImpDecl = 893 dyn_cast<ObjCContainerDecl>(CurContext); 894 // Make sure we have a context for the property implementation declaration. 895 if (!ClassImpDecl) { 896 Diag(AtLoc, diag::error_missing_property_context); 897 return nullptr; 898 } 899 if (PropertyIvarLoc.isInvalid()) 900 PropertyIvarLoc = PropertyLoc; 901 SourceLocation PropertyDiagLoc = PropertyLoc; 902 if (PropertyDiagLoc.isInvalid()) 903 PropertyDiagLoc = ClassImpDecl->getLocStart(); 904 ObjCPropertyDecl *property = nullptr; 905 ObjCInterfaceDecl *IDecl = nullptr; 906 // Find the class or category class where this property must have 907 // a declaration. 908 ObjCImplementationDecl *IC = nullptr; 909 ObjCCategoryImplDecl *CatImplClass = nullptr; 910 if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) { 911 IDecl = IC->getClassInterface(); 912 // We always synthesize an interface for an implementation 913 // without an interface decl. So, IDecl is always non-zero. 914 assert(IDecl && 915 "ActOnPropertyImplDecl - @implementation without @interface"); 916 917 // Look for this property declaration in the @implementation's @interface 918 property = IDecl->FindPropertyDeclaration(PropertyId); 919 if (!property) { 920 Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName(); 921 return nullptr; 922 } 923 unsigned PIkind = property->getPropertyAttributesAsWritten(); 924 if ((PIkind & (ObjCPropertyDecl::OBJC_PR_atomic | 925 ObjCPropertyDecl::OBJC_PR_nonatomic) ) == 0) { 926 if (AtLoc.isValid()) 927 Diag(AtLoc, diag::warn_implicit_atomic_property); 928 else 929 Diag(IC->getLocation(), diag::warn_auto_implicit_atomic_property); 930 Diag(property->getLocation(), diag::note_property_declare); 931 } 932 933 if (const ObjCCategoryDecl *CD = 934 dyn_cast<ObjCCategoryDecl>(property->getDeclContext())) { 935 if (!CD->IsClassExtension()) { 936 Diag(PropertyLoc, diag::error_category_property) << CD->getDeclName(); 937 Diag(property->getLocation(), diag::note_property_declare); 938 return nullptr; 939 } 940 } 941 if (Synthesize&& 942 (PIkind & ObjCPropertyDecl::OBJC_PR_readonly) && 943 property->hasAttr<IBOutletAttr>() && 944 !AtLoc.isValid()) { 945 bool ReadWriteProperty = false; 946 // Search into the class extensions and see if 'readonly property is 947 // redeclared 'readwrite', then no warning is to be issued. 948 for (auto *Ext : IDecl->known_extensions()) { 949 DeclContext::lookup_result R = Ext->lookup(property->getDeclName()); 950 if (!R.empty()) 951 if (ObjCPropertyDecl *ExtProp = dyn_cast<ObjCPropertyDecl>(R[0])) { 952 PIkind = ExtProp->getPropertyAttributesAsWritten(); 953 if (PIkind & ObjCPropertyDecl::OBJC_PR_readwrite) { 954 ReadWriteProperty = true; 955 break; 956 } 957 } 958 } 959 960 if (!ReadWriteProperty) { 961 Diag(property->getLocation(), diag::warn_auto_readonly_iboutlet_property) 962 << property; 963 SourceLocation readonlyLoc; 964 if (LocPropertyAttribute(Context, "readonly", 965 property->getLParenLoc(), readonlyLoc)) { 966 SourceLocation endLoc = 967 readonlyLoc.getLocWithOffset(strlen("readonly")-1); 968 SourceRange ReadonlySourceRange(readonlyLoc, endLoc); 969 Diag(property->getLocation(), 970 diag::note_auto_readonly_iboutlet_fixup_suggest) << 971 FixItHint::CreateReplacement(ReadonlySourceRange, "readwrite"); 972 } 973 } 974 } 975 if (Synthesize && isa<ObjCProtocolDecl>(property->getDeclContext())) 976 DiagnosePropertyMismatchDeclInProtocols(*this, AtLoc, IDecl, property); 977 978 } else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) { 979 if (Synthesize) { 980 Diag(AtLoc, diag::error_synthesize_category_decl); 981 return nullptr; 982 } 983 IDecl = CatImplClass->getClassInterface(); 984 if (!IDecl) { 985 Diag(AtLoc, diag::error_missing_property_interface); 986 return nullptr; 987 } 988 ObjCCategoryDecl *Category = 989 IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier()); 990 991 // If category for this implementation not found, it is an error which 992 // has already been reported eralier. 993 if (!Category) 994 return nullptr; 995 // Look for this property declaration in @implementation's category 996 property = Category->FindPropertyDeclaration(PropertyId); 997 if (!property) { 998 Diag(PropertyLoc, diag::error_bad_category_property_decl) 999 << Category->getDeclName(); 1000 return nullptr; 1001 } 1002 } else { 1003 Diag(AtLoc, diag::error_bad_property_context); 1004 return nullptr; 1005 } 1006 ObjCIvarDecl *Ivar = nullptr; 1007 bool CompleteTypeErr = false; 1008 bool compat = true; 1009 // Check that we have a valid, previously declared ivar for @synthesize 1010 if (Synthesize) { 1011 // @synthesize 1012 if (!PropertyIvar) 1013 PropertyIvar = PropertyId; 1014 // Check that this is a previously declared 'ivar' in 'IDecl' interface 1015 ObjCInterfaceDecl *ClassDeclared; 1016 Ivar = IDecl->lookupInstanceVariable(PropertyIvar, ClassDeclared); 1017 QualType PropType = property->getType(); 1018 QualType PropertyIvarType = PropType.getNonReferenceType(); 1019 1020 if (RequireCompleteType(PropertyDiagLoc, PropertyIvarType, 1021 diag::err_incomplete_synthesized_property, 1022 property->getDeclName())) { 1023 Diag(property->getLocation(), diag::note_property_declare); 1024 CompleteTypeErr = true; 1025 } 1026 1027 if (getLangOpts().ObjCAutoRefCount && 1028 (property->getPropertyAttributesAsWritten() & 1029 ObjCPropertyDecl::OBJC_PR_readonly) && 1030 PropertyIvarType->isObjCRetainableType()) { 1031 setImpliedPropertyAttributeForReadOnlyProperty(property, Ivar); 1032 } 1033 1034 ObjCPropertyDecl::PropertyAttributeKind kind 1035 = property->getPropertyAttributes(); 1036 1037 bool isARCWeak = false; 1038 if (kind & ObjCPropertyDecl::OBJC_PR_weak) { 1039 // Add GC __weak to the ivar type if the property is weak. 1040 if (getLangOpts().getGC() != LangOptions::NonGC) { 1041 assert(!getLangOpts().ObjCAutoRefCount); 1042 if (PropertyIvarType.isObjCGCStrong()) { 1043 Diag(PropertyDiagLoc, diag::err_gc_weak_property_strong_type); 1044 Diag(property->getLocation(), diag::note_property_declare); 1045 } else { 1046 PropertyIvarType = 1047 Context.getObjCGCQualType(PropertyIvarType, Qualifiers::Weak); 1048 } 1049 1050 // Otherwise, check whether ARC __weak is enabled and works with 1051 // the property type. 1052 } else { 1053 if (!getLangOpts().ObjCWeak) { 1054 // Only complain here when synthesizing an ivar. 1055 if (!Ivar) { 1056 Diag(PropertyDiagLoc, 1057 getLangOpts().ObjCWeakRuntime 1058 ? diag::err_synthesizing_arc_weak_property_disabled 1059 : diag::err_synthesizing_arc_weak_property_no_runtime); 1060 Diag(property->getLocation(), diag::note_property_declare); 1061 } 1062 CompleteTypeErr = true; // suppress later diagnostics about the ivar 1063 } else { 1064 isARCWeak = true; 1065 if (const ObjCObjectPointerType *ObjT = 1066 PropertyIvarType->getAs<ObjCObjectPointerType>()) { 1067 const ObjCInterfaceDecl *ObjI = ObjT->getInterfaceDecl(); 1068 if (ObjI && ObjI->isArcWeakrefUnavailable()) { 1069 Diag(property->getLocation(), 1070 diag::err_arc_weak_unavailable_property) 1071 << PropertyIvarType; 1072 Diag(ClassImpDecl->getLocation(), diag::note_implemented_by_class) 1073 << ClassImpDecl->getName(); 1074 } 1075 } 1076 } 1077 } 1078 } 1079 1080 if (AtLoc.isInvalid()) { 1081 // Check when default synthesizing a property that there is 1082 // an ivar matching property name and issue warning; since this 1083 // is the most common case of not using an ivar used for backing 1084 // property in non-default synthesis case. 1085 ObjCInterfaceDecl *ClassDeclared=nullptr; 1086 ObjCIvarDecl *originalIvar = 1087 IDecl->lookupInstanceVariable(property->getIdentifier(), 1088 ClassDeclared); 1089 if (originalIvar) { 1090 Diag(PropertyDiagLoc, 1091 diag::warn_autosynthesis_property_ivar_match) 1092 << PropertyId << (Ivar == nullptr) << PropertyIvar 1093 << originalIvar->getIdentifier(); 1094 Diag(property->getLocation(), diag::note_property_declare); 1095 Diag(originalIvar->getLocation(), diag::note_ivar_decl); 1096 } 1097 } 1098 1099 if (!Ivar) { 1100 // In ARC, give the ivar a lifetime qualifier based on the 1101 // property attributes. 1102 if ((getLangOpts().ObjCAutoRefCount || isARCWeak) && 1103 !PropertyIvarType.getObjCLifetime() && 1104 PropertyIvarType->isObjCRetainableType()) { 1105 1106 // It's an error if we have to do this and the user didn't 1107 // explicitly write an ownership attribute on the property. 1108 if (!hasWrittenStorageAttribute(property) && 1109 !(kind & ObjCPropertyDecl::OBJC_PR_strong)) { 1110 Diag(PropertyDiagLoc, 1111 diag::err_arc_objc_property_default_assign_on_object); 1112 Diag(property->getLocation(), diag::note_property_declare); 1113 } else { 1114 Qualifiers::ObjCLifetime lifetime = 1115 getImpliedARCOwnership(kind, PropertyIvarType); 1116 assert(lifetime && "no lifetime for property?"); 1117 1118 Qualifiers qs; 1119 qs.addObjCLifetime(lifetime); 1120 PropertyIvarType = Context.getQualifiedType(PropertyIvarType, qs); 1121 } 1122 } 1123 1124 Ivar = ObjCIvarDecl::Create(Context, ClassImpDecl, 1125 PropertyIvarLoc,PropertyIvarLoc, PropertyIvar, 1126 PropertyIvarType, /*Dinfo=*/nullptr, 1127 ObjCIvarDecl::Private, 1128 (Expr *)nullptr, true); 1129 if (RequireNonAbstractType(PropertyIvarLoc, 1130 PropertyIvarType, 1131 diag::err_abstract_type_in_decl, 1132 AbstractSynthesizedIvarType)) { 1133 Diag(property->getLocation(), diag::note_property_declare); 1134 Ivar->setInvalidDecl(); 1135 } else if (CompleteTypeErr) 1136 Ivar->setInvalidDecl(); 1137 ClassImpDecl->addDecl(Ivar); 1138 IDecl->makeDeclVisibleInContext(Ivar); 1139 1140 if (getLangOpts().ObjCRuntime.isFragile()) 1141 Diag(PropertyDiagLoc, diag::error_missing_property_ivar_decl) 1142 << PropertyId; 1143 // Note! I deliberately want it to fall thru so, we have a 1144 // a property implementation and to avoid future warnings. 1145 } else if (getLangOpts().ObjCRuntime.isNonFragile() && 1146 !declaresSameEntity(ClassDeclared, IDecl)) { 1147 Diag(PropertyDiagLoc, diag::error_ivar_in_superclass_use) 1148 << property->getDeclName() << Ivar->getDeclName() 1149 << ClassDeclared->getDeclName(); 1150 Diag(Ivar->getLocation(), diag::note_previous_access_declaration) 1151 << Ivar << Ivar->getName(); 1152 // Note! I deliberately want it to fall thru so more errors are caught. 1153 } 1154 property->setPropertyIvarDecl(Ivar); 1155 1156 QualType IvarType = Context.getCanonicalType(Ivar->getType()); 1157 1158 // Check that type of property and its ivar are type compatible. 1159 if (!Context.hasSameType(PropertyIvarType, IvarType)) { 1160 if (isa<ObjCObjectPointerType>(PropertyIvarType) 1161 && isa<ObjCObjectPointerType>(IvarType)) 1162 compat = 1163 Context.canAssignObjCInterfaces( 1164 PropertyIvarType->getAs<ObjCObjectPointerType>(), 1165 IvarType->getAs<ObjCObjectPointerType>()); 1166 else { 1167 compat = (CheckAssignmentConstraints(PropertyIvarLoc, PropertyIvarType, 1168 IvarType) 1169 == Compatible); 1170 } 1171 if (!compat) { 1172 Diag(PropertyDiagLoc, diag::error_property_ivar_type) 1173 << property->getDeclName() << PropType 1174 << Ivar->getDeclName() << IvarType; 1175 Diag(Ivar->getLocation(), diag::note_ivar_decl); 1176 // Note! I deliberately want it to fall thru so, we have a 1177 // a property implementation and to avoid future warnings. 1178 } 1179 else { 1180 // FIXME! Rules for properties are somewhat different that those 1181 // for assignments. Use a new routine to consolidate all cases; 1182 // specifically for property redeclarations as well as for ivars. 1183 QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType(); 1184 QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType(); 1185 if (lhsType != rhsType && 1186 lhsType->isArithmeticType()) { 1187 Diag(PropertyDiagLoc, diag::error_property_ivar_type) 1188 << property->getDeclName() << PropType 1189 << Ivar->getDeclName() << IvarType; 1190 Diag(Ivar->getLocation(), diag::note_ivar_decl); 1191 // Fall thru - see previous comment 1192 } 1193 } 1194 // __weak is explicit. So it works on Canonical type. 1195 if ((PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() && 1196 getLangOpts().getGC() != LangOptions::NonGC)) { 1197 Diag(PropertyDiagLoc, diag::error_weak_property) 1198 << property->getDeclName() << Ivar->getDeclName(); 1199 Diag(Ivar->getLocation(), diag::note_ivar_decl); 1200 // Fall thru - see previous comment 1201 } 1202 // Fall thru - see previous comment 1203 if ((property->getType()->isObjCObjectPointerType() || 1204 PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() && 1205 getLangOpts().getGC() != LangOptions::NonGC) { 1206 Diag(PropertyDiagLoc, diag::error_strong_property) 1207 << property->getDeclName() << Ivar->getDeclName(); 1208 // Fall thru - see previous comment 1209 } 1210 } 1211 if (getLangOpts().ObjCAutoRefCount || isARCWeak || 1212 Ivar->getType().getObjCLifetime()) 1213 checkARCPropertyImpl(*this, PropertyLoc, property, Ivar); 1214 } else if (PropertyIvar) 1215 // @dynamic 1216 Diag(PropertyDiagLoc, diag::error_dynamic_property_ivar_decl); 1217 1218 assert (property && "ActOnPropertyImplDecl - property declaration missing"); 1219 ObjCPropertyImplDecl *PIDecl = 1220 ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc, 1221 property, 1222 (Synthesize ? 1223 ObjCPropertyImplDecl::Synthesize 1224 : ObjCPropertyImplDecl::Dynamic), 1225 Ivar, PropertyIvarLoc); 1226 1227 if (CompleteTypeErr || !compat) 1228 PIDecl->setInvalidDecl(); 1229 1230 if (ObjCMethodDecl *getterMethod = property->getGetterMethodDecl()) { 1231 getterMethod->createImplicitParams(Context, IDecl); 1232 if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr && 1233 Ivar->getType()->isRecordType()) { 1234 // For Objective-C++, need to synthesize the AST for the IVAR object to be 1235 // returned by the getter as it must conform to C++'s copy-return rules. 1236 // FIXME. Eventually we want to do this for Objective-C as well. 1237 SynthesizedFunctionScope Scope(*this, getterMethod); 1238 ImplicitParamDecl *SelfDecl = getterMethod->getSelfDecl(); 1239 DeclRefExpr *SelfExpr = 1240 new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(), 1241 VK_LValue, PropertyDiagLoc); 1242 MarkDeclRefReferenced(SelfExpr); 1243 Expr *LoadSelfExpr = 1244 ImplicitCastExpr::Create(Context, SelfDecl->getType(), 1245 CK_LValueToRValue, SelfExpr, nullptr, 1246 VK_RValue); 1247 Expr *IvarRefExpr = 1248 new (Context) ObjCIvarRefExpr(Ivar, 1249 Ivar->getUsageType(SelfDecl->getType()), 1250 PropertyDiagLoc, 1251 Ivar->getLocation(), 1252 LoadSelfExpr, true, true); 1253 ExprResult Res = PerformCopyInitialization( 1254 InitializedEntity::InitializeResult(PropertyDiagLoc, 1255 getterMethod->getReturnType(), 1256 /*NRVO=*/false), 1257 PropertyDiagLoc, IvarRefExpr); 1258 if (!Res.isInvalid()) { 1259 Expr *ResExpr = Res.getAs<Expr>(); 1260 if (ResExpr) 1261 ResExpr = MaybeCreateExprWithCleanups(ResExpr); 1262 PIDecl->setGetterCXXConstructor(ResExpr); 1263 } 1264 } 1265 if (property->hasAttr<NSReturnsNotRetainedAttr>() && 1266 !getterMethod->hasAttr<NSReturnsNotRetainedAttr>()) { 1267 Diag(getterMethod->getLocation(), 1268 diag::warn_property_getter_owning_mismatch); 1269 Diag(property->getLocation(), diag::note_property_declare); 1270 } 1271 if (getLangOpts().ObjCAutoRefCount && Synthesize) 1272 switch (getterMethod->getMethodFamily()) { 1273 case OMF_retain: 1274 case OMF_retainCount: 1275 case OMF_release: 1276 case OMF_autorelease: 1277 Diag(getterMethod->getLocation(), diag::err_arc_illegal_method_def) 1278 << 1 << getterMethod->getSelector(); 1279 break; 1280 default: 1281 break; 1282 } 1283 } 1284 if (ObjCMethodDecl *setterMethod = property->getSetterMethodDecl()) { 1285 setterMethod->createImplicitParams(Context, IDecl); 1286 if (getLangOpts().CPlusPlus && Synthesize && !CompleteTypeErr && 1287 Ivar->getType()->isRecordType()) { 1288 // FIXME. Eventually we want to do this for Objective-C as well. 1289 SynthesizedFunctionScope Scope(*this, setterMethod); 1290 ImplicitParamDecl *SelfDecl = setterMethod->getSelfDecl(); 1291 DeclRefExpr *SelfExpr = 1292 new (Context) DeclRefExpr(SelfDecl, false, SelfDecl->getType(), 1293 VK_LValue, PropertyDiagLoc); 1294 MarkDeclRefReferenced(SelfExpr); 1295 Expr *LoadSelfExpr = 1296 ImplicitCastExpr::Create(Context, SelfDecl->getType(), 1297 CK_LValueToRValue, SelfExpr, nullptr, 1298 VK_RValue); 1299 Expr *lhs = 1300 new (Context) ObjCIvarRefExpr(Ivar, 1301 Ivar->getUsageType(SelfDecl->getType()), 1302 PropertyDiagLoc, 1303 Ivar->getLocation(), 1304 LoadSelfExpr, true, true); 1305 ObjCMethodDecl::param_iterator P = setterMethod->param_begin(); 1306 ParmVarDecl *Param = (*P); 1307 QualType T = Param->getType().getNonReferenceType(); 1308 DeclRefExpr *rhs = new (Context) DeclRefExpr(Param, false, T, 1309 VK_LValue, PropertyDiagLoc); 1310 MarkDeclRefReferenced(rhs); 1311 ExprResult Res = BuildBinOp(S, PropertyDiagLoc, 1312 BO_Assign, lhs, rhs); 1313 if (property->getPropertyAttributes() & 1314 ObjCPropertyDecl::OBJC_PR_atomic) { 1315 Expr *callExpr = Res.getAs<Expr>(); 1316 if (const CXXOperatorCallExpr *CXXCE = 1317 dyn_cast_or_null<CXXOperatorCallExpr>(callExpr)) 1318 if (const FunctionDecl *FuncDecl = CXXCE->getDirectCallee()) 1319 if (!FuncDecl->isTrivial()) 1320 if (property->getType()->isReferenceType()) { 1321 Diag(PropertyDiagLoc, 1322 diag::err_atomic_property_nontrivial_assign_op) 1323 << property->getType(); 1324 Diag(FuncDecl->getLocStart(), 1325 diag::note_callee_decl) << FuncDecl; 1326 } 1327 } 1328 PIDecl->setSetterCXXAssignment(Res.getAs<Expr>()); 1329 } 1330 } 1331 1332 if (IC) { 1333 if (Synthesize) 1334 if (ObjCPropertyImplDecl *PPIDecl = 1335 IC->FindPropertyImplIvarDecl(PropertyIvar)) { 1336 Diag(PropertyLoc, diag::error_duplicate_ivar_use) 1337 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier() 1338 << PropertyIvar; 1339 Diag(PPIDecl->getLocation(), diag::note_previous_use); 1340 } 1341 1342 if (ObjCPropertyImplDecl *PPIDecl 1343 = IC->FindPropertyImplDecl(PropertyId)) { 1344 Diag(PropertyLoc, diag::error_property_implemented) << PropertyId; 1345 Diag(PPIDecl->getLocation(), diag::note_previous_declaration); 1346 return nullptr; 1347 } 1348 IC->addPropertyImplementation(PIDecl); 1349 if (getLangOpts().ObjCDefaultSynthProperties && 1350 getLangOpts().ObjCRuntime.isNonFragile() && 1351 !IDecl->isObjCRequiresPropertyDefs()) { 1352 // Diagnose if an ivar was lazily synthesdized due to a previous 1353 // use and if 1) property is @dynamic or 2) property is synthesized 1354 // but it requires an ivar of different name. 1355 ObjCInterfaceDecl *ClassDeclared=nullptr; 1356 ObjCIvarDecl *Ivar = nullptr; 1357 if (!Synthesize) 1358 Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared); 1359 else { 1360 if (PropertyIvar && PropertyIvar != PropertyId) 1361 Ivar = IDecl->lookupInstanceVariable(PropertyId, ClassDeclared); 1362 } 1363 // Issue diagnostics only if Ivar belongs to current class. 1364 if (Ivar && Ivar->getSynthesize() && 1365 declaresSameEntity(IC->getClassInterface(), ClassDeclared)) { 1366 Diag(Ivar->getLocation(), diag::err_undeclared_var_use) 1367 << PropertyId; 1368 Ivar->setInvalidDecl(); 1369 } 1370 } 1371 } else { 1372 if (Synthesize) 1373 if (ObjCPropertyImplDecl *PPIDecl = 1374 CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) { 1375 Diag(PropertyDiagLoc, diag::error_duplicate_ivar_use) 1376 << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier() 1377 << PropertyIvar; 1378 Diag(PPIDecl->getLocation(), diag::note_previous_use); 1379 } 1380 1381 if (ObjCPropertyImplDecl *PPIDecl = 1382 CatImplClass->FindPropertyImplDecl(PropertyId)) { 1383 Diag(PropertyDiagLoc, diag::error_property_implemented) << PropertyId; 1384 Diag(PPIDecl->getLocation(), diag::note_previous_declaration); 1385 return nullptr; 1386 } 1387 CatImplClass->addPropertyImplementation(PIDecl); 1388 } 1389 1390 return PIDecl; 1391} 1392 1393//===----------------------------------------------------------------------===// 1394// Helper methods. 1395//===----------------------------------------------------------------------===// 1396 1397/// DiagnosePropertyMismatch - Compares two properties for their 1398/// attributes and types and warns on a variety of inconsistencies. 1399/// 1400void 1401Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property, 1402 ObjCPropertyDecl *SuperProperty, 1403 const IdentifierInfo *inheritedName, 1404 bool OverridingProtocolProperty) { 1405 ObjCPropertyDecl::PropertyAttributeKind CAttr = 1406 Property->getPropertyAttributes(); 1407 ObjCPropertyDecl::PropertyAttributeKind SAttr = 1408 SuperProperty->getPropertyAttributes(); 1409 1410 // We allow readonly properties without an explicit ownership 1411 // (assign/unsafe_unretained/weak/retain/strong/copy) in super class 1412 // to be overridden by a property with any explicit ownership in the subclass. 1413 if (!OverridingProtocolProperty && 1414 !getOwnershipRule(SAttr) && getOwnershipRule(CAttr)) 1415 ; 1416 else { 1417 if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly) 1418 && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite)) 1419 Diag(Property->getLocation(), diag::warn_readonly_property) 1420 << Property->getDeclName() << inheritedName; 1421 if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy) 1422 != (SAttr & ObjCPropertyDecl::OBJC_PR_copy)) 1423 Diag(Property->getLocation(), diag::warn_property_attribute) 1424 << Property->getDeclName() << "copy" << inheritedName; 1425 else if (!(SAttr & ObjCPropertyDecl::OBJC_PR_readonly)){ 1426 unsigned CAttrRetain = 1427 (CAttr & 1428 (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong)); 1429 unsigned SAttrRetain = 1430 (SAttr & 1431 (ObjCPropertyDecl::OBJC_PR_retain | ObjCPropertyDecl::OBJC_PR_strong)); 1432 bool CStrong = (CAttrRetain != 0); 1433 bool SStrong = (SAttrRetain != 0); 1434 if (CStrong != SStrong) 1435 Diag(Property->getLocation(), diag::warn_property_attribute) 1436 << Property->getDeclName() << "retain (or strong)" << inheritedName; 1437 } 1438 } 1439 1440 // Check for nonatomic; note that nonatomic is effectively 1441 // meaningless for readonly properties, so don't diagnose if the 1442 // atomic property is 'readonly'. 1443 checkAtomicPropertyMismatch(*this, SuperProperty, Property, false); 1444 if (Property->getSetterName() != SuperProperty->getSetterName()) { 1445 Diag(Property->getLocation(), diag::warn_property_attribute) 1446 << Property->getDeclName() << "setter" << inheritedName; 1447 Diag(SuperProperty->getLocation(), diag::note_property_declare); 1448 } 1449 if (Property->getGetterName() != SuperProperty->getGetterName()) { 1450 Diag(Property->getLocation(), diag::warn_property_attribute) 1451 << Property->getDeclName() << "getter" << inheritedName; 1452 Diag(SuperProperty->getLocation(), diag::note_property_declare); 1453 } 1454 1455 QualType LHSType = 1456 Context.getCanonicalType(SuperProperty->getType()); 1457 QualType RHSType = 1458 Context.getCanonicalType(Property->getType()); 1459 1460 if (!Context.propertyTypesAreCompatible(LHSType, RHSType)) { 1461 // Do cases not handled in above. 1462 // FIXME. For future support of covariant property types, revisit this. 1463 bool IncompatibleObjC = false; 1464 QualType ConvertedType; 1465 if (!isObjCPointerConversion(RHSType, LHSType, 1466 ConvertedType, IncompatibleObjC) || 1467 IncompatibleObjC) { 1468 Diag(Property->getLocation(), diag::warn_property_types_are_incompatible) 1469 << Property->getType() << SuperProperty->getType() << inheritedName; 1470 Diag(SuperProperty->getLocation(), diag::note_property_declare); 1471 } 1472 } 1473} 1474 1475bool Sema::DiagnosePropertyAccessorMismatch(ObjCPropertyDecl *property, 1476 ObjCMethodDecl *GetterMethod, 1477 SourceLocation Loc) { 1478 if (!GetterMethod) 1479 return false; 1480 QualType GetterType = GetterMethod->getReturnType().getNonReferenceType(); 1481 QualType PropertyIvarType = property->getType().getNonReferenceType(); 1482 bool compat = Context.hasSameType(PropertyIvarType, GetterType); 1483 if (!compat) { 1484 const ObjCObjectPointerType *propertyObjCPtr = nullptr; 1485 const ObjCObjectPointerType *getterObjCPtr = nullptr; 1486 if ((propertyObjCPtr = PropertyIvarType->getAs<ObjCObjectPointerType>()) && 1487 (getterObjCPtr = GetterType->getAs<ObjCObjectPointerType>())) 1488 compat = Context.canAssignObjCInterfaces(getterObjCPtr, propertyObjCPtr); 1489 else if (CheckAssignmentConstraints(Loc, GetterType, PropertyIvarType) 1490 != Compatible) { 1491 Diag(Loc, diag::error_property_accessor_type) 1492 << property->getDeclName() << PropertyIvarType 1493 << GetterMethod->getSelector() << GetterType; 1494 Diag(GetterMethod->getLocation(), diag::note_declared_at); 1495 return true; 1496 } else { 1497 compat = true; 1498 QualType lhsType =Context.getCanonicalType(PropertyIvarType).getUnqualifiedType(); 1499 QualType rhsType =Context.getCanonicalType(GetterType).getUnqualifiedType(); 1500 if (lhsType != rhsType && lhsType->isArithmeticType()) 1501 compat = false; 1502 } 1503 } 1504 1505 if (!compat) { 1506 Diag(Loc, diag::warn_accessor_property_type_mismatch) 1507 << property->getDeclName() 1508 << GetterMethod->getSelector(); 1509 Diag(GetterMethod->getLocation(), diag::note_declared_at); 1510 return true; 1511 } 1512 1513 return false; 1514} 1515 1516/// CollectImmediateProperties - This routine collects all properties in 1517/// the class and its conforming protocols; but not those in its super class. 1518static void CollectImmediateProperties(ObjCContainerDecl *CDecl, 1519 ObjCContainerDecl::PropertyMap &PropMap, 1520 ObjCContainerDecl::PropertyMap &SuperPropMap, 1521 bool IncludeProtocols = true) { 1522 1523 if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) { 1524 for (auto *Prop : IDecl->properties()) 1525 PropMap[Prop->getIdentifier()] = Prop; 1526 1527 // Collect the properties from visible extensions. 1528 for (auto *Ext : IDecl->visible_extensions()) 1529 CollectImmediateProperties(Ext, PropMap, SuperPropMap, IncludeProtocols); 1530 1531 if (IncludeProtocols) { 1532 // Scan through class's protocols. 1533 for (auto *PI : IDecl->all_referenced_protocols()) 1534 CollectImmediateProperties(PI, PropMap, SuperPropMap); 1535 } 1536 } 1537 if (ObjCCategoryDecl *CATDecl = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1538 for (auto *Prop : CATDecl->properties()) 1539 PropMap[Prop->getIdentifier()] = Prop; 1540 if (IncludeProtocols) { 1541 // Scan through class's protocols. 1542 for (auto *PI : CATDecl->protocols()) 1543 CollectImmediateProperties(PI, PropMap, SuperPropMap); 1544 } 1545 } 1546 else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(CDecl)) { 1547 for (auto *Prop : PDecl->properties()) { 1548 ObjCPropertyDecl *PropertyFromSuper = SuperPropMap[Prop->getIdentifier()]; 1549 // Exclude property for protocols which conform to class's super-class, 1550 // as super-class has to implement the property. 1551 if (!PropertyFromSuper || 1552 PropertyFromSuper->getIdentifier() != Prop->getIdentifier()) { 1553 ObjCPropertyDecl *&PropEntry = PropMap[Prop->getIdentifier()]; 1554 if (!PropEntry) 1555 PropEntry = Prop; 1556 } 1557 } 1558 // scan through protocol's protocols. 1559 for (auto *PI : PDecl->protocols()) 1560 CollectImmediateProperties(PI, PropMap, SuperPropMap); 1561 } 1562} 1563 1564/// CollectSuperClassPropertyImplementations - This routine collects list of 1565/// properties to be implemented in super class(s) and also coming from their 1566/// conforming protocols. 1567static void CollectSuperClassPropertyImplementations(ObjCInterfaceDecl *CDecl, 1568 ObjCInterfaceDecl::PropertyMap &PropMap) { 1569 if (ObjCInterfaceDecl *SDecl = CDecl->getSuperClass()) { 1570 ObjCInterfaceDecl::PropertyDeclOrder PO; 1571 while (SDecl) { 1572 SDecl->collectPropertiesToImplement(PropMap, PO); 1573 SDecl = SDecl->getSuperClass(); 1574 } 1575 } 1576} 1577 1578/// IvarBacksCurrentMethodAccessor - This routine returns 'true' if 'IV' is 1579/// an ivar synthesized for 'Method' and 'Method' is a property accessor 1580/// declared in class 'IFace'. 1581bool 1582Sema::IvarBacksCurrentMethodAccessor(ObjCInterfaceDecl *IFace, 1583 ObjCMethodDecl *Method, ObjCIvarDecl *IV) { 1584 if (!IV->getSynthesize()) 1585 return false; 1586 ObjCMethodDecl *IMD = IFace->lookupMethod(Method->getSelector(), 1587 Method->isInstanceMethod()); 1588 if (!IMD || !IMD->isPropertyAccessor()) 1589 return false; 1590 1591 // look up a property declaration whose one of its accessors is implemented 1592 // by this method. 1593 for (const auto *Property : IFace->properties()) { 1594 if ((Property->getGetterName() == IMD->getSelector() || 1595 Property->getSetterName() == IMD->getSelector()) && 1596 (Property->getPropertyIvarDecl() == IV)) 1597 return true; 1598 } 1599 // Also look up property declaration in class extension whose one of its 1600 // accessors is implemented by this method. 1601 for (const auto *Ext : IFace->known_extensions()) 1602 for (const auto *Property : Ext->properties()) 1603 if ((Property->getGetterName() == IMD->getSelector() || 1604 Property->getSetterName() == IMD->getSelector()) && 1605 (Property->getPropertyIvarDecl() == IV)) 1606 return true; 1607 return false; 1608} 1609 1610static bool SuperClassImplementsProperty(ObjCInterfaceDecl *IDecl, 1611 ObjCPropertyDecl *Prop) { 1612 bool SuperClassImplementsGetter = false; 1613 bool SuperClassImplementsSetter = false; 1614 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly) 1615 SuperClassImplementsSetter = true; 1616 1617 while (IDecl->getSuperClass()) { 1618 ObjCInterfaceDecl *SDecl = IDecl->getSuperClass(); 1619 if (!SuperClassImplementsGetter && SDecl->getInstanceMethod(Prop->getGetterName())) 1620 SuperClassImplementsGetter = true; 1621 1622 if (!SuperClassImplementsSetter && SDecl->getInstanceMethod(Prop->getSetterName())) 1623 SuperClassImplementsSetter = true; 1624 if (SuperClassImplementsGetter && SuperClassImplementsSetter) 1625 return true; 1626 IDecl = IDecl->getSuperClass(); 1627 } 1628 return false; 1629} 1630 1631/// \brief Default synthesizes all properties which must be synthesized 1632/// in class's \@implementation. 1633void Sema::DefaultSynthesizeProperties(Scope *S, ObjCImplDecl* IMPDecl, 1634 ObjCInterfaceDecl *IDecl) { 1635 1636 ObjCInterfaceDecl::PropertyMap PropMap; 1637 ObjCInterfaceDecl::PropertyDeclOrder PropertyOrder; 1638 IDecl->collectPropertiesToImplement(PropMap, PropertyOrder); 1639 if (PropMap.empty()) 1640 return; 1641 ObjCInterfaceDecl::PropertyMap SuperPropMap; 1642 CollectSuperClassPropertyImplementations(IDecl, SuperPropMap); 1643 1644 for (unsigned i = 0, e = PropertyOrder.size(); i != e; i++) { 1645 ObjCPropertyDecl *Prop = PropertyOrder[i]; 1646 // Is there a matching property synthesize/dynamic? 1647 if (Prop->isInvalidDecl() || 1648 Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional) 1649 continue; 1650 // Property may have been synthesized by user. 1651 if (IMPDecl->FindPropertyImplDecl(Prop->getIdentifier())) 1652 continue; 1653 if (IMPDecl->getInstanceMethod(Prop->getGetterName())) { 1654 if (Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readonly) 1655 continue; 1656 if (IMPDecl->getInstanceMethod(Prop->getSetterName())) 1657 continue; 1658 } 1659 if (ObjCPropertyImplDecl *PID = 1660 IMPDecl->FindPropertyImplIvarDecl(Prop->getIdentifier())) { 1661 Diag(Prop->getLocation(), diag::warn_no_autosynthesis_shared_ivar_property) 1662 << Prop->getIdentifier(); 1663 if (PID->getLocation().isValid()) 1664 Diag(PID->getLocation(), diag::note_property_synthesize); 1665 continue; 1666 } 1667 ObjCPropertyDecl *PropInSuperClass = SuperPropMap[Prop->getIdentifier()]; 1668 if (ObjCProtocolDecl *Proto = 1669 dyn_cast<ObjCProtocolDecl>(Prop->getDeclContext())) { 1670 // We won't auto-synthesize properties declared in protocols. 1671 // Suppress the warning if class's superclass implements property's 1672 // getter and implements property's setter (if readwrite property). 1673 // Or, if property is going to be implemented in its super class. 1674 if (!SuperClassImplementsProperty(IDecl, Prop) && !PropInSuperClass) { 1675 Diag(IMPDecl->getLocation(), 1676 diag::warn_auto_synthesizing_protocol_property) 1677 << Prop << Proto; 1678 Diag(Prop->getLocation(), diag::note_property_declare); 1679 } 1680 continue; 1681 } 1682 // If property to be implemented in the super class, ignore. 1683 if (PropInSuperClass) { 1684 if ((Prop->getPropertyAttributes() & ObjCPropertyDecl::OBJC_PR_readwrite) && 1685 (PropInSuperClass->getPropertyAttributes() & 1686 ObjCPropertyDecl::OBJC_PR_readonly) && 1687 !IMPDecl->getInstanceMethod(Prop->getSetterName()) && 1688 !IDecl->HasUserDeclaredSetterMethod(Prop)) { 1689 Diag(Prop->getLocation(), diag::warn_no_autosynthesis_property) 1690 << Prop->getIdentifier(); 1691 Diag(PropInSuperClass->getLocation(), diag::note_property_declare); 1692 } 1693 else { 1694 Diag(Prop->getLocation(), diag::warn_autosynthesis_property_in_superclass) 1695 << Prop->getIdentifier(); 1696 Diag(PropInSuperClass->getLocation(), diag::note_property_declare); 1697 Diag(IMPDecl->getLocation(), diag::note_while_in_implementation); 1698 } 1699 continue; 1700 } 1701 // We use invalid SourceLocations for the synthesized ivars since they 1702 // aren't really synthesized at a particular location; they just exist. 1703 // Saying that they are located at the @implementation isn't really going 1704 // to help users. 1705 ObjCPropertyImplDecl *PIDecl = dyn_cast_or_null<ObjCPropertyImplDecl>( 1706 ActOnPropertyImplDecl(S, SourceLocation(), SourceLocation(), 1707 true, 1708 /* property = */ Prop->getIdentifier(), 1709 /* ivar = */ Prop->getDefaultSynthIvarName(Context), 1710 Prop->getLocation())); 1711 if (PIDecl) { 1712 Diag(Prop->getLocation(), diag::warn_missing_explicit_synthesis); 1713 Diag(IMPDecl->getLocation(), diag::note_while_in_implementation); 1714 } 1715 } 1716} 1717 1718void Sema::DefaultSynthesizeProperties(Scope *S, Decl *D) { 1719 if (!LangOpts.ObjCDefaultSynthProperties || LangOpts.ObjCRuntime.isFragile()) 1720 return; 1721 ObjCImplementationDecl *IC=dyn_cast_or_null<ObjCImplementationDecl>(D); 1722 if (!IC) 1723 return; 1724 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) 1725 if (!IDecl->isObjCRequiresPropertyDefs()) 1726 DefaultSynthesizeProperties(S, IC, IDecl); 1727} 1728 1729static void DiagnoseUnimplementedAccessor(Sema &S, 1730 ObjCInterfaceDecl *PrimaryClass, 1731 Selector Method, 1732 ObjCImplDecl* IMPDecl, 1733 ObjCContainerDecl *CDecl, 1734 ObjCCategoryDecl *C, 1735 ObjCPropertyDecl *Prop, 1736 Sema::SelectorSet &SMap) { 1737 // When reporting on missing property setter/getter implementation in 1738 // categories, do not report when they are declared in primary class, 1739 // class's protocol, or one of it super classes. This is because, 1740 // the class is going to implement them. 1741 if (!SMap.count(Method) && 1742 (PrimaryClass == nullptr || 1743 !PrimaryClass->lookupPropertyAccessor(Method, C))) { 1744 S.Diag(IMPDecl->getLocation(), 1745 isa<ObjCCategoryDecl>(CDecl) ? 1746 diag::warn_setter_getter_impl_required_in_category : 1747 diag::warn_setter_getter_impl_required) 1748 << Prop->getDeclName() << Method; 1749 S.Diag(Prop->getLocation(), 1750 diag::note_property_declare); 1751 if (S.LangOpts.ObjCDefaultSynthProperties && 1752 S.LangOpts.ObjCRuntime.isNonFragile()) 1753 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(CDecl)) 1754 if (const ObjCInterfaceDecl *RID = ID->isObjCRequiresPropertyDefs()) 1755 S.Diag(RID->getLocation(), diag::note_suppressed_class_declare); 1756 } 1757} 1758 1759void Sema::DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl* IMPDecl, 1760 ObjCContainerDecl *CDecl, 1761 bool SynthesizeProperties) { 1762 ObjCContainerDecl::PropertyMap PropMap; 1763 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl); 1764 1765 if (!SynthesizeProperties) { 1766 ObjCContainerDecl::PropertyMap NoNeedToImplPropMap; 1767 // Gather properties which need not be implemented in this class 1768 // or category. 1769 if (!IDecl) 1770 if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) { 1771 // For categories, no need to implement properties declared in 1772 // its primary class (and its super classes) if property is 1773 // declared in one of those containers. 1774 if ((IDecl = C->getClassInterface())) { 1775 ObjCInterfaceDecl::PropertyDeclOrder PO; 1776 IDecl->collectPropertiesToImplement(NoNeedToImplPropMap, PO); 1777 } 1778 } 1779 if (IDecl) 1780 CollectSuperClassPropertyImplementations(IDecl, NoNeedToImplPropMap); 1781 1782 CollectImmediateProperties(CDecl, PropMap, NoNeedToImplPropMap); 1783 } 1784 1785 // Scan the @interface to see if any of the protocols it adopts 1786 // require an explicit implementation, via attribute 1787 // 'objc_protocol_requires_explicit_implementation'. 1788 if (IDecl) { 1789 std::unique_ptr<ObjCContainerDecl::PropertyMap> LazyMap; 1790 1791 for (auto *PDecl : IDecl->all_referenced_protocols()) { 1792 if (!PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) 1793 continue; 1794 // Lazily construct a set of all the properties in the @interface 1795 // of the class, without looking at the superclass. We cannot 1796 // use the call to CollectImmediateProperties() above as that 1797 // utilizes information from the super class's properties as well 1798 // as scans the adopted protocols. This work only triggers for protocols 1799 // with the attribute, which is very rare, and only occurs when 1800 // analyzing the @implementation. 1801 if (!LazyMap) { 1802 ObjCContainerDecl::PropertyMap NoNeedToImplPropMap; 1803 LazyMap.reset(new ObjCContainerDecl::PropertyMap()); 1804 CollectImmediateProperties(CDecl, *LazyMap, NoNeedToImplPropMap, 1805 /* IncludeProtocols */ false); 1806 } 1807 // Add the properties of 'PDecl' to the list of properties that 1808 // need to be implemented. 1809 for (auto *PropDecl : PDecl->properties()) { 1810 if ((*LazyMap)[PropDecl->getIdentifier()]) 1811 continue; 1812 PropMap[PropDecl->getIdentifier()] = PropDecl; 1813 } 1814 } 1815 } 1816 1817 if (PropMap.empty()) 1818 return; 1819 1820 llvm::DenseSet<ObjCPropertyDecl *> PropImplMap; 1821 for (const auto *I : IMPDecl->property_impls()) 1822 PropImplMap.insert(I->getPropertyDecl()); 1823 1824 SelectorSet InsMap; 1825 // Collect property accessors implemented in current implementation. 1826 for (const auto *I : IMPDecl->instance_methods()) 1827 InsMap.insert(I->getSelector()); 1828 1829 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl); 1830 ObjCInterfaceDecl *PrimaryClass = nullptr; 1831 if (C && !C->IsClassExtension()) 1832 if ((PrimaryClass = C->getClassInterface())) 1833 // Report unimplemented properties in the category as well. 1834 if (ObjCImplDecl *IMP = PrimaryClass->getImplementation()) { 1835 // When reporting on missing setter/getters, do not report when 1836 // setter/getter is implemented in category's primary class 1837 // implementation. 1838 for (const auto *I : IMP->instance_methods()) 1839 InsMap.insert(I->getSelector()); 1840 } 1841 1842 for (ObjCContainerDecl::PropertyMap::iterator 1843 P = PropMap.begin(), E = PropMap.end(); P != E; ++P) { 1844 ObjCPropertyDecl *Prop = P->second; 1845 // Is there a matching propery synthesize/dynamic? 1846 if (Prop->isInvalidDecl() || 1847 Prop->getPropertyImplementation() == ObjCPropertyDecl::Optional || 1848 PropImplMap.count(Prop) || 1849 Prop->getAvailability() == AR_Unavailable) 1850 continue; 1851 1852 // Diagnose unimplemented getters and setters. 1853 DiagnoseUnimplementedAccessor(*this, 1854 PrimaryClass, Prop->getGetterName(), IMPDecl, CDecl, C, Prop, InsMap); 1855 if (!Prop->isReadOnly()) 1856 DiagnoseUnimplementedAccessor(*this, 1857 PrimaryClass, Prop->getSetterName(), 1858 IMPDecl, CDecl, C, Prop, InsMap); 1859 } 1860} 1861 1862void Sema::diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl) { 1863 for (const auto *propertyImpl : impDecl->property_impls()) { 1864 const auto *property = propertyImpl->getPropertyDecl(); 1865 1866 // Warn about null_resettable properties with synthesized setters, 1867 // because the setter won't properly handle nil. 1868 if (propertyImpl->getPropertyImplementation() 1869 == ObjCPropertyImplDecl::Synthesize && 1870 (property->getPropertyAttributes() & 1871 ObjCPropertyDecl::OBJC_PR_null_resettable) && 1872 property->getGetterMethodDecl() && 1873 property->getSetterMethodDecl()) { 1874 auto *getterMethod = property->getGetterMethodDecl(); 1875 auto *setterMethod = property->getSetterMethodDecl(); 1876 if (!impDecl->getInstanceMethod(setterMethod->getSelector()) && 1877 !impDecl->getInstanceMethod(getterMethod->getSelector())) { 1878 SourceLocation loc = propertyImpl->getLocation(); 1879 if (loc.isInvalid()) 1880 loc = impDecl->getLocStart(); 1881 1882 Diag(loc, diag::warn_null_resettable_setter) 1883 << setterMethod->getSelector() << property->getDeclName(); 1884 } 1885 } 1886 } 1887} 1888 1889void 1890Sema::AtomicPropertySetterGetterRules (ObjCImplDecl* IMPDecl, 1891 ObjCInterfaceDecl* IDecl) { 1892 // Rules apply in non-GC mode only 1893 if (getLangOpts().getGC() != LangOptions::NonGC) 1894 return; 1895 ObjCContainerDecl::PropertyMap PM; 1896 for (auto *Prop : IDecl->properties()) 1897 PM[Prop->getIdentifier()] = Prop; 1898 for (const auto *Ext : IDecl->known_extensions()) 1899 for (auto *Prop : Ext->properties()) 1900 PM[Prop->getIdentifier()] = Prop; 1901 1902 for (ObjCContainerDecl::PropertyMap::iterator I = PM.begin(), E = PM.end(); 1903 I != E; ++I) { 1904 const ObjCPropertyDecl *Property = I->second; 1905 ObjCMethodDecl *GetterMethod = nullptr; 1906 ObjCMethodDecl *SetterMethod = nullptr; 1907 bool LookedUpGetterSetter = false; 1908 1909 unsigned Attributes = Property->getPropertyAttributes(); 1910 unsigned AttributesAsWritten = Property->getPropertyAttributesAsWritten(); 1911 1912 if (!(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic) && 1913 !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_nonatomic)) { 1914 GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName()); 1915 SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName()); 1916 LookedUpGetterSetter = true; 1917 if (GetterMethod) { 1918 Diag(GetterMethod->getLocation(), 1919 diag::warn_default_atomic_custom_getter_setter) 1920 << Property->getIdentifier() << 0; 1921 Diag(Property->getLocation(), diag::note_property_declare); 1922 } 1923 if (SetterMethod) { 1924 Diag(SetterMethod->getLocation(), 1925 diag::warn_default_atomic_custom_getter_setter) 1926 << Property->getIdentifier() << 1; 1927 Diag(Property->getLocation(), diag::note_property_declare); 1928 } 1929 } 1930 1931 // We only care about readwrite atomic property. 1932 if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) || 1933 !(Attributes & ObjCPropertyDecl::OBJC_PR_readwrite)) 1934 continue; 1935 if (const ObjCPropertyImplDecl *PIDecl 1936 = IMPDecl->FindPropertyImplDecl(Property->getIdentifier())) { 1937 if (PIDecl->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic) 1938 continue; 1939 if (!LookedUpGetterSetter) { 1940 GetterMethod = IMPDecl->getInstanceMethod(Property->getGetterName()); 1941 SetterMethod = IMPDecl->getInstanceMethod(Property->getSetterName()); 1942 } 1943 if ((GetterMethod && !SetterMethod) || (!GetterMethod && SetterMethod)) { 1944 SourceLocation MethodLoc = 1945 (GetterMethod ? GetterMethod->getLocation() 1946 : SetterMethod->getLocation()); 1947 Diag(MethodLoc, diag::warn_atomic_property_rule) 1948 << Property->getIdentifier() << (GetterMethod != nullptr) 1949 << (SetterMethod != nullptr); 1950 // fixit stuff. 1951 if (Property->getLParenLoc().isValid() && 1952 !(AttributesAsWritten & ObjCPropertyDecl::OBJC_PR_atomic)) { 1953 // @property () ... case. 1954 SourceLocation AfterLParen = 1955 getLocForEndOfToken(Property->getLParenLoc()); 1956 StringRef NonatomicStr = AttributesAsWritten? "nonatomic, " 1957 : "nonatomic"; 1958 Diag(Property->getLocation(), 1959 diag::note_atomic_property_fixup_suggest) 1960 << FixItHint::CreateInsertion(AfterLParen, NonatomicStr); 1961 } else if (Property->getLParenLoc().isInvalid()) { 1962 //@property id etc. 1963 SourceLocation startLoc = 1964 Property->getTypeSourceInfo()->getTypeLoc().getBeginLoc(); 1965 Diag(Property->getLocation(), 1966 diag::note_atomic_property_fixup_suggest) 1967 << FixItHint::CreateInsertion(startLoc, "(nonatomic) "); 1968 } 1969 else 1970 Diag(MethodLoc, diag::note_atomic_property_fixup_suggest); 1971 Diag(Property->getLocation(), diag::note_property_declare); 1972 } 1973 } 1974 } 1975} 1976 1977void Sema::DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D) { 1978 if (getLangOpts().getGC() == LangOptions::GCOnly) 1979 return; 1980 1981 for (const auto *PID : D->property_impls()) { 1982 const ObjCPropertyDecl *PD = PID->getPropertyDecl(); 1983 if (PD && !PD->hasAttr<NSReturnsNotRetainedAttr>() && 1984 !D->getInstanceMethod(PD->getGetterName())) { 1985 ObjCMethodDecl *method = PD->getGetterMethodDecl(); 1986 if (!method) 1987 continue; 1988 ObjCMethodFamily family = method->getMethodFamily(); 1989 if (family == OMF_alloc || family == OMF_copy || 1990 family == OMF_mutableCopy || family == OMF_new) { 1991 if (getLangOpts().ObjCAutoRefCount) 1992 Diag(PD->getLocation(), diag::err_cocoa_naming_owned_rule); 1993 else 1994 Diag(PD->getLocation(), diag::warn_cocoa_naming_owned_rule); 1995 1996 // Look for a getter explicitly declared alongside the property. 1997 // If we find one, use its location for the note. 1998 SourceLocation noteLoc = PD->getLocation(); 1999 SourceLocation fixItLoc; 2000 for (auto *getterRedecl : method->redecls()) { 2001 if (getterRedecl->isImplicit()) 2002 continue; 2003 if (getterRedecl->getDeclContext() != PD->getDeclContext()) 2004 continue; 2005 noteLoc = getterRedecl->getLocation(); 2006 fixItLoc = getterRedecl->getLocEnd(); 2007 } 2008 2009 Preprocessor &PP = getPreprocessor(); 2010 TokenValue tokens[] = { 2011 tok::kw___attribute, tok::l_paren, tok::l_paren, 2012 PP.getIdentifierInfo("objc_method_family"), tok::l_paren, 2013 PP.getIdentifierInfo("none"), tok::r_paren, 2014 tok::r_paren, tok::r_paren 2015 }; 2016 StringRef spelling = "__attribute__((objc_method_family(none)))"; 2017 StringRef macroName = PP.getLastMacroWithSpelling(noteLoc, tokens); 2018 if (!macroName.empty()) 2019 spelling = macroName; 2020 2021 auto noteDiag = Diag(noteLoc, diag::note_cocoa_naming_declare_family) 2022 << method->getDeclName() << spelling; 2023 if (fixItLoc.isValid()) { 2024 SmallString<64> fixItText(" "); 2025 fixItText += spelling; 2026 noteDiag << FixItHint::CreateInsertion(fixItLoc, fixItText); 2027 } 2028 } 2029 } 2030 } 2031} 2032 2033void Sema::DiagnoseMissingDesignatedInitOverrides( 2034 const ObjCImplementationDecl *ImplD, 2035 const ObjCInterfaceDecl *IFD) { 2036 assert(IFD->hasDesignatedInitializers()); 2037 const ObjCInterfaceDecl *SuperD = IFD->getSuperClass(); 2038 if (!SuperD) 2039 return; 2040 2041 SelectorSet InitSelSet; 2042 for (const auto *I : ImplD->instance_methods()) 2043 if (I->getMethodFamily() == OMF_init) 2044 InitSelSet.insert(I->getSelector()); 2045 2046 SmallVector<const ObjCMethodDecl *, 8> DesignatedInits; 2047 SuperD->getDesignatedInitializers(DesignatedInits); 2048 for (SmallVector<const ObjCMethodDecl *, 8>::iterator 2049 I = DesignatedInits.begin(), E = DesignatedInits.end(); I != E; ++I) { 2050 const ObjCMethodDecl *MD = *I; 2051 if (!InitSelSet.count(MD->getSelector())) { 2052 bool Ignore = false; 2053 if (auto *IMD = IFD->getInstanceMethod(MD->getSelector())) { 2054 Ignore = IMD->isUnavailable(); 2055 } 2056 if (!Ignore) { 2057 Diag(ImplD->getLocation(), 2058 diag::warn_objc_implementation_missing_designated_init_override) 2059 << MD->getSelector(); 2060 Diag(MD->getLocation(), diag::note_objc_designated_init_marked_here); 2061 } 2062 } 2063 } 2064} 2065 2066/// AddPropertyAttrs - Propagates attributes from a property to the 2067/// implicitly-declared getter or setter for that property. 2068static void AddPropertyAttrs(Sema &S, ObjCMethodDecl *PropertyMethod, 2069 ObjCPropertyDecl *Property) { 2070 // Should we just clone all attributes over? 2071 for (const auto *A : Property->attrs()) { 2072 if (isa<DeprecatedAttr>(A) || 2073 isa<UnavailableAttr>(A) || 2074 isa<AvailabilityAttr>(A)) 2075 PropertyMethod->addAttr(A->clone(S.Context)); 2076 } 2077} 2078 2079/// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods 2080/// have the property type and issue diagnostics if they don't. 2081/// Also synthesize a getter/setter method if none exist (and update the 2082/// appropriate lookup tables. 2083void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property) { 2084 ObjCMethodDecl *GetterMethod, *SetterMethod; 2085 ObjCContainerDecl *CD = cast<ObjCContainerDecl>(property->getDeclContext()); 2086 if (CD->isInvalidDecl()) 2087 return; 2088 2089 GetterMethod = CD->getInstanceMethod(property->getGetterName()); 2090 // if setter or getter is not found in class extension, it might be 2091 // in the primary class. 2092 if (!GetterMethod) 2093 if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) 2094 if (CatDecl->IsClassExtension()) 2095 GetterMethod = CatDecl->getClassInterface()-> 2096 getInstanceMethod(property->getGetterName()); 2097 2098 SetterMethod = CD->getInstanceMethod(property->getSetterName()); 2099 if (!SetterMethod) 2100 if (const ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CD)) 2101 if (CatDecl->IsClassExtension()) 2102 SetterMethod = CatDecl->getClassInterface()-> 2103 getInstanceMethod(property->getSetterName()); 2104 DiagnosePropertyAccessorMismatch(property, GetterMethod, 2105 property->getLocation()); 2106 2107 if (SetterMethod) { 2108 ObjCPropertyDecl::PropertyAttributeKind CAttr = 2109 property->getPropertyAttributes(); 2110 if ((!(CAttr & ObjCPropertyDecl::OBJC_PR_readonly)) && 2111 Context.getCanonicalType(SetterMethod->getReturnType()) != 2112 Context.VoidTy) 2113 Diag(SetterMethod->getLocation(), diag::err_setter_type_void); 2114 if (SetterMethod->param_size() != 1 || 2115 !Context.hasSameUnqualifiedType( 2116 (*SetterMethod->param_begin())->getType().getNonReferenceType(), 2117 property->getType().getNonReferenceType())) { 2118 Diag(property->getLocation(), 2119 diag::warn_accessor_property_type_mismatch) 2120 << property->getDeclName() 2121 << SetterMethod->getSelector(); 2122 Diag(SetterMethod->getLocation(), diag::note_declared_at); 2123 } 2124 } 2125 2126 // Synthesize getter/setter methods if none exist. 2127 // Find the default getter and if one not found, add one. 2128 // FIXME: The synthesized property we set here is misleading. We almost always 2129 // synthesize these methods unless the user explicitly provided prototypes 2130 // (which is odd, but allowed). Sema should be typechecking that the 2131 // declarations jive in that situation (which it is not currently). 2132 if (!GetterMethod) { 2133 // No instance method of same name as property getter name was found. 2134 // Declare a getter method and add it to the list of methods 2135 // for this class. 2136 SourceLocation Loc = property->getLocation(); 2137 2138 // If the property is null_resettable, the getter returns nonnull. 2139 QualType resultTy = property->getType(); 2140 if (property->getPropertyAttributes() & 2141 ObjCPropertyDecl::OBJC_PR_null_resettable) { 2142 QualType modifiedTy = resultTy; 2143 if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)) { 2144 if (*nullability == NullabilityKind::Unspecified) 2145 resultTy = Context.getAttributedType(AttributedType::attr_nonnull, 2146 modifiedTy, modifiedTy); 2147 } 2148 } 2149 2150 GetterMethod = ObjCMethodDecl::Create(Context, Loc, Loc, 2151 property->getGetterName(), 2152 resultTy, nullptr, CD, 2153 /*isInstance=*/true, /*isVariadic=*/false, 2154 /*isPropertyAccessor=*/true, 2155 /*isImplicitlyDeclared=*/true, /*isDefined=*/false, 2156 (property->getPropertyImplementation() == 2157 ObjCPropertyDecl::Optional) ? 2158 ObjCMethodDecl::Optional : 2159 ObjCMethodDecl::Required); 2160 CD->addDecl(GetterMethod); 2161 2162 AddPropertyAttrs(*this, GetterMethod, property); 2163 2164 if (property->hasAttr<NSReturnsNotRetainedAttr>()) 2165 GetterMethod->addAttr(NSReturnsNotRetainedAttr::CreateImplicit(Context, 2166 Loc)); 2167 2168 if (property->hasAttr<ObjCReturnsInnerPointerAttr>()) 2169 GetterMethod->addAttr( 2170 ObjCReturnsInnerPointerAttr::CreateImplicit(Context, Loc)); 2171 2172 if (const SectionAttr *SA = property->getAttr<SectionAttr>()) 2173 GetterMethod->addAttr( 2174 SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section, 2175 SA->getName(), Loc)); 2176 2177 if (getLangOpts().ObjCAutoRefCount) 2178 CheckARCMethodDecl(GetterMethod); 2179 } else 2180 // A user declared getter will be synthesize when @synthesize of 2181 // the property with the same name is seen in the @implementation 2182 GetterMethod->setPropertyAccessor(true); 2183 property->setGetterMethodDecl(GetterMethod); 2184 2185 // Skip setter if property is read-only. 2186 if (!property->isReadOnly()) { 2187 // Find the default setter and if one not found, add one. 2188 if (!SetterMethod) { 2189 // No instance method of same name as property setter name was found. 2190 // Declare a setter method and add it to the list of methods 2191 // for this class. 2192 SourceLocation Loc = property->getLocation(); 2193 2194 SetterMethod = 2195 ObjCMethodDecl::Create(Context, Loc, Loc, 2196 property->getSetterName(), Context.VoidTy, 2197 nullptr, CD, /*isInstance=*/true, 2198 /*isVariadic=*/false, 2199 /*isPropertyAccessor=*/true, 2200 /*isImplicitlyDeclared=*/true, 2201 /*isDefined=*/false, 2202 (property->getPropertyImplementation() == 2203 ObjCPropertyDecl::Optional) ? 2204 ObjCMethodDecl::Optional : 2205 ObjCMethodDecl::Required); 2206 2207 // If the property is null_resettable, the setter accepts a 2208 // nullable value. 2209 QualType paramTy = property->getType().getUnqualifiedType(); 2210 if (property->getPropertyAttributes() & 2211 ObjCPropertyDecl::OBJC_PR_null_resettable) { 2212 QualType modifiedTy = paramTy; 2213 if (auto nullability = AttributedType::stripOuterNullability(modifiedTy)){ 2214 if (*nullability == NullabilityKind::Unspecified) 2215 paramTy = Context.getAttributedType(AttributedType::attr_nullable, 2216 modifiedTy, modifiedTy); 2217 } 2218 } 2219 2220 // Invent the arguments for the setter. We don't bother making a 2221 // nice name for the argument. 2222 ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod, 2223 Loc, Loc, 2224 property->getIdentifier(), 2225 paramTy, 2226 /*TInfo=*/nullptr, 2227 SC_None, 2228 nullptr); 2229 SetterMethod->setMethodParams(Context, Argument, None); 2230 2231 AddPropertyAttrs(*this, SetterMethod, property); 2232 2233 CD->addDecl(SetterMethod); 2234 if (const SectionAttr *SA = property->getAttr<SectionAttr>()) 2235 SetterMethod->addAttr( 2236 SectionAttr::CreateImplicit(Context, SectionAttr::GNU_section, 2237 SA->getName(), Loc)); 2238 // It's possible for the user to have set a very odd custom 2239 // setter selector that causes it to have a method family. 2240 if (getLangOpts().ObjCAutoRefCount) 2241 CheckARCMethodDecl(SetterMethod); 2242 } else 2243 // A user declared setter will be synthesize when @synthesize of 2244 // the property with the same name is seen in the @implementation 2245 SetterMethod->setPropertyAccessor(true); 2246 property->setSetterMethodDecl(SetterMethod); 2247 } 2248 // Add any synthesized methods to the global pool. This allows us to 2249 // handle the following, which is supported by GCC (and part of the design). 2250 // 2251 // @interface Foo 2252 // @property double bar; 2253 // @end 2254 // 2255 // void thisIsUnfortunate() { 2256 // id foo; 2257 // double bar = [foo bar]; 2258 // } 2259 // 2260 if (GetterMethod) 2261 AddInstanceMethodToGlobalPool(GetterMethod); 2262 if (SetterMethod) 2263 AddInstanceMethodToGlobalPool(SetterMethod); 2264 2265 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(CD); 2266 if (!CurrentClass) { 2267 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(CD)) 2268 CurrentClass = Cat->getClassInterface(); 2269 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(CD)) 2270 CurrentClass = Impl->getClassInterface(); 2271 } 2272 if (GetterMethod) 2273 CheckObjCMethodOverrides(GetterMethod, CurrentClass, Sema::RTC_Unknown); 2274 if (SetterMethod) 2275 CheckObjCMethodOverrides(SetterMethod, CurrentClass, Sema::RTC_Unknown); 2276} 2277 2278void Sema::CheckObjCPropertyAttributes(Decl *PDecl, 2279 SourceLocation Loc, 2280 unsigned &Attributes, 2281 bool propertyInPrimaryClass) { 2282 // FIXME: Improve the reported location. 2283 if (!PDecl || PDecl->isInvalidDecl()) 2284 return; 2285 2286 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 2287 (Attributes & ObjCDeclSpec::DQ_PR_readwrite)) 2288 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2289 << "readonly" << "readwrite"; 2290 2291 ObjCPropertyDecl *PropertyDecl = cast<ObjCPropertyDecl>(PDecl); 2292 QualType PropertyTy = PropertyDecl->getType(); 2293 2294 // Check for copy or retain on non-object types. 2295 if ((Attributes & (ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy | 2296 ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong)) && 2297 !PropertyTy->isObjCRetainableType() && 2298 !PropertyDecl->hasAttr<ObjCNSObjectAttr>()) { 2299 Diag(Loc, diag::err_objc_property_requires_object) 2300 << (Attributes & ObjCDeclSpec::DQ_PR_weak ? "weak" : 2301 Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain (or strong)"); 2302 Attributes &= ~(ObjCDeclSpec::DQ_PR_weak | ObjCDeclSpec::DQ_PR_copy | 2303 ObjCDeclSpec::DQ_PR_retain | ObjCDeclSpec::DQ_PR_strong); 2304 PropertyDecl->setInvalidDecl(); 2305 } 2306 2307 // Check for more than one of { assign, copy, retain }. 2308 if (Attributes & ObjCDeclSpec::DQ_PR_assign) { 2309 if (Attributes & ObjCDeclSpec::DQ_PR_copy) { 2310 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2311 << "assign" << "copy"; 2312 Attributes &= ~ObjCDeclSpec::DQ_PR_copy; 2313 } 2314 if (Attributes & ObjCDeclSpec::DQ_PR_retain) { 2315 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2316 << "assign" << "retain"; 2317 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2318 } 2319 if (Attributes & ObjCDeclSpec::DQ_PR_strong) { 2320 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2321 << "assign" << "strong"; 2322 Attributes &= ~ObjCDeclSpec::DQ_PR_strong; 2323 } 2324 if (getLangOpts().ObjCAutoRefCount && 2325 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2326 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2327 << "assign" << "weak"; 2328 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2329 } 2330 if (PropertyDecl->hasAttr<IBOutletCollectionAttr>()) 2331 Diag(Loc, diag::warn_iboutletcollection_property_assign); 2332 } else if (Attributes & ObjCDeclSpec::DQ_PR_unsafe_unretained) { 2333 if (Attributes & ObjCDeclSpec::DQ_PR_copy) { 2334 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2335 << "unsafe_unretained" << "copy"; 2336 Attributes &= ~ObjCDeclSpec::DQ_PR_copy; 2337 } 2338 if (Attributes & ObjCDeclSpec::DQ_PR_retain) { 2339 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2340 << "unsafe_unretained" << "retain"; 2341 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2342 } 2343 if (Attributes & ObjCDeclSpec::DQ_PR_strong) { 2344 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2345 << "unsafe_unretained" << "strong"; 2346 Attributes &= ~ObjCDeclSpec::DQ_PR_strong; 2347 } 2348 if (getLangOpts().ObjCAutoRefCount && 2349 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2350 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2351 << "unsafe_unretained" << "weak"; 2352 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2353 } 2354 } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) { 2355 if (Attributes & ObjCDeclSpec::DQ_PR_retain) { 2356 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2357 << "copy" << "retain"; 2358 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2359 } 2360 if (Attributes & ObjCDeclSpec::DQ_PR_strong) { 2361 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2362 << "copy" << "strong"; 2363 Attributes &= ~ObjCDeclSpec::DQ_PR_strong; 2364 } 2365 if (Attributes & ObjCDeclSpec::DQ_PR_weak) { 2366 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2367 << "copy" << "weak"; 2368 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2369 } 2370 } 2371 else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) && 2372 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2373 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2374 << "retain" << "weak"; 2375 Attributes &= ~ObjCDeclSpec::DQ_PR_retain; 2376 } 2377 else if ((Attributes & ObjCDeclSpec::DQ_PR_strong) && 2378 (Attributes & ObjCDeclSpec::DQ_PR_weak)) { 2379 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2380 << "strong" << "weak"; 2381 Attributes &= ~ObjCDeclSpec::DQ_PR_weak; 2382 } 2383 2384 if (Attributes & ObjCDeclSpec::DQ_PR_weak) { 2385 // 'weak' and 'nonnull' are mutually exclusive. 2386 if (auto nullability = PropertyTy->getNullability(Context)) { 2387 if (*nullability == NullabilityKind::NonNull) 2388 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2389 << "nonnull" << "weak"; 2390 } 2391 } 2392 2393 if ((Attributes & ObjCDeclSpec::DQ_PR_atomic) && 2394 (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)) { 2395 Diag(Loc, diag::err_objc_property_attr_mutually_exclusive) 2396 << "atomic" << "nonatomic"; 2397 Attributes &= ~ObjCDeclSpec::DQ_PR_atomic; 2398 } 2399 2400 // Warn if user supplied no assignment attribute, property is 2401 // readwrite, and this is an object type. 2402 if (!getOwnershipRule(Attributes) && PropertyTy->isObjCRetainableType()) { 2403 if (Attributes & ObjCDeclSpec::DQ_PR_readonly) { 2404 // do nothing 2405 } else if (getLangOpts().ObjCAutoRefCount) { 2406 // With arc, @property definitions should default to strong when 2407 // not specified. 2408 PropertyDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_strong); 2409 } else if (PropertyTy->isObjCObjectPointerType()) { 2410 bool isAnyClassTy = 2411 (PropertyTy->isObjCClassType() || 2412 PropertyTy->isObjCQualifiedClassType()); 2413 // In non-gc, non-arc mode, 'Class' is treated as a 'void *' no need to 2414 // issue any warning. 2415 if (isAnyClassTy && getLangOpts().getGC() == LangOptions::NonGC) 2416 ; 2417 else if (propertyInPrimaryClass) { 2418 // Don't issue warning on property with no life time in class 2419 // extension as it is inherited from property in primary class. 2420 // Skip this warning in gc-only mode. 2421 if (getLangOpts().getGC() != LangOptions::GCOnly) 2422 Diag(Loc, diag::warn_objc_property_no_assignment_attribute); 2423 2424 // If non-gc code warn that this is likely inappropriate. 2425 if (getLangOpts().getGC() == LangOptions::NonGC) 2426 Diag(Loc, diag::warn_objc_property_default_assign_on_object); 2427 } 2428 } 2429 2430 // FIXME: Implement warning dependent on NSCopying being 2431 // implemented. See also: 2432 // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496> 2433 // (please trim this list while you are at it). 2434 } 2435 2436 if (!(Attributes & ObjCDeclSpec::DQ_PR_copy) 2437 &&!(Attributes & ObjCDeclSpec::DQ_PR_readonly) 2438 && getLangOpts().getGC() == LangOptions::GCOnly 2439 && PropertyTy->isBlockPointerType()) 2440 Diag(Loc, diag::warn_objc_property_copy_missing_on_block); 2441 else if ((Attributes & ObjCDeclSpec::DQ_PR_retain) && 2442 !(Attributes & ObjCDeclSpec::DQ_PR_readonly) && 2443 !(Attributes & ObjCDeclSpec::DQ_PR_strong) && 2444 PropertyTy->isBlockPointerType()) 2445 Diag(Loc, diag::warn_objc_property_retain_of_block); 2446 2447 if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) && 2448 (Attributes & ObjCDeclSpec::DQ_PR_setter)) 2449 Diag(Loc, diag::warn_objc_readonly_property_has_setter); 2450 2451} 2452