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