1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===// 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 member access expressions. 11 // 12 //===----------------------------------------------------------------------===// 13 #include "clang/Sema/SemaInternal.h" 14 #include "clang/AST/DeclCXX.h" 15 #include "clang/AST/DeclObjC.h" 16 #include "clang/AST/DeclTemplate.h" 17 #include "clang/AST/ExprCXX.h" 18 #include "clang/AST/ExprObjC.h" 19 #include "clang/Lex/Preprocessor.h" 20 #include "clang/Sema/Lookup.h" 21 #include "clang/Sema/Scope.h" 22 #include "clang/Sema/ScopeInfo.h" 23 24 using namespace clang; 25 using namespace sema; 26 27 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet; 28 static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) { 29 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr); 30 return !Bases.count(Base->getCanonicalDecl()); 31 } 32 33 /// Determines if the given class is provably not derived from all of 34 /// the prospective base classes. 35 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record, 36 const BaseSet &Bases) { 37 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases)); 38 return BaseIsNotInSet(Record, BasesPtr) && 39 Record->forallBases(BaseIsNotInSet, BasesPtr); 40 } 41 42 enum IMAKind { 43 /// The reference is definitely not an instance member access. 44 IMA_Static, 45 46 /// The reference may be an implicit instance member access. 47 IMA_Mixed, 48 49 /// The reference may be to an instance member, but it might be invalid if 50 /// so, because the context is not an instance method. 51 IMA_Mixed_StaticContext, 52 53 /// The reference may be to an instance member, but it is invalid if 54 /// so, because the context is from an unrelated class. 55 IMA_Mixed_Unrelated, 56 57 /// The reference is definitely an implicit instance member access. 58 IMA_Instance, 59 60 /// The reference may be to an unresolved using declaration. 61 IMA_Unresolved, 62 63 /// The reference may be to an unresolved using declaration and the 64 /// context is not an instance method. 65 IMA_Unresolved_StaticContext, 66 67 // The reference refers to a field which is not a member of the containing 68 // class, which is allowed because we're in C++11 mode and the context is 69 // unevaluated. 70 IMA_Field_Uneval_Context, 71 72 /// All possible referrents are instance members and the current 73 /// context is not an instance method. 74 IMA_Error_StaticContext, 75 76 /// All possible referrents are instance members of an unrelated 77 /// class. 78 IMA_Error_Unrelated 79 }; 80 81 /// The given lookup names class member(s) and is not being used for 82 /// an address-of-member expression. Classify the type of access 83 /// according to whether it's possible that this reference names an 84 /// instance member. This is best-effort in dependent contexts; it is okay to 85 /// conservatively answer "yes", in which case some errors will simply 86 /// not be caught until template-instantiation. 87 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef, 88 Scope *CurScope, 89 const LookupResult &R) { 90 assert(!R.empty() && (*R.begin())->isCXXClassMember()); 91 92 DeclContext *DC = SemaRef.getFunctionLevelDeclContext(); 93 94 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() && 95 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic()); 96 97 if (R.isUnresolvableResult()) 98 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved; 99 100 // Collect all the declaring classes of instance members we find. 101 bool hasNonInstance = false; 102 bool isField = false; 103 BaseSet Classes; 104 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 105 NamedDecl *D = *I; 106 107 if (D->isCXXInstanceMember()) { 108 if (dyn_cast<FieldDecl>(D) || dyn_cast<IndirectFieldDecl>(D)) 109 isField = true; 110 111 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext()); 112 Classes.insert(R->getCanonicalDecl()); 113 } 114 else 115 hasNonInstance = true; 116 } 117 118 // If we didn't find any instance members, it can't be an implicit 119 // member reference. 120 if (Classes.empty()) 121 return IMA_Static; 122 123 bool IsCXX11UnevaluatedField = false; 124 if (SemaRef.getLangOpts().CPlusPlus11 && isField) { 125 // C++11 [expr.prim.general]p12: 126 // An id-expression that denotes a non-static data member or non-static 127 // member function of a class can only be used: 128 // (...) 129 // - if that id-expression denotes a non-static data member and it 130 // appears in an unevaluated operand. 131 const Sema::ExpressionEvaluationContextRecord& record 132 = SemaRef.ExprEvalContexts.back(); 133 if (record.Context == Sema::Unevaluated) 134 IsCXX11UnevaluatedField = true; 135 } 136 137 // If the current context is not an instance method, it can't be 138 // an implicit member reference. 139 if (isStaticContext) { 140 if (hasNonInstance) 141 return IMA_Mixed_StaticContext; 142 143 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context 144 : IMA_Error_StaticContext; 145 } 146 147 CXXRecordDecl *contextClass; 148 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) 149 contextClass = MD->getParent()->getCanonicalDecl(); 150 else 151 contextClass = cast<CXXRecordDecl>(DC); 152 153 // [class.mfct.non-static]p3: 154 // ...is used in the body of a non-static member function of class X, 155 // if name lookup (3.4.1) resolves the name in the id-expression to a 156 // non-static non-type member of some class C [...] 157 // ...if C is not X or a base class of X, the class member access expression 158 // is ill-formed. 159 if (R.getNamingClass() && 160 contextClass->getCanonicalDecl() != 161 R.getNamingClass()->getCanonicalDecl()) { 162 // If the naming class is not the current context, this was a qualified 163 // member name lookup, and it's sufficient to check that we have the naming 164 // class as a base class. 165 Classes.clear(); 166 Classes.insert(R.getNamingClass()->getCanonicalDecl()); 167 } 168 169 // If we can prove that the current context is unrelated to all the 170 // declaring classes, it can't be an implicit member reference (in 171 // which case it's an error if any of those members are selected). 172 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes)) 173 return hasNonInstance ? IMA_Mixed_Unrelated : 174 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context : 175 IMA_Error_Unrelated; 176 177 return (hasNonInstance ? IMA_Mixed : IMA_Instance); 178 } 179 180 /// Diagnose a reference to a field with no object available. 181 static void diagnoseInstanceReference(Sema &SemaRef, 182 const CXXScopeSpec &SS, 183 NamedDecl *Rep, 184 const DeclarationNameInfo &nameInfo) { 185 SourceLocation Loc = nameInfo.getLoc(); 186 SourceRange Range(Loc); 187 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin()); 188 189 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext(); 190 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC); 191 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0; 192 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext()); 193 194 bool InStaticMethod = Method && Method->isStatic(); 195 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep); 196 197 if (IsField && InStaticMethod) 198 // "invalid use of member 'x' in static member function" 199 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method) 200 << Range << nameInfo.getName(); 201 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod && 202 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass)) 203 // Unqualified lookup in a non-static member function found a member of an 204 // enclosing class. 205 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use) 206 << IsField << RepClass << nameInfo.getName() << ContextClass << Range; 207 else if (IsField) 208 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use) 209 << nameInfo.getName() << Range; 210 else 211 SemaRef.Diag(Loc, diag::err_member_call_without_object) 212 << Range; 213 } 214 215 /// Builds an expression which might be an implicit member expression. 216 ExprResult 217 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS, 218 SourceLocation TemplateKWLoc, 219 LookupResult &R, 220 const TemplateArgumentListInfo *TemplateArgs) { 221 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) { 222 case IMA_Instance: 223 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true); 224 225 case IMA_Mixed: 226 case IMA_Mixed_Unrelated: 227 case IMA_Unresolved: 228 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false); 229 230 case IMA_Field_Uneval_Context: 231 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use) 232 << R.getLookupNameInfo().getName(); 233 // Fall through. 234 case IMA_Static: 235 case IMA_Mixed_StaticContext: 236 case IMA_Unresolved_StaticContext: 237 if (TemplateArgs || TemplateKWLoc.isValid()) 238 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs); 239 return BuildDeclarationNameExpr(SS, R, false); 240 241 case IMA_Error_StaticContext: 242 case IMA_Error_Unrelated: 243 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(), 244 R.getLookupNameInfo()); 245 return ExprError(); 246 } 247 248 llvm_unreachable("unexpected instance member access kind"); 249 } 250 251 /// Check an ext-vector component access expression. 252 /// 253 /// VK should be set in advance to the value kind of the base 254 /// expression. 255 static QualType 256 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK, 257 SourceLocation OpLoc, const IdentifierInfo *CompName, 258 SourceLocation CompLoc) { 259 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements, 260 // see FIXME there. 261 // 262 // FIXME: This logic can be greatly simplified by splitting it along 263 // halving/not halving and reworking the component checking. 264 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>(); 265 266 // The vector accessor can't exceed the number of elements. 267 const char *compStr = CompName->getNameStart(); 268 269 // This flag determines whether or not the component is one of the four 270 // special names that indicate a subset of exactly half the elements are 271 // to be selected. 272 bool HalvingSwizzle = false; 273 274 // This flag determines whether or not CompName has an 's' char prefix, 275 // indicating that it is a string of hex values to be used as vector indices. 276 bool HexSwizzle = *compStr == 's' || *compStr == 'S'; 277 278 bool HasRepeated = false; 279 bool HasIndex[16] = {}; 280 281 int Idx; 282 283 // Check that we've found one of the special components, or that the component 284 // names must come from the same set. 285 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") || 286 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) { 287 HalvingSwizzle = true; 288 } else if (!HexSwizzle && 289 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) { 290 do { 291 if (HasIndex[Idx]) HasRepeated = true; 292 HasIndex[Idx] = true; 293 compStr++; 294 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1); 295 } else { 296 if (HexSwizzle) compStr++; 297 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) { 298 if (HasIndex[Idx]) HasRepeated = true; 299 HasIndex[Idx] = true; 300 compStr++; 301 } 302 } 303 304 if (!HalvingSwizzle && *compStr) { 305 // We didn't get to the end of the string. This means the component names 306 // didn't come from the same set *or* we encountered an illegal name. 307 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal) 308 << StringRef(compStr, 1) << SourceRange(CompLoc); 309 return QualType(); 310 } 311 312 // Ensure no component accessor exceeds the width of the vector type it 313 // operates on. 314 if (!HalvingSwizzle) { 315 compStr = CompName->getNameStart(); 316 317 if (HexSwizzle) 318 compStr++; 319 320 while (*compStr) { 321 if (!vecType->isAccessorWithinNumElements(*compStr++)) { 322 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length) 323 << baseType << SourceRange(CompLoc); 324 return QualType(); 325 } 326 } 327 } 328 329 // The component accessor looks fine - now we need to compute the actual type. 330 // The vector type is implied by the component accessor. For example, 331 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc. 332 // vec4.s0 is a float, vec4.s23 is a vec3, etc. 333 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2. 334 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2 335 : CompName->getLength(); 336 if (HexSwizzle) 337 CompSize--; 338 339 if (CompSize == 1) 340 return vecType->getElementType(); 341 342 if (HasRepeated) VK = VK_RValue; 343 344 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize); 345 // Now look up the TypeDefDecl from the vector type. Without this, 346 // diagostics look bad. We want extended vector types to appear built-in. 347 for (Sema::ExtVectorDeclsType::iterator 348 I = S.ExtVectorDecls.begin(S.getExternalSource()), 349 E = S.ExtVectorDecls.end(); 350 I != E; ++I) { 351 if ((*I)->getUnderlyingType() == VT) 352 return S.Context.getTypedefType(*I); 353 } 354 355 return VT; // should never get here (a typedef type should always be found). 356 } 357 358 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl, 359 IdentifierInfo *Member, 360 const Selector &Sel, 361 ASTContext &Context) { 362 if (Member) 363 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member)) 364 return PD; 365 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel)) 366 return OMD; 367 368 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(), 369 E = PDecl->protocol_end(); I != E; ++I) { 370 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel, 371 Context)) 372 return D; 373 } 374 return 0; 375 } 376 377 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy, 378 IdentifierInfo *Member, 379 const Selector &Sel, 380 ASTContext &Context) { 381 // Check protocols on qualified interfaces. 382 Decl *GDecl = 0; 383 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 384 E = QIdTy->qual_end(); I != E; ++I) { 385 if (Member) 386 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) { 387 GDecl = PD; 388 break; 389 } 390 // Also must look for a getter or setter name which uses property syntax. 391 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) { 392 GDecl = OMD; 393 break; 394 } 395 } 396 if (!GDecl) { 397 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(), 398 E = QIdTy->qual_end(); I != E; ++I) { 399 // Search in the protocol-qualifier list of current protocol. 400 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel, 401 Context); 402 if (GDecl) 403 return GDecl; 404 } 405 } 406 return GDecl; 407 } 408 409 ExprResult 410 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType, 411 bool IsArrow, SourceLocation OpLoc, 412 const CXXScopeSpec &SS, 413 SourceLocation TemplateKWLoc, 414 NamedDecl *FirstQualifierInScope, 415 const DeclarationNameInfo &NameInfo, 416 const TemplateArgumentListInfo *TemplateArgs) { 417 // Even in dependent contexts, try to diagnose base expressions with 418 // obviously wrong types, e.g.: 419 // 420 // T* t; 421 // t.f; 422 // 423 // In Obj-C++, however, the above expression is valid, since it could be 424 // accessing the 'f' property if T is an Obj-C interface. The extra check 425 // allows this, while still reporting an error if T is a struct pointer. 426 if (!IsArrow) { 427 const PointerType *PT = BaseType->getAs<PointerType>(); 428 if (PT && (!getLangOpts().ObjC1 || 429 PT->getPointeeType()->isRecordType())) { 430 assert(BaseExpr && "cannot happen with implicit member accesses"); 431 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union) 432 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange(); 433 return ExprError(); 434 } 435 } 436 437 assert(BaseType->isDependentType() || 438 NameInfo.getName().isDependentName() || 439 isDependentScopeSpecifier(SS)); 440 441 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr 442 // must have pointer type, and the accessed type is the pointee. 443 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType, 444 IsArrow, OpLoc, 445 SS.getWithLocInContext(Context), 446 TemplateKWLoc, 447 FirstQualifierInScope, 448 NameInfo, TemplateArgs)); 449 } 450 451 /// We know that the given qualified member reference points only to 452 /// declarations which do not belong to the static type of the base 453 /// expression. Diagnose the problem. 454 static void DiagnoseQualifiedMemberReference(Sema &SemaRef, 455 Expr *BaseExpr, 456 QualType BaseType, 457 const CXXScopeSpec &SS, 458 NamedDecl *rep, 459 const DeclarationNameInfo &nameInfo) { 460 // If this is an implicit member access, use a different set of 461 // diagnostics. 462 if (!BaseExpr) 463 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo); 464 465 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated) 466 << SS.getRange() << rep << BaseType; 467 } 468 469 // Check whether the declarations we found through a nested-name 470 // specifier in a member expression are actually members of the base 471 // type. The restriction here is: 472 // 473 // C++ [expr.ref]p2: 474 // ... In these cases, the id-expression shall name a 475 // member of the class or of one of its base classes. 476 // 477 // So it's perfectly legitimate for the nested-name specifier to name 478 // an unrelated class, and for us to find an overload set including 479 // decls from classes which are not superclasses, as long as the decl 480 // we actually pick through overload resolution is from a superclass. 481 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr, 482 QualType BaseType, 483 const CXXScopeSpec &SS, 484 const LookupResult &R) { 485 CXXRecordDecl *BaseRecord = 486 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType)); 487 if (!BaseRecord) { 488 // We can't check this yet because the base type is still 489 // dependent. 490 assert(BaseType->isDependentType()); 491 return false; 492 } 493 494 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) { 495 // If this is an implicit member reference and we find a 496 // non-instance member, it's not an error. 497 if (!BaseExpr && !(*I)->isCXXInstanceMember()) 498 return false; 499 500 // Note that we use the DC of the decl, not the underlying decl. 501 DeclContext *DC = (*I)->getDeclContext(); 502 while (DC->isTransparentContext()) 503 DC = DC->getParent(); 504 505 if (!DC->isRecord()) 506 continue; 507 508 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl(); 509 if (BaseRecord->getCanonicalDecl() == MemberRecord || 510 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord)) 511 return false; 512 } 513 514 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS, 515 R.getRepresentativeDecl(), 516 R.getLookupNameInfo()); 517 return true; 518 } 519 520 namespace { 521 522 // Callback to only accept typo corrections that are either a ValueDecl or a 523 // FunctionTemplateDecl. 524 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback { 525 public: 526 virtual bool ValidateCandidate(const TypoCorrection &candidate) { 527 NamedDecl *ND = candidate.getCorrectionDecl(); 528 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)); 529 } 530 }; 531 532 } 533 534 static bool 535 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R, 536 SourceRange BaseRange, const RecordType *RTy, 537 SourceLocation OpLoc, CXXScopeSpec &SS, 538 bool HasTemplateArgs) { 539 RecordDecl *RDecl = RTy->getDecl(); 540 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) && 541 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0), 542 diag::err_typecheck_incomplete_tag, 543 BaseRange)) 544 return true; 545 546 if (HasTemplateArgs) { 547 // LookupTemplateName doesn't expect these both to exist simultaneously. 548 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0); 549 550 bool MOUS; 551 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS); 552 return false; 553 } 554 555 DeclContext *DC = RDecl; 556 if (SS.isSet()) { 557 // If the member name was a qualified-id, look into the 558 // nested-name-specifier. 559 DC = SemaRef.computeDeclContext(SS, false); 560 561 if (SemaRef.RequireCompleteDeclContext(SS, DC)) { 562 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag) 563 << SS.getRange() << DC; 564 return true; 565 } 566 567 assert(DC && "Cannot handle non-computable dependent contexts in lookup"); 568 569 if (!isa<TypeDecl>(DC)) { 570 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass) 571 << DC << SS.getRange(); 572 return true; 573 } 574 } 575 576 // The record definition is complete, now look up the member. 577 SemaRef.LookupQualifiedName(R, DC); 578 579 if (!R.empty()) 580 return false; 581 582 // We didn't find anything with the given name, so try to correct 583 // for typos. 584 DeclarationName Name = R.getLookupName(); 585 RecordMemberExprValidatorCCC Validator; 586 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(), 587 R.getLookupKind(), NULL, 588 &SS, Validator, DC); 589 R.clear(); 590 if (NamedDecl *ND = Corrected.getCorrectionDecl()) { 591 std::string CorrectedStr( 592 Corrected.getAsString(SemaRef.getLangOpts())); 593 std::string CorrectedQuotedStr( 594 Corrected.getQuoted(SemaRef.getLangOpts())); 595 R.setLookupName(Corrected.getCorrection()); 596 R.addDecl(ND); 597 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest) 598 << Name << DC << CorrectedQuotedStr << SS.getRange() 599 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(), 600 CorrectedStr); 601 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl) 602 << ND->getDeclName(); 603 } 604 605 return false; 606 } 607 608 ExprResult 609 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 610 SourceLocation OpLoc, bool IsArrow, 611 CXXScopeSpec &SS, 612 SourceLocation TemplateKWLoc, 613 NamedDecl *FirstQualifierInScope, 614 const DeclarationNameInfo &NameInfo, 615 const TemplateArgumentListInfo *TemplateArgs) { 616 if (BaseType->isDependentType() || 617 (SS.isSet() && isDependentScopeSpecifier(SS))) 618 return ActOnDependentMemberExpr(Base, BaseType, 619 IsArrow, OpLoc, 620 SS, TemplateKWLoc, FirstQualifierInScope, 621 NameInfo, TemplateArgs); 622 623 LookupResult R(*this, NameInfo, LookupMemberName); 624 625 // Implicit member accesses. 626 if (!Base) { 627 QualType RecordTy = BaseType; 628 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType(); 629 if (LookupMemberExprInRecord(*this, R, SourceRange(), 630 RecordTy->getAs<RecordType>(), 631 OpLoc, SS, TemplateArgs != 0)) 632 return ExprError(); 633 634 // Explicit member accesses. 635 } else { 636 ExprResult BaseResult = Owned(Base); 637 ExprResult Result = 638 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc, 639 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0); 640 641 if (BaseResult.isInvalid()) 642 return ExprError(); 643 Base = BaseResult.take(); 644 645 if (Result.isInvalid()) { 646 Owned(Base); 647 return ExprError(); 648 } 649 650 if (Result.get()) 651 return Result; 652 653 // LookupMemberExpr can modify Base, and thus change BaseType 654 BaseType = Base->getType(); 655 } 656 657 return BuildMemberReferenceExpr(Base, BaseType, 658 OpLoc, IsArrow, SS, TemplateKWLoc, 659 FirstQualifierInScope, R, TemplateArgs); 660 } 661 662 static ExprResult 663 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 664 const CXXScopeSpec &SS, FieldDecl *Field, 665 DeclAccessPair FoundDecl, 666 const DeclarationNameInfo &MemberNameInfo); 667 668 ExprResult 669 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 670 SourceLocation loc, 671 IndirectFieldDecl *indirectField, 672 Expr *baseObjectExpr, 673 SourceLocation opLoc) { 674 // First, build the expression that refers to the base object. 675 676 bool baseObjectIsPointer = false; 677 Qualifiers baseQuals; 678 679 // Case 1: the base of the indirect field is not a field. 680 VarDecl *baseVariable = indirectField->getVarDecl(); 681 CXXScopeSpec EmptySS; 682 if (baseVariable) { 683 assert(baseVariable->getType()->isRecordType()); 684 685 // In principle we could have a member access expression that 686 // accesses an anonymous struct/union that's a static member of 687 // the base object's class. However, under the current standard, 688 // static data members cannot be anonymous structs or unions. 689 // Supporting this is as easy as building a MemberExpr here. 690 assert(!baseObjectExpr && "anonymous struct/union is static data member?"); 691 692 DeclarationNameInfo baseNameInfo(DeclarationName(), loc); 693 694 ExprResult result 695 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable); 696 if (result.isInvalid()) return ExprError(); 697 698 baseObjectExpr = result.take(); 699 baseObjectIsPointer = false; 700 baseQuals = baseObjectExpr->getType().getQualifiers(); 701 702 // Case 2: the base of the indirect field is a field and the user 703 // wrote a member expression. 704 } else if (baseObjectExpr) { 705 // The caller provided the base object expression. Determine 706 // whether its a pointer and whether it adds any qualifiers to the 707 // anonymous struct/union fields we're looking into. 708 QualType objectType = baseObjectExpr->getType(); 709 710 if (const PointerType *ptr = objectType->getAs<PointerType>()) { 711 baseObjectIsPointer = true; 712 objectType = ptr->getPointeeType(); 713 } else { 714 baseObjectIsPointer = false; 715 } 716 baseQuals = objectType.getQualifiers(); 717 718 // Case 3: the base of the indirect field is a field and we should 719 // build an implicit member access. 720 } else { 721 // We've found a member of an anonymous struct/union that is 722 // inside a non-anonymous struct/union, so in a well-formed 723 // program our base object expression is "this". 724 QualType ThisTy = getCurrentThisType(); 725 if (ThisTy.isNull()) { 726 Diag(loc, diag::err_invalid_member_use_in_static_method) 727 << indirectField->getDeclName(); 728 return ExprError(); 729 } 730 731 // Our base object expression is "this". 732 CheckCXXThisCapture(loc); 733 baseObjectExpr 734 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true); 735 baseObjectIsPointer = true; 736 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers(); 737 } 738 739 // Build the implicit member references to the field of the 740 // anonymous struct/union. 741 Expr *result = baseObjectExpr; 742 IndirectFieldDecl::chain_iterator 743 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end(); 744 745 // Build the first member access in the chain with full information. 746 if (!baseVariable) { 747 FieldDecl *field = cast<FieldDecl>(*FI); 748 749 // FIXME: use the real found-decl info! 750 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess()); 751 752 // Make a nameInfo that properly uses the anonymous name. 753 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 754 755 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer, 756 EmptySS, field, foundDecl, 757 memberNameInfo).take(); 758 baseObjectIsPointer = false; 759 760 // FIXME: check qualified member access 761 } 762 763 // In all cases, we should now skip the first declaration in the chain. 764 ++FI; 765 766 while (FI != FEnd) { 767 FieldDecl *field = cast<FieldDecl>(*FI++); 768 769 // FIXME: these are somewhat meaningless 770 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 771 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess()); 772 773 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false, 774 (FI == FEnd? SS : EmptySS), field, 775 foundDecl, memberNameInfo).take(); 776 } 777 778 return Owned(result); 779 } 780 781 /// \brief Build a MemberExpr AST node. 782 static MemberExpr *BuildMemberExpr(Sema &SemaRef, 783 ASTContext &C, Expr *Base, bool isArrow, 784 const CXXScopeSpec &SS, 785 SourceLocation TemplateKWLoc, 786 ValueDecl *Member, 787 DeclAccessPair FoundDecl, 788 const DeclarationNameInfo &MemberNameInfo, 789 QualType Ty, 790 ExprValueKind VK, ExprObjectKind OK, 791 const TemplateArgumentListInfo *TemplateArgs = 0) { 792 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue"); 793 MemberExpr *E = 794 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C), 795 TemplateKWLoc, Member, FoundDecl, MemberNameInfo, 796 TemplateArgs, Ty, VK, OK); 797 SemaRef.MarkMemberReferenced(E); 798 return E; 799 } 800 801 ExprResult 802 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, 803 SourceLocation OpLoc, bool IsArrow, 804 const CXXScopeSpec &SS, 805 SourceLocation TemplateKWLoc, 806 NamedDecl *FirstQualifierInScope, 807 LookupResult &R, 808 const TemplateArgumentListInfo *TemplateArgs, 809 bool SuppressQualifierCheck, 810 ActOnMemberAccessExtraArgs *ExtraArgs) { 811 QualType BaseType = BaseExprType; 812 if (IsArrow) { 813 assert(BaseType->isPointerType()); 814 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 815 } 816 R.setBaseObjectType(BaseType); 817 818 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); 819 DeclarationName MemberName = MemberNameInfo.getName(); 820 SourceLocation MemberLoc = MemberNameInfo.getLoc(); 821 822 if (R.isAmbiguous()) 823 return ExprError(); 824 825 if (R.empty()) { 826 // Rederive where we looked up. 827 DeclContext *DC = (SS.isSet() 828 ? computeDeclContext(SS, false) 829 : BaseType->getAs<RecordType>()->getDecl()); 830 831 if (ExtraArgs) { 832 ExprResult RetryExpr; 833 if (!IsArrow && BaseExpr) { 834 SFINAETrap Trap(*this, true); 835 ParsedType ObjectType; 836 bool MayBePseudoDestructor = false; 837 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr, 838 OpLoc, tok::arrow, ObjectType, 839 MayBePseudoDestructor); 840 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) { 841 CXXScopeSpec TempSS(SS); 842 RetryExpr = ActOnMemberAccessExpr( 843 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS, 844 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl, 845 ExtraArgs->HasTrailingLParen); 846 } 847 if (Trap.hasErrorOccurred()) 848 RetryExpr = ExprError(); 849 } 850 if (RetryExpr.isUsable()) { 851 Diag(OpLoc, diag::err_no_member_overloaded_arrow) 852 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->"); 853 return RetryExpr; 854 } 855 } 856 857 Diag(R.getNameLoc(), diag::err_no_member) 858 << MemberName << DC 859 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); 860 return ExprError(); 861 } 862 863 // Diagnose lookups that find only declarations from a non-base 864 // type. This is possible for either qualified lookups (which may 865 // have been qualified with an unrelated type) or implicit member 866 // expressions (which were found with unqualified lookup and thus 867 // may have come from an enclosing scope). Note that it's okay for 868 // lookup to find declarations from a non-base type as long as those 869 // aren't the ones picked by overload resolution. 870 if ((SS.isSet() || !BaseExpr || 871 (isa<CXXThisExpr>(BaseExpr) && 872 cast<CXXThisExpr>(BaseExpr)->isImplicit())) && 873 !SuppressQualifierCheck && 874 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) 875 return ExprError(); 876 877 // Construct an unresolved result if we in fact got an unresolved 878 // result. 879 if (R.isOverloadedResult() || R.isUnresolvableResult()) { 880 // Suppress any lookup-related diagnostics; we'll do these when we 881 // pick a member. 882 R.suppressDiagnostics(); 883 884 UnresolvedMemberExpr *MemExpr 885 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(), 886 BaseExpr, BaseExprType, 887 IsArrow, OpLoc, 888 SS.getWithLocInContext(Context), 889 TemplateKWLoc, MemberNameInfo, 890 TemplateArgs, R.begin(), R.end()); 891 892 return Owned(MemExpr); 893 } 894 895 assert(R.isSingleResult()); 896 DeclAccessPair FoundDecl = R.begin().getPair(); 897 NamedDecl *MemberDecl = R.getFoundDecl(); 898 899 // FIXME: diagnose the presence of template arguments now. 900 901 // If the decl being referenced had an error, return an error for this 902 // sub-expr without emitting another error, in order to avoid cascading 903 // error cases. 904 if (MemberDecl->isInvalidDecl()) 905 return ExprError(); 906 907 // Handle the implicit-member-access case. 908 if (!BaseExpr) { 909 // If this is not an instance member, convert to a non-member access. 910 if (!MemberDecl->isCXXInstanceMember()) 911 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl); 912 913 SourceLocation Loc = R.getNameLoc(); 914 if (SS.getRange().isValid()) 915 Loc = SS.getRange().getBegin(); 916 CheckCXXThisCapture(Loc); 917 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true); 918 } 919 920 bool ShouldCheckUse = true; 921 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) { 922 // Don't diagnose the use of a virtual member function unless it's 923 // explicitly qualified. 924 if (MD->isVirtual() && !SS.isSet()) 925 ShouldCheckUse = false; 926 } 927 928 // Check the use of this member. 929 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) { 930 Owned(BaseExpr); 931 return ExprError(); 932 } 933 934 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) 935 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, 936 SS, FD, FoundDecl, MemberNameInfo); 937 938 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl)) 939 // We may have found a field within an anonymous union or struct 940 // (C++ [class.union]). 941 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD, 942 BaseExpr, OpLoc); 943 944 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 945 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, 946 TemplateKWLoc, Var, FoundDecl, MemberNameInfo, 947 Var->getType().getNonReferenceType(), 948 VK_LValue, OK_Ordinary)); 949 } 950 951 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) { 952 ExprValueKind valueKind; 953 QualType type; 954 if (MemberFn->isInstance()) { 955 valueKind = VK_RValue; 956 type = Context.BoundMemberTy; 957 } else { 958 valueKind = VK_LValue; 959 type = MemberFn->getType(); 960 } 961 962 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, 963 TemplateKWLoc, MemberFn, FoundDecl, 964 MemberNameInfo, type, valueKind, 965 OK_Ordinary)); 966 } 967 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?"); 968 969 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 970 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, 971 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo, 972 Enum->getType(), VK_RValue, OK_Ordinary)); 973 } 974 975 Owned(BaseExpr); 976 977 // We found something that we didn't expect. Complain. 978 if (isa<TypeDecl>(MemberDecl)) 979 Diag(MemberLoc, diag::err_typecheck_member_reference_type) 980 << MemberName << BaseType << int(IsArrow); 981 else 982 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown) 983 << MemberName << BaseType << int(IsArrow); 984 985 Diag(MemberDecl->getLocation(), diag::note_member_declared_here) 986 << MemberName; 987 R.suppressDiagnostics(); 988 return ExprError(); 989 } 990 991 /// Given that normal member access failed on the given expression, 992 /// and given that the expression's type involves builtin-id or 993 /// builtin-Class, decide whether substituting in the redefinition 994 /// types would be profitable. The redefinition type is whatever 995 /// this translation unit tried to typedef to id/Class; we store 996 /// it to the side and then re-use it in places like this. 997 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) { 998 const ObjCObjectPointerType *opty 999 = base.get()->getType()->getAs<ObjCObjectPointerType>(); 1000 if (!opty) return false; 1001 1002 const ObjCObjectType *ty = opty->getObjectType(); 1003 1004 QualType redef; 1005 if (ty->isObjCId()) { 1006 redef = S.Context.getObjCIdRedefinitionType(); 1007 } else if (ty->isObjCClass()) { 1008 redef = S.Context.getObjCClassRedefinitionType(); 1009 } else { 1010 return false; 1011 } 1012 1013 // Do the substitution as long as the redefinition type isn't just a 1014 // possibly-qualified pointer to builtin-id or builtin-Class again. 1015 opty = redef->getAs<ObjCObjectPointerType>(); 1016 if (opty && !opty->getObjectType()->getInterface()) 1017 return false; 1018 1019 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast); 1020 return true; 1021 } 1022 1023 static bool isRecordType(QualType T) { 1024 return T->isRecordType(); 1025 } 1026 static bool isPointerToRecordType(QualType T) { 1027 if (const PointerType *PT = T->getAs<PointerType>()) 1028 return PT->getPointeeType()->isRecordType(); 1029 return false; 1030 } 1031 1032 /// Perform conversions on the LHS of a member access expression. 1033 ExprResult 1034 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) { 1035 if (IsArrow && !Base->getType()->isFunctionType()) 1036 return DefaultFunctionArrayLvalueConversion(Base); 1037 1038 return CheckPlaceholderExpr(Base); 1039 } 1040 1041 /// Look up the given member of the given non-type-dependent 1042 /// expression. This can return in one of two ways: 1043 /// * If it returns a sentinel null-but-valid result, the caller will 1044 /// assume that lookup was performed and the results written into 1045 /// the provided structure. It will take over from there. 1046 /// * Otherwise, the returned expression will be produced in place of 1047 /// an ordinary member expression. 1048 /// 1049 /// The ObjCImpDecl bit is a gross hack that will need to be properly 1050 /// fixed for ObjC++. 1051 ExprResult 1052 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr, 1053 bool &IsArrow, SourceLocation OpLoc, 1054 CXXScopeSpec &SS, 1055 Decl *ObjCImpDecl, bool HasTemplateArgs) { 1056 assert(BaseExpr.get() && "no base expression"); 1057 1058 // Perform default conversions. 1059 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow); 1060 if (BaseExpr.isInvalid()) 1061 return ExprError(); 1062 1063 QualType BaseType = BaseExpr.get()->getType(); 1064 assert(!BaseType->isDependentType()); 1065 1066 DeclarationName MemberName = R.getLookupName(); 1067 SourceLocation MemberLoc = R.getNameLoc(); 1068 1069 // For later type-checking purposes, turn arrow accesses into dot 1070 // accesses. The only access type we support that doesn't follow 1071 // the C equivalence "a->b === (*a).b" is ObjC property accesses, 1072 // and those never use arrows, so this is unaffected. 1073 if (IsArrow) { 1074 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 1075 BaseType = Ptr->getPointeeType(); 1076 else if (const ObjCObjectPointerType *Ptr 1077 = BaseType->getAs<ObjCObjectPointerType>()) 1078 BaseType = Ptr->getPointeeType(); 1079 else if (BaseType->isRecordType()) { 1080 // Recover from arrow accesses to records, e.g.: 1081 // struct MyRecord foo; 1082 // foo->bar 1083 // This is actually well-formed in C++ if MyRecord has an 1084 // overloaded operator->, but that should have been dealt with 1085 // by now. 1086 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 1087 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() 1088 << FixItHint::CreateReplacement(OpLoc, "."); 1089 IsArrow = false; 1090 } else if (BaseType->isFunctionType()) { 1091 goto fail; 1092 } else { 1093 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 1094 << BaseType << BaseExpr.get()->getSourceRange(); 1095 return ExprError(); 1096 } 1097 } 1098 1099 // Handle field access to simple records. 1100 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 1101 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(), 1102 RTy, OpLoc, SS, HasTemplateArgs)) 1103 return ExprError(); 1104 1105 // Returning valid-but-null is how we indicate to the caller that 1106 // the lookup result was filled in. 1107 return Owned((Expr*) 0); 1108 } 1109 1110 // Handle ivar access to Objective-C objects. 1111 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) { 1112 if (!SS.isEmpty() && !SS.isInvalid()) { 1113 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access) 1114 << 1 << SS.getScopeRep() 1115 << FixItHint::CreateRemoval(SS.getRange()); 1116 SS.clear(); 1117 } 1118 1119 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1120 1121 // There are three cases for the base type: 1122 // - builtin id (qualified or unqualified) 1123 // - builtin Class (qualified or unqualified) 1124 // - an interface 1125 ObjCInterfaceDecl *IDecl = OTy->getInterface(); 1126 if (!IDecl) { 1127 if (getLangOpts().ObjCAutoRefCount && 1128 (OTy->isObjCId() || OTy->isObjCClass())) 1129 goto fail; 1130 // There's an implicit 'isa' ivar on all objects. 1131 // But we only actually find it this way on objects of type 'id', 1132 // apparently. 1133 if (OTy->isObjCId() && Member->isStr("isa")) { 1134 Diag(MemberLoc, diag::warn_objc_isa_use); 1135 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc, 1136 Context.getObjCClassType())); 1137 } 1138 1139 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1140 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1141 ObjCImpDecl, HasTemplateArgs); 1142 goto fail; 1143 } 1144 else if (Member && Member->isStr("isa")) { 1145 // If an ivar is (1) the first ivar in a root class and (2) named `isa`, 1146 // then issue the same deprecated warning that id->isa gets. 1147 ObjCInterfaceDecl *ClassDeclared = 0; 1148 if (ObjCIvarDecl *IV = 1149 IDecl->lookupInstanceVariable(Member, ClassDeclared)) { 1150 if (!ClassDeclared->getSuperClass() 1151 && (*ClassDeclared->ivar_begin()) == IV) { 1152 Diag(MemberLoc, diag::warn_objc_isa_use); 1153 Diag(IV->getLocation(), diag::note_ivar_decl); 1154 } 1155 } 1156 } 1157 1158 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag, 1159 BaseExpr.get())) 1160 return ExprError(); 1161 1162 ObjCInterfaceDecl *ClassDeclared = 0; 1163 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 1164 1165 if (!IV) { 1166 // Attempt to correct for typos in ivar names. 1167 DeclFilterCCC<ObjCIvarDecl> Validator; 1168 Validator.IsObjCIvarLookup = IsArrow; 1169 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 1170 LookupMemberName, NULL, NULL, 1171 Validator, IDecl)) { 1172 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>(); 1173 Diag(R.getNameLoc(), 1174 diag::err_typecheck_member_reference_ivar_suggest) 1175 << IDecl->getDeclName() << MemberName << IV->getDeclName() 1176 << FixItHint::CreateReplacement(R.getNameLoc(), 1177 IV->getNameAsString()); 1178 Diag(IV->getLocation(), diag::note_previous_decl) 1179 << IV->getDeclName(); 1180 1181 // Figure out the class that declares the ivar. 1182 assert(!ClassDeclared); 1183 Decl *D = cast<Decl>(IV->getDeclContext()); 1184 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D)) 1185 D = CAT->getClassInterface(); 1186 ClassDeclared = cast<ObjCInterfaceDecl>(D); 1187 } else { 1188 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) { 1189 Diag(MemberLoc, 1190 diag::err_property_found_suggest) 1191 << Member << BaseExpr.get()->getType() 1192 << FixItHint::CreateReplacement(OpLoc, "."); 1193 return ExprError(); 1194 } 1195 1196 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 1197 << IDecl->getDeclName() << MemberName 1198 << BaseExpr.get()->getSourceRange(); 1199 return ExprError(); 1200 } 1201 } 1202 1203 assert(ClassDeclared); 1204 1205 // If the decl being referenced had an error, return an error for this 1206 // sub-expr without emitting another error, in order to avoid cascading 1207 // error cases. 1208 if (IV->isInvalidDecl()) 1209 return ExprError(); 1210 1211 // Check whether we can reference this field. 1212 if (DiagnoseUseOfDecl(IV, MemberLoc)) 1213 return ExprError(); 1214 if (IV->getAccessControl() != ObjCIvarDecl::Public && 1215 IV->getAccessControl() != ObjCIvarDecl::Package) { 1216 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 1217 if (ObjCMethodDecl *MD = getCurMethodDecl()) 1218 ClassOfMethodDecl = MD->getClassInterface(); 1219 else if (ObjCImpDecl && getCurFunctionDecl()) { 1220 // Case of a c-function declared inside an objc implementation. 1221 // FIXME: For a c-style function nested inside an objc implementation 1222 // class, there is no implementation context available, so we pass 1223 // down the context as argument to this routine. Ideally, this context 1224 // need be passed down in the AST node and somehow calculated from the 1225 // AST for a function decl. 1226 if (ObjCImplementationDecl *IMPD = 1227 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl)) 1228 ClassOfMethodDecl = IMPD->getClassInterface(); 1229 else if (ObjCCategoryImplDecl* CatImplClass = 1230 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl)) 1231 ClassOfMethodDecl = CatImplClass->getClassInterface(); 1232 } 1233 if (!getLangOpts().DebuggerSupport) { 1234 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 1235 if (!declaresSameEntity(ClassDeclared, IDecl) || 1236 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared)) 1237 Diag(MemberLoc, diag::error_private_ivar_access) 1238 << IV->getDeclName(); 1239 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 1240 // @protected 1241 Diag(MemberLoc, diag::error_protected_ivar_access) 1242 << IV->getDeclName(); 1243 } 1244 } 1245 bool warn = true; 1246 if (getLangOpts().ObjCAutoRefCount) { 1247 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts(); 1248 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp)) 1249 if (UO->getOpcode() == UO_Deref) 1250 BaseExp = UO->getSubExpr()->IgnoreParenCasts(); 1251 1252 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp)) 1253 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 1254 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access); 1255 warn = false; 1256 } 1257 } 1258 if (warn) { 1259 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1260 ObjCMethodFamily MF = MD->getMethodFamily(); 1261 warn = (MF != OMF_init && MF != OMF_dealloc && 1262 MF != OMF_finalize && 1263 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV)); 1264 } 1265 if (warn) 1266 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName(); 1267 } 1268 1269 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 1270 MemberLoc, 1271 BaseExpr.take(), 1272 IsArrow); 1273 1274 if (getLangOpts().ObjCAutoRefCount) { 1275 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 1276 DiagnosticsEngine::Level Level = 1277 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1278 MemberLoc); 1279 if (Level != DiagnosticsEngine::Ignored) 1280 getCurFunction()->recordUseOfWeak(Result); 1281 } 1282 } 1283 1284 return Owned(Result); 1285 } 1286 1287 // Objective-C property access. 1288 const ObjCObjectPointerType *OPT; 1289 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) { 1290 if (!SS.isEmpty() && !SS.isInvalid()) { 1291 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access) 1292 << 0 << SS.getScopeRep() 1293 << FixItHint::CreateRemoval(SS.getRange()); 1294 SS.clear(); 1295 } 1296 1297 // This actually uses the base as an r-value. 1298 BaseExpr = DefaultLvalueConversion(BaseExpr.take()); 1299 if (BaseExpr.isInvalid()) 1300 return ExprError(); 1301 1302 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType())); 1303 1304 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1305 1306 const ObjCObjectType *OT = OPT->getObjectType(); 1307 1308 // id, with and without qualifiers. 1309 if (OT->isObjCId()) { 1310 // Check protocols on qualified interfaces. 1311 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1312 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) { 1313 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 1314 // Check the use of this declaration 1315 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1316 return ExprError(); 1317 1318 return Owned(new (Context) ObjCPropertyRefExpr(PD, 1319 Context.PseudoObjectTy, 1320 VK_LValue, 1321 OK_ObjCProperty, 1322 MemberLoc, 1323 BaseExpr.take())); 1324 } 1325 1326 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 1327 // Check the use of this method. 1328 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 1329 return ExprError(); 1330 Selector SetterSel = 1331 SelectorTable::constructSetterName(PP.getIdentifierTable(), 1332 PP.getSelectorTable(), Member); 1333 ObjCMethodDecl *SMD = 0; 1334 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0, 1335 SetterSel, Context)) 1336 SMD = dyn_cast<ObjCMethodDecl>(SDecl); 1337 1338 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, 1339 Context.PseudoObjectTy, 1340 VK_LValue, OK_ObjCProperty, 1341 MemberLoc, BaseExpr.take())); 1342 } 1343 } 1344 // Use of id.member can only be for a property reference. Do not 1345 // use the 'id' redefinition in this case. 1346 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1347 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1348 ObjCImpDecl, HasTemplateArgs); 1349 1350 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1351 << MemberName << BaseType); 1352 } 1353 1354 // 'Class', unqualified only. 1355 if (OT->isObjCClass()) { 1356 // Only works in a method declaration (??!). 1357 ObjCMethodDecl *MD = getCurMethodDecl(); 1358 if (!MD) { 1359 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1360 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1361 ObjCImpDecl, HasTemplateArgs); 1362 1363 goto fail; 1364 } 1365 1366 // Also must look for a getter name which uses property syntax. 1367 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1368 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 1369 ObjCMethodDecl *Getter; 1370 if ((Getter = IFace->lookupClassMethod(Sel))) { 1371 // Check the use of this method. 1372 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1373 return ExprError(); 1374 } else 1375 Getter = IFace->lookupPrivateMethod(Sel, false); 1376 // If we found a getter then this may be a valid dot-reference, we 1377 // will look for the matching setter, in case it is needed. 1378 Selector SetterSel = 1379 SelectorTable::constructSetterName(PP.getIdentifierTable(), 1380 PP.getSelectorTable(), Member); 1381 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 1382 if (!Setter) { 1383 // If this reference is in an @implementation, also check for 'private' 1384 // methods. 1385 Setter = IFace->lookupPrivateMethod(SetterSel, false); 1386 } 1387 1388 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1389 return ExprError(); 1390 1391 if (Getter || Setter) { 1392 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, 1393 Context.PseudoObjectTy, 1394 VK_LValue, OK_ObjCProperty, 1395 MemberLoc, BaseExpr.take())); 1396 } 1397 1398 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1399 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1400 ObjCImpDecl, HasTemplateArgs); 1401 1402 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1403 << MemberName << BaseType); 1404 } 1405 1406 // Normal property access. 1407 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, 1408 MemberName, MemberLoc, 1409 SourceLocation(), QualType(), false); 1410 } 1411 1412 // Handle 'field access' to vectors, such as 'V.xx'. 1413 if (BaseType->isExtVectorType()) { 1414 // FIXME: this expr should store IsArrow. 1415 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1416 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind()); 1417 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc, 1418 Member, MemberLoc); 1419 if (ret.isNull()) 1420 return ExprError(); 1421 1422 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(), 1423 *Member, MemberLoc)); 1424 } 1425 1426 // Adjust builtin-sel to the appropriate redefinition type if that's 1427 // not just a pointer to builtin-sel again. 1428 if (IsArrow && 1429 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) && 1430 !Context.getObjCSelRedefinitionType()->isObjCSelType()) { 1431 BaseExpr = ImpCastExprToType(BaseExpr.take(), 1432 Context.getObjCSelRedefinitionType(), 1433 CK_BitCast); 1434 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1435 ObjCImpDecl, HasTemplateArgs); 1436 } 1437 1438 // Failure cases. 1439 fail: 1440 1441 // Recover from dot accesses to pointers, e.g.: 1442 // type *foo; 1443 // foo.bar 1444 // This is actually well-formed in two cases: 1445 // - 'type' is an Objective C type 1446 // - 'bar' is a pseudo-destructor name which happens to refer to 1447 // the appropriate pointer type 1448 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 1449 if (!IsArrow && Ptr->getPointeeType()->isRecordType() && 1450 MemberName.getNameKind() != DeclarationName::CXXDestructorName) { 1451 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 1452 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() 1453 << FixItHint::CreateReplacement(OpLoc, "->"); 1454 1455 // Recurse as an -> access. 1456 IsArrow = true; 1457 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1458 ObjCImpDecl, HasTemplateArgs); 1459 } 1460 } 1461 1462 // If the user is trying to apply -> or . to a function name, it's probably 1463 // because they forgot parentheses to call that function. 1464 if (tryToRecoverWithCall(BaseExpr, 1465 PDiag(diag::err_member_reference_needs_call), 1466 /*complain*/ false, 1467 IsArrow ? &isPointerToRecordType : &isRecordType)) { 1468 if (BaseExpr.isInvalid()) 1469 return ExprError(); 1470 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take()); 1471 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1472 ObjCImpDecl, HasTemplateArgs); 1473 } 1474 1475 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union) 1476 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc; 1477 1478 return ExprError(); 1479 } 1480 1481 /// The main callback when the parser finds something like 1482 /// expression . [nested-name-specifier] identifier 1483 /// expression -> [nested-name-specifier] identifier 1484 /// where 'identifier' encompasses a fairly broad spectrum of 1485 /// possibilities, including destructor and operator references. 1486 /// 1487 /// \param OpKind either tok::arrow or tok::period 1488 /// \param HasTrailingLParen whether the next token is '(', which 1489 /// is used to diagnose mis-uses of special members that can 1490 /// only be called 1491 /// \param ObjCImpDecl the current Objective-C \@implementation 1492 /// decl; this is an ugly hack around the fact that Objective-C 1493 /// \@implementations aren't properly put in the context chain 1494 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, 1495 SourceLocation OpLoc, 1496 tok::TokenKind OpKind, 1497 CXXScopeSpec &SS, 1498 SourceLocation TemplateKWLoc, 1499 UnqualifiedId &Id, 1500 Decl *ObjCImpDecl, 1501 bool HasTrailingLParen) { 1502 if (SS.isSet() && SS.isInvalid()) 1503 return ExprError(); 1504 1505 // Warn about the explicit constructor calls Microsoft extension. 1506 if (getLangOpts().MicrosoftExt && 1507 Id.getKind() == UnqualifiedId::IK_ConstructorName) 1508 Diag(Id.getSourceRange().getBegin(), 1509 diag::ext_ms_explicit_constructor_call); 1510 1511 TemplateArgumentListInfo TemplateArgsBuffer; 1512 1513 // Decompose the name into its component parts. 1514 DeclarationNameInfo NameInfo; 1515 const TemplateArgumentListInfo *TemplateArgs; 1516 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, 1517 NameInfo, TemplateArgs); 1518 1519 DeclarationName Name = NameInfo.getName(); 1520 bool IsArrow = (OpKind == tok::arrow); 1521 1522 NamedDecl *FirstQualifierInScope 1523 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S, 1524 static_cast<NestedNameSpecifier*>(SS.getScopeRep()))); 1525 1526 // This is a postfix expression, so get rid of ParenListExprs. 1527 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 1528 if (Result.isInvalid()) return ExprError(); 1529 Base = Result.take(); 1530 1531 if (Base->getType()->isDependentType() || Name.isDependentName() || 1532 isDependentScopeSpecifier(SS)) { 1533 Result = ActOnDependentMemberExpr(Base, Base->getType(), 1534 IsArrow, OpLoc, 1535 SS, TemplateKWLoc, FirstQualifierInScope, 1536 NameInfo, TemplateArgs); 1537 } else { 1538 LookupResult R(*this, NameInfo, LookupMemberName); 1539 ExprResult BaseResult = Owned(Base); 1540 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc, 1541 SS, ObjCImpDecl, TemplateArgs != 0); 1542 if (BaseResult.isInvalid()) 1543 return ExprError(); 1544 Base = BaseResult.take(); 1545 1546 if (Result.isInvalid()) { 1547 Owned(Base); 1548 return ExprError(); 1549 } 1550 1551 if (Result.get()) { 1552 // The only way a reference to a destructor can be used is to 1553 // immediately call it, which falls into this case. If the 1554 // next token is not a '(', produce a diagnostic and build the 1555 // call now. 1556 if (!HasTrailingLParen && 1557 Id.getKind() == UnqualifiedId::IK_DestructorName) 1558 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get()); 1559 1560 return Result; 1561 } 1562 1563 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen}; 1564 Result = BuildMemberReferenceExpr(Base, Base->getType(), 1565 OpLoc, IsArrow, SS, TemplateKWLoc, 1566 FirstQualifierInScope, R, TemplateArgs, 1567 false, &ExtraArgs); 1568 } 1569 1570 return Result; 1571 } 1572 1573 static ExprResult 1574 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 1575 const CXXScopeSpec &SS, FieldDecl *Field, 1576 DeclAccessPair FoundDecl, 1577 const DeclarationNameInfo &MemberNameInfo) { 1578 // x.a is an l-value if 'a' has a reference type. Otherwise: 1579 // x.a is an l-value/x-value/pr-value if the base is (and note 1580 // that *x is always an l-value), except that if the base isn't 1581 // an ordinary object then we must have an rvalue. 1582 ExprValueKind VK = VK_LValue; 1583 ExprObjectKind OK = OK_Ordinary; 1584 if (!IsArrow) { 1585 if (BaseExpr->getObjectKind() == OK_Ordinary) 1586 VK = BaseExpr->getValueKind(); 1587 else 1588 VK = VK_RValue; 1589 } 1590 if (VK != VK_RValue && Field->isBitField()) 1591 OK = OK_BitField; 1592 1593 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 1594 QualType MemberType = Field->getType(); 1595 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) { 1596 MemberType = Ref->getPointeeType(); 1597 VK = VK_LValue; 1598 } else { 1599 QualType BaseType = BaseExpr->getType(); 1600 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 1601 1602 Qualifiers BaseQuals = BaseType.getQualifiers(); 1603 1604 // GC attributes are never picked up by members. 1605 BaseQuals.removeObjCGCAttr(); 1606 1607 // CVR attributes from the base are picked up by members, 1608 // except that 'mutable' members don't pick up 'const'. 1609 if (Field->isMutable()) BaseQuals.removeConst(); 1610 1611 Qualifiers MemberQuals 1612 = S.Context.getCanonicalType(MemberType).getQualifiers(); 1613 1614 assert(!MemberQuals.hasAddressSpace()); 1615 1616 1617 Qualifiers Combined = BaseQuals + MemberQuals; 1618 if (Combined != MemberQuals) 1619 MemberType = S.Context.getQualifiedType(MemberType, Combined); 1620 } 1621 1622 S.UnusedPrivateFields.remove(Field); 1623 1624 ExprResult Base = 1625 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(), 1626 FoundDecl, Field); 1627 if (Base.isInvalid()) 1628 return ExprError(); 1629 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS, 1630 /*TemplateKWLoc=*/SourceLocation(), 1631 Field, FoundDecl, MemberNameInfo, 1632 MemberType, VK, OK)); 1633 } 1634 1635 /// Builds an implicit member access expression. The current context 1636 /// is known to be an instance method, and the given unqualified lookup 1637 /// set is known to contain only instance members, at least one of which 1638 /// is from an appropriate type. 1639 ExprResult 1640 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, 1641 SourceLocation TemplateKWLoc, 1642 LookupResult &R, 1643 const TemplateArgumentListInfo *TemplateArgs, 1644 bool IsKnownInstance) { 1645 assert(!R.empty() && !R.isAmbiguous()); 1646 1647 SourceLocation loc = R.getNameLoc(); 1648 1649 // We may have found a field within an anonymous union or struct 1650 // (C++ [class.union]). 1651 // FIXME: template-ids inside anonymous structs? 1652 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>()) 1653 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD); 1654 1655 // If this is known to be an instance access, go ahead and build an 1656 // implicit 'this' expression now. 1657 // 'this' expression now. 1658 QualType ThisTy = getCurrentThisType(); 1659 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'"); 1660 1661 Expr *baseExpr = 0; // null signifies implicit access 1662 if (IsKnownInstance) { 1663 SourceLocation Loc = R.getNameLoc(); 1664 if (SS.getRange().isValid()) 1665 Loc = SS.getRange().getBegin(); 1666 CheckCXXThisCapture(Loc); 1667 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true); 1668 } 1669 1670 return BuildMemberReferenceExpr(baseExpr, ThisTy, 1671 /*OpLoc*/ SourceLocation(), 1672 /*IsArrow*/ true, 1673 SS, TemplateKWLoc, 1674 /*FirstQualifierInScope*/ 0, 1675 R, TemplateArgs); 1676 } 1677