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