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