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