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, DC); 631 R.clear(); 632 if (Corrected.isResolved() && !Corrected.isKeyword()) { 633 R.setLookupName(Corrected.getCorrection()); 634 for (TypoCorrection::decl_iterator DI = Corrected.begin(), 635 DIEnd = Corrected.end(); 636 DI != DIEnd; ++DI) { 637 R.addDecl(*DI); 638 } 639 R.resolveKind(); 640 641 // If we're typo-correcting to an overloaded name, we don't yet have enough 642 // information to do overload resolution, so we don't know which previous 643 // declaration to point to. 644 if (Corrected.isOverloaded()) 645 Corrected.setCorrectionDecl(0); 646 bool DroppedSpecifier = 647 Corrected.WillReplaceSpecifier() && 648 Name.getAsString() == Corrected.getAsString(SemaRef.getLangOpts()); 649 SemaRef.diagnoseTypo(Corrected, 650 SemaRef.PDiag(diag::err_no_member_suggest) 651 << Name << DC << DroppedSpecifier << SS.getRange()); 652 } 653 654 return false; 655 } 656 657 ExprResult 658 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType, 659 SourceLocation OpLoc, bool IsArrow, 660 CXXScopeSpec &SS, 661 SourceLocation TemplateKWLoc, 662 NamedDecl *FirstQualifierInScope, 663 const DeclarationNameInfo &NameInfo, 664 const TemplateArgumentListInfo *TemplateArgs) { 665 if (BaseType->isDependentType() || 666 (SS.isSet() && isDependentScopeSpecifier(SS))) 667 return ActOnDependentMemberExpr(Base, BaseType, 668 IsArrow, OpLoc, 669 SS, TemplateKWLoc, FirstQualifierInScope, 670 NameInfo, TemplateArgs); 671 672 LookupResult R(*this, NameInfo, LookupMemberName); 673 674 // Implicit member accesses. 675 if (!Base) { 676 QualType RecordTy = BaseType; 677 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType(); 678 if (LookupMemberExprInRecord(*this, R, SourceRange(), 679 RecordTy->getAs<RecordType>(), 680 OpLoc, SS, TemplateArgs != 0)) 681 return ExprError(); 682 683 // Explicit member accesses. 684 } else { 685 ExprResult BaseResult = Owned(Base); 686 ExprResult Result = 687 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc, 688 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0); 689 690 if (BaseResult.isInvalid()) 691 return ExprError(); 692 Base = BaseResult.take(); 693 694 if (Result.isInvalid()) { 695 Owned(Base); 696 return ExprError(); 697 } 698 699 if (Result.get()) 700 return Result; 701 702 // LookupMemberExpr can modify Base, and thus change BaseType 703 BaseType = Base->getType(); 704 } 705 706 return BuildMemberReferenceExpr(Base, BaseType, 707 OpLoc, IsArrow, SS, TemplateKWLoc, 708 FirstQualifierInScope, R, TemplateArgs); 709 } 710 711 static ExprResult 712 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 713 const CXXScopeSpec &SS, FieldDecl *Field, 714 DeclAccessPair FoundDecl, 715 const DeclarationNameInfo &MemberNameInfo); 716 717 ExprResult 718 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS, 719 SourceLocation loc, 720 IndirectFieldDecl *indirectField, 721 DeclAccessPair foundDecl, 722 Expr *baseObjectExpr, 723 SourceLocation opLoc) { 724 // First, build the expression that refers to the base object. 725 726 bool baseObjectIsPointer = false; 727 Qualifiers baseQuals; 728 729 // Case 1: the base of the indirect field is not a field. 730 VarDecl *baseVariable = indirectField->getVarDecl(); 731 CXXScopeSpec EmptySS; 732 if (baseVariable) { 733 assert(baseVariable->getType()->isRecordType()); 734 735 // In principle we could have a member access expression that 736 // accesses an anonymous struct/union that's a static member of 737 // the base object's class. However, under the current standard, 738 // static data members cannot be anonymous structs or unions. 739 // Supporting this is as easy as building a MemberExpr here. 740 assert(!baseObjectExpr && "anonymous struct/union is static data member?"); 741 742 DeclarationNameInfo baseNameInfo(DeclarationName(), loc); 743 744 ExprResult result 745 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable); 746 if (result.isInvalid()) return ExprError(); 747 748 baseObjectExpr = result.take(); 749 baseObjectIsPointer = false; 750 baseQuals = baseObjectExpr->getType().getQualifiers(); 751 752 // Case 2: the base of the indirect field is a field and the user 753 // wrote a member expression. 754 } else if (baseObjectExpr) { 755 // The caller provided the base object expression. Determine 756 // whether its a pointer and whether it adds any qualifiers to the 757 // anonymous struct/union fields we're looking into. 758 QualType objectType = baseObjectExpr->getType(); 759 760 if (const PointerType *ptr = objectType->getAs<PointerType>()) { 761 baseObjectIsPointer = true; 762 objectType = ptr->getPointeeType(); 763 } else { 764 baseObjectIsPointer = false; 765 } 766 baseQuals = objectType.getQualifiers(); 767 768 // Case 3: the base of the indirect field is a field and we should 769 // build an implicit member access. 770 } else { 771 // We've found a member of an anonymous struct/union that is 772 // inside a non-anonymous struct/union, so in a well-formed 773 // program our base object expression is "this". 774 QualType ThisTy = getCurrentThisType(); 775 if (ThisTy.isNull()) { 776 Diag(loc, diag::err_invalid_member_use_in_static_method) 777 << indirectField->getDeclName(); 778 return ExprError(); 779 } 780 781 // Our base object expression is "this". 782 CheckCXXThisCapture(loc); 783 baseObjectExpr 784 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true); 785 baseObjectIsPointer = true; 786 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers(); 787 } 788 789 // Build the implicit member references to the field of the 790 // anonymous struct/union. 791 Expr *result = baseObjectExpr; 792 IndirectFieldDecl::chain_iterator 793 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end(); 794 795 // Build the first member access in the chain with full information. 796 if (!baseVariable) { 797 FieldDecl *field = cast<FieldDecl>(*FI); 798 799 // Make a nameInfo that properly uses the anonymous name. 800 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 801 802 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer, 803 EmptySS, field, foundDecl, 804 memberNameInfo).take(); 805 if (!result) 806 return ExprError(); 807 808 // FIXME: check qualified member access 809 } 810 811 // In all cases, we should now skip the first declaration in the chain. 812 ++FI; 813 814 while (FI != FEnd) { 815 FieldDecl *field = cast<FieldDecl>(*FI++); 816 817 // FIXME: these are somewhat meaningless 818 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc); 819 DeclAccessPair fakeFoundDecl = 820 DeclAccessPair::make(field, field->getAccess()); 821 822 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false, 823 (FI == FEnd? SS : EmptySS), field, 824 fakeFoundDecl, memberNameInfo).take(); 825 } 826 827 return Owned(result); 828 } 829 830 static ExprResult 831 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 832 const CXXScopeSpec &SS, 833 MSPropertyDecl *PD, 834 const DeclarationNameInfo &NameInfo) { 835 // Property names are always simple identifiers and therefore never 836 // require any interesting additional storage. 837 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow, 838 S.Context.PseudoObjectTy, VK_LValue, 839 SS.getWithLocInContext(S.Context), 840 NameInfo.getLoc()); 841 } 842 843 /// \brief Build a MemberExpr AST node. 844 static MemberExpr *BuildMemberExpr(Sema &SemaRef, 845 ASTContext &C, Expr *Base, bool isArrow, 846 const CXXScopeSpec &SS, 847 SourceLocation TemplateKWLoc, 848 ValueDecl *Member, 849 DeclAccessPair FoundDecl, 850 const DeclarationNameInfo &MemberNameInfo, 851 QualType Ty, 852 ExprValueKind VK, ExprObjectKind OK, 853 const TemplateArgumentListInfo *TemplateArgs = 0) { 854 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue"); 855 MemberExpr *E = 856 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C), 857 TemplateKWLoc, Member, FoundDecl, MemberNameInfo, 858 TemplateArgs, Ty, VK, OK); 859 SemaRef.MarkMemberReferenced(E); 860 return E; 861 } 862 863 ExprResult 864 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType, 865 SourceLocation OpLoc, bool IsArrow, 866 const CXXScopeSpec &SS, 867 SourceLocation TemplateKWLoc, 868 NamedDecl *FirstQualifierInScope, 869 LookupResult &R, 870 const TemplateArgumentListInfo *TemplateArgs, 871 bool SuppressQualifierCheck, 872 ActOnMemberAccessExtraArgs *ExtraArgs) { 873 QualType BaseType = BaseExprType; 874 if (IsArrow) { 875 assert(BaseType->isPointerType()); 876 BaseType = BaseType->castAs<PointerType>()->getPointeeType(); 877 } 878 R.setBaseObjectType(BaseType); 879 880 LambdaScopeInfo *const CurLSI = getCurLambda(); 881 // If this is an implicit member reference and the overloaded 882 // name refers to both static and non-static member functions 883 // (i.e. BaseExpr is null) and if we are currently processing a lambda, 884 // check if we should/can capture 'this'... 885 // Keep this example in mind: 886 // struct X { 887 // void f(int) { } 888 // static void f(double) { } 889 // 890 // int g() { 891 // auto L = [=](auto a) { 892 // return [](int i) { 893 // return [=](auto b) { 894 // f(b); 895 // //f(decltype(a){}); 896 // }; 897 // }; 898 // }; 899 // auto M = L(0.0); 900 // auto N = M(3); 901 // N(5.32); // OK, must not error. 902 // return 0; 903 // } 904 // }; 905 // 906 if (!BaseExpr && CurLSI) { 907 SourceLocation Loc = R.getNameLoc(); 908 if (SS.getRange().isValid()) 909 Loc = SS.getRange().getBegin(); 910 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent(); 911 // If the enclosing function is not dependent, then this lambda is 912 // capture ready, so if we can capture this, do so. 913 if (!EnclosingFunctionCtx->isDependentContext()) { 914 // If the current lambda and all enclosing lambdas can capture 'this' - 915 // then go ahead and capture 'this' (since our unresolved overload set 916 // contains both static and non-static member functions). 917 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false)) 918 CheckCXXThisCapture(Loc); 919 } else if (CurContext->isDependentContext()) { 920 // ... since this is an implicit member reference, that might potentially 921 // involve a 'this' capture, mark 'this' for potential capture in 922 // enclosing lambdas. 923 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None) 924 CurLSI->addPotentialThisCapture(Loc); 925 } 926 } 927 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo(); 928 DeclarationName MemberName = MemberNameInfo.getName(); 929 SourceLocation MemberLoc = MemberNameInfo.getLoc(); 930 931 if (R.isAmbiguous()) 932 return ExprError(); 933 934 if (R.empty()) { 935 // Rederive where we looked up. 936 DeclContext *DC = (SS.isSet() 937 ? computeDeclContext(SS, false) 938 : BaseType->getAs<RecordType>()->getDecl()); 939 940 if (ExtraArgs) { 941 ExprResult RetryExpr; 942 if (!IsArrow && BaseExpr) { 943 SFINAETrap Trap(*this, true); 944 ParsedType ObjectType; 945 bool MayBePseudoDestructor = false; 946 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr, 947 OpLoc, tok::arrow, ObjectType, 948 MayBePseudoDestructor); 949 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) { 950 CXXScopeSpec TempSS(SS); 951 RetryExpr = ActOnMemberAccessExpr( 952 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS, 953 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl, 954 ExtraArgs->HasTrailingLParen); 955 } 956 if (Trap.hasErrorOccurred()) 957 RetryExpr = ExprError(); 958 } 959 if (RetryExpr.isUsable()) { 960 Diag(OpLoc, diag::err_no_member_overloaded_arrow) 961 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->"); 962 return RetryExpr; 963 } 964 } 965 966 Diag(R.getNameLoc(), diag::err_no_member) 967 << MemberName << DC 968 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange()); 969 return ExprError(); 970 } 971 972 // Diagnose lookups that find only declarations from a non-base 973 // type. This is possible for either qualified lookups (which may 974 // have been qualified with an unrelated type) or implicit member 975 // expressions (which were found with unqualified lookup and thus 976 // may have come from an enclosing scope). Note that it's okay for 977 // lookup to find declarations from a non-base type as long as those 978 // aren't the ones picked by overload resolution. 979 if ((SS.isSet() || !BaseExpr || 980 (isa<CXXThisExpr>(BaseExpr) && 981 cast<CXXThisExpr>(BaseExpr)->isImplicit())) && 982 !SuppressQualifierCheck && 983 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R)) 984 return ExprError(); 985 986 // Construct an unresolved result if we in fact got an unresolved 987 // result. 988 if (R.isOverloadedResult() || R.isUnresolvableResult()) { 989 // Suppress any lookup-related diagnostics; we'll do these when we 990 // pick a member. 991 R.suppressDiagnostics(); 992 993 UnresolvedMemberExpr *MemExpr 994 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(), 995 BaseExpr, BaseExprType, 996 IsArrow, OpLoc, 997 SS.getWithLocInContext(Context), 998 TemplateKWLoc, MemberNameInfo, 999 TemplateArgs, R.begin(), R.end()); 1000 1001 return Owned(MemExpr); 1002 } 1003 1004 assert(R.isSingleResult()); 1005 DeclAccessPair FoundDecl = R.begin().getPair(); 1006 NamedDecl *MemberDecl = R.getFoundDecl(); 1007 1008 // FIXME: diagnose the presence of template arguments now. 1009 1010 // If the decl being referenced had an error, return an error for this 1011 // sub-expr without emitting another error, in order to avoid cascading 1012 // error cases. 1013 if (MemberDecl->isInvalidDecl()) 1014 return ExprError(); 1015 1016 // Handle the implicit-member-access case. 1017 if (!BaseExpr) { 1018 // If this is not an instance member, convert to a non-member access. 1019 if (!MemberDecl->isCXXInstanceMember()) 1020 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl); 1021 1022 SourceLocation Loc = R.getNameLoc(); 1023 if (SS.getRange().isValid()) 1024 Loc = SS.getRange().getBegin(); 1025 CheckCXXThisCapture(Loc); 1026 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true); 1027 } 1028 1029 bool ShouldCheckUse = true; 1030 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) { 1031 // Don't diagnose the use of a virtual member function unless it's 1032 // explicitly qualified. 1033 if (MD->isVirtual() && !SS.isSet()) 1034 ShouldCheckUse = false; 1035 } 1036 1037 // Check the use of this member. 1038 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) { 1039 Owned(BaseExpr); 1040 return ExprError(); 1041 } 1042 1043 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl)) 1044 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, 1045 SS, FD, FoundDecl, MemberNameInfo); 1046 1047 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl)) 1048 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD, 1049 MemberNameInfo); 1050 1051 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl)) 1052 // We may have found a field within an anonymous union or struct 1053 // (C++ [class.union]). 1054 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD, 1055 FoundDecl, BaseExpr, 1056 OpLoc); 1057 1058 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) { 1059 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, 1060 TemplateKWLoc, Var, FoundDecl, MemberNameInfo, 1061 Var->getType().getNonReferenceType(), 1062 VK_LValue, OK_Ordinary)); 1063 } 1064 1065 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) { 1066 ExprValueKind valueKind; 1067 QualType type; 1068 if (MemberFn->isInstance()) { 1069 valueKind = VK_RValue; 1070 type = Context.BoundMemberTy; 1071 } else { 1072 valueKind = VK_LValue; 1073 type = MemberFn->getType(); 1074 } 1075 1076 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, 1077 TemplateKWLoc, MemberFn, FoundDecl, 1078 MemberNameInfo, type, valueKind, 1079 OK_Ordinary)); 1080 } 1081 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?"); 1082 1083 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) { 1084 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, 1085 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo, 1086 Enum->getType(), VK_RValue, OK_Ordinary)); 1087 } 1088 1089 Owned(BaseExpr); 1090 1091 // We found something that we didn't expect. Complain. 1092 if (isa<TypeDecl>(MemberDecl)) 1093 Diag(MemberLoc, diag::err_typecheck_member_reference_type) 1094 << MemberName << BaseType << int(IsArrow); 1095 else 1096 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown) 1097 << MemberName << BaseType << int(IsArrow); 1098 1099 Diag(MemberDecl->getLocation(), diag::note_member_declared_here) 1100 << MemberName; 1101 R.suppressDiagnostics(); 1102 return ExprError(); 1103 } 1104 1105 /// Given that normal member access failed on the given expression, 1106 /// and given that the expression's type involves builtin-id or 1107 /// builtin-Class, decide whether substituting in the redefinition 1108 /// types would be profitable. The redefinition type is whatever 1109 /// this translation unit tried to typedef to id/Class; we store 1110 /// it to the side and then re-use it in places like this. 1111 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) { 1112 const ObjCObjectPointerType *opty 1113 = base.get()->getType()->getAs<ObjCObjectPointerType>(); 1114 if (!opty) return false; 1115 1116 const ObjCObjectType *ty = opty->getObjectType(); 1117 1118 QualType redef; 1119 if (ty->isObjCId()) { 1120 redef = S.Context.getObjCIdRedefinitionType(); 1121 } else if (ty->isObjCClass()) { 1122 redef = S.Context.getObjCClassRedefinitionType(); 1123 } else { 1124 return false; 1125 } 1126 1127 // Do the substitution as long as the redefinition type isn't just a 1128 // possibly-qualified pointer to builtin-id or builtin-Class again. 1129 opty = redef->getAs<ObjCObjectPointerType>(); 1130 if (opty && !opty->getObjectType()->getInterface()) 1131 return false; 1132 1133 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast); 1134 return true; 1135 } 1136 1137 static bool isRecordType(QualType T) { 1138 return T->isRecordType(); 1139 } 1140 static bool isPointerToRecordType(QualType T) { 1141 if (const PointerType *PT = T->getAs<PointerType>()) 1142 return PT->getPointeeType()->isRecordType(); 1143 return false; 1144 } 1145 1146 /// Perform conversions on the LHS of a member access expression. 1147 ExprResult 1148 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) { 1149 if (IsArrow && !Base->getType()->isFunctionType()) 1150 return DefaultFunctionArrayLvalueConversion(Base); 1151 1152 return CheckPlaceholderExpr(Base); 1153 } 1154 1155 /// Look up the given member of the given non-type-dependent 1156 /// expression. This can return in one of two ways: 1157 /// * If it returns a sentinel null-but-valid result, the caller will 1158 /// assume that lookup was performed and the results written into 1159 /// the provided structure. It will take over from there. 1160 /// * Otherwise, the returned expression will be produced in place of 1161 /// an ordinary member expression. 1162 /// 1163 /// The ObjCImpDecl bit is a gross hack that will need to be properly 1164 /// fixed for ObjC++. 1165 ExprResult 1166 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr, 1167 bool &IsArrow, SourceLocation OpLoc, 1168 CXXScopeSpec &SS, 1169 Decl *ObjCImpDecl, bool HasTemplateArgs) { 1170 assert(BaseExpr.get() && "no base expression"); 1171 1172 // Perform default conversions. 1173 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow); 1174 if (BaseExpr.isInvalid()) 1175 return ExprError(); 1176 1177 QualType BaseType = BaseExpr.get()->getType(); 1178 assert(!BaseType->isDependentType()); 1179 1180 DeclarationName MemberName = R.getLookupName(); 1181 SourceLocation MemberLoc = R.getNameLoc(); 1182 1183 // For later type-checking purposes, turn arrow accesses into dot 1184 // accesses. The only access type we support that doesn't follow 1185 // the C equivalence "a->b === (*a).b" is ObjC property accesses, 1186 // and those never use arrows, so this is unaffected. 1187 if (IsArrow) { 1188 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) 1189 BaseType = Ptr->getPointeeType(); 1190 else if (const ObjCObjectPointerType *Ptr 1191 = BaseType->getAs<ObjCObjectPointerType>()) 1192 BaseType = Ptr->getPointeeType(); 1193 else if (BaseType->isRecordType()) { 1194 // Recover from arrow accesses to records, e.g.: 1195 // struct MyRecord foo; 1196 // foo->bar 1197 // This is actually well-formed in C++ if MyRecord has an 1198 // overloaded operator->, but that should have been dealt with 1199 // by now--or a diagnostic message already issued if a problem 1200 // was encountered while looking for the overloaded operator->. 1201 if (!getLangOpts().CPlusPlus) { 1202 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 1203 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() 1204 << FixItHint::CreateReplacement(OpLoc, "."); 1205 } 1206 IsArrow = false; 1207 } else if (BaseType->isFunctionType()) { 1208 goto fail; 1209 } else { 1210 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow) 1211 << BaseType << BaseExpr.get()->getSourceRange(); 1212 return ExprError(); 1213 } 1214 } 1215 1216 // Handle field access to simple records. 1217 if (const RecordType *RTy = BaseType->getAs<RecordType>()) { 1218 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(), 1219 RTy, OpLoc, SS, HasTemplateArgs)) 1220 return ExprError(); 1221 1222 // Returning valid-but-null is how we indicate to the caller that 1223 // the lookup result was filled in. 1224 return Owned((Expr*) 0); 1225 } 1226 1227 // Handle ivar access to Objective-C objects. 1228 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) { 1229 if (!SS.isEmpty() && !SS.isInvalid()) { 1230 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access) 1231 << 1 << SS.getScopeRep() 1232 << FixItHint::CreateRemoval(SS.getRange()); 1233 SS.clear(); 1234 } 1235 1236 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1237 1238 // There are three cases for the base type: 1239 // - builtin id (qualified or unqualified) 1240 // - builtin Class (qualified or unqualified) 1241 // - an interface 1242 ObjCInterfaceDecl *IDecl = OTy->getInterface(); 1243 if (!IDecl) { 1244 if (getLangOpts().ObjCAutoRefCount && 1245 (OTy->isObjCId() || OTy->isObjCClass())) 1246 goto fail; 1247 // There's an implicit 'isa' ivar on all objects. 1248 // But we only actually find it this way on objects of type 'id', 1249 // apparently. 1250 if (OTy->isObjCId() && Member->isStr("isa")) 1251 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc, 1252 OpLoc, 1253 Context.getObjCClassType())); 1254 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1255 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1256 ObjCImpDecl, HasTemplateArgs); 1257 goto fail; 1258 } 1259 1260 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag, 1261 BaseExpr.get())) 1262 return ExprError(); 1263 1264 ObjCInterfaceDecl *ClassDeclared = 0; 1265 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared); 1266 1267 if (!IV) { 1268 // Attempt to correct for typos in ivar names. 1269 DeclFilterCCC<ObjCIvarDecl> Validator; 1270 Validator.IsObjCIvarLookup = IsArrow; 1271 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(), 1272 LookupMemberName, NULL, NULL, 1273 Validator, IDecl)) { 1274 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>(); 1275 diagnoseTypo(Corrected, 1276 PDiag(diag::err_typecheck_member_reference_ivar_suggest) 1277 << IDecl->getDeclName() << MemberName); 1278 1279 // Figure out the class that declares the ivar. 1280 assert(!ClassDeclared); 1281 Decl *D = cast<Decl>(IV->getDeclContext()); 1282 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D)) 1283 D = CAT->getClassInterface(); 1284 ClassDeclared = cast<ObjCInterfaceDecl>(D); 1285 } else { 1286 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) { 1287 Diag(MemberLoc, 1288 diag::err_property_found_suggest) 1289 << Member << BaseExpr.get()->getType() 1290 << FixItHint::CreateReplacement(OpLoc, "."); 1291 return ExprError(); 1292 } 1293 1294 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar) 1295 << IDecl->getDeclName() << MemberName 1296 << BaseExpr.get()->getSourceRange(); 1297 return ExprError(); 1298 } 1299 } 1300 1301 assert(ClassDeclared); 1302 1303 // If the decl being referenced had an error, return an error for this 1304 // sub-expr without emitting another error, in order to avoid cascading 1305 // error cases. 1306 if (IV->isInvalidDecl()) 1307 return ExprError(); 1308 1309 // Check whether we can reference this field. 1310 if (DiagnoseUseOfDecl(IV, MemberLoc)) 1311 return ExprError(); 1312 if (IV->getAccessControl() != ObjCIvarDecl::Public && 1313 IV->getAccessControl() != ObjCIvarDecl::Package) { 1314 ObjCInterfaceDecl *ClassOfMethodDecl = 0; 1315 if (ObjCMethodDecl *MD = getCurMethodDecl()) 1316 ClassOfMethodDecl = MD->getClassInterface(); 1317 else if (ObjCImpDecl && getCurFunctionDecl()) { 1318 // Case of a c-function declared inside an objc implementation. 1319 // FIXME: For a c-style function nested inside an objc implementation 1320 // class, there is no implementation context available, so we pass 1321 // down the context as argument to this routine. Ideally, this context 1322 // need be passed down in the AST node and somehow calculated from the 1323 // AST for a function decl. 1324 if (ObjCImplementationDecl *IMPD = 1325 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl)) 1326 ClassOfMethodDecl = IMPD->getClassInterface(); 1327 else if (ObjCCategoryImplDecl* CatImplClass = 1328 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl)) 1329 ClassOfMethodDecl = CatImplClass->getClassInterface(); 1330 } 1331 if (!getLangOpts().DebuggerSupport) { 1332 if (IV->getAccessControl() == ObjCIvarDecl::Private) { 1333 if (!declaresSameEntity(ClassDeclared, IDecl) || 1334 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared)) 1335 Diag(MemberLoc, diag::error_private_ivar_access) 1336 << IV->getDeclName(); 1337 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl)) 1338 // @protected 1339 Diag(MemberLoc, diag::error_protected_ivar_access) 1340 << IV->getDeclName(); 1341 } 1342 } 1343 bool warn = true; 1344 if (getLangOpts().ObjCAutoRefCount) { 1345 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts(); 1346 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp)) 1347 if (UO->getOpcode() == UO_Deref) 1348 BaseExp = UO->getSubExpr()->IgnoreParenCasts(); 1349 1350 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp)) 1351 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 1352 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access); 1353 warn = false; 1354 } 1355 } 1356 if (warn) { 1357 if (ObjCMethodDecl *MD = getCurMethodDecl()) { 1358 ObjCMethodFamily MF = MD->getMethodFamily(); 1359 warn = (MF != OMF_init && MF != OMF_dealloc && 1360 MF != OMF_finalize && 1361 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV)); 1362 } 1363 if (warn) 1364 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName(); 1365 } 1366 1367 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(), 1368 MemberLoc, OpLoc, 1369 BaseExpr.take(), 1370 IsArrow); 1371 1372 if (getLangOpts().ObjCAutoRefCount) { 1373 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) { 1374 DiagnosticsEngine::Level Level = 1375 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak, 1376 MemberLoc); 1377 if (Level != DiagnosticsEngine::Ignored) 1378 recordUseOfEvaluatedWeak(Result); 1379 } 1380 } 1381 1382 return Owned(Result); 1383 } 1384 1385 // Objective-C property access. 1386 const ObjCObjectPointerType *OPT; 1387 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) { 1388 if (!SS.isEmpty() && !SS.isInvalid()) { 1389 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access) 1390 << 0 << SS.getScopeRep() 1391 << FixItHint::CreateRemoval(SS.getRange()); 1392 SS.clear(); 1393 } 1394 1395 // This actually uses the base as an r-value. 1396 BaseExpr = DefaultLvalueConversion(BaseExpr.take()); 1397 if (BaseExpr.isInvalid()) 1398 return ExprError(); 1399 1400 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType())); 1401 1402 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1403 1404 const ObjCObjectType *OT = OPT->getObjectType(); 1405 1406 // id, with and without qualifiers. 1407 if (OT->isObjCId()) { 1408 // Check protocols on qualified interfaces. 1409 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1410 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) { 1411 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) { 1412 // Check the use of this declaration 1413 if (DiagnoseUseOfDecl(PD, MemberLoc)) 1414 return ExprError(); 1415 1416 return Owned(new (Context) ObjCPropertyRefExpr(PD, 1417 Context.PseudoObjectTy, 1418 VK_LValue, 1419 OK_ObjCProperty, 1420 MemberLoc, 1421 BaseExpr.take())); 1422 } 1423 1424 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) { 1425 // Check the use of this method. 1426 if (DiagnoseUseOfDecl(OMD, MemberLoc)) 1427 return ExprError(); 1428 Selector SetterSel = 1429 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1430 PP.getSelectorTable(), 1431 Member); 1432 ObjCMethodDecl *SMD = 0; 1433 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0, 1434 SetterSel, Context)) 1435 SMD = dyn_cast<ObjCMethodDecl>(SDecl); 1436 1437 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, 1438 Context.PseudoObjectTy, 1439 VK_LValue, OK_ObjCProperty, 1440 MemberLoc, BaseExpr.take())); 1441 } 1442 } 1443 // Use of id.member can only be for a property reference. Do not 1444 // use the 'id' redefinition in this case. 1445 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1446 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1447 ObjCImpDecl, HasTemplateArgs); 1448 1449 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1450 << MemberName << BaseType); 1451 } 1452 1453 // 'Class', unqualified only. 1454 if (OT->isObjCClass()) { 1455 // Only works in a method declaration (??!). 1456 ObjCMethodDecl *MD = getCurMethodDecl(); 1457 if (!MD) { 1458 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1459 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1460 ObjCImpDecl, HasTemplateArgs); 1461 1462 goto fail; 1463 } 1464 1465 // Also must look for a getter name which uses property syntax. 1466 Selector Sel = PP.getSelectorTable().getNullarySelector(Member); 1467 ObjCInterfaceDecl *IFace = MD->getClassInterface(); 1468 ObjCMethodDecl *Getter; 1469 if ((Getter = IFace->lookupClassMethod(Sel))) { 1470 // Check the use of this method. 1471 if (DiagnoseUseOfDecl(Getter, MemberLoc)) 1472 return ExprError(); 1473 } else 1474 Getter = IFace->lookupPrivateMethod(Sel, false); 1475 // If we found a getter then this may be a valid dot-reference, we 1476 // will look for the matching setter, in case it is needed. 1477 Selector SetterSel = 1478 SelectorTable::constructSetterSelector(PP.getIdentifierTable(), 1479 PP.getSelectorTable(), 1480 Member); 1481 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel); 1482 if (!Setter) { 1483 // If this reference is in an @implementation, also check for 'private' 1484 // methods. 1485 Setter = IFace->lookupPrivateMethod(SetterSel, false); 1486 } 1487 1488 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc)) 1489 return ExprError(); 1490 1491 if (Getter || Setter) { 1492 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter, 1493 Context.PseudoObjectTy, 1494 VK_LValue, OK_ObjCProperty, 1495 MemberLoc, BaseExpr.take())); 1496 } 1497 1498 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr)) 1499 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1500 ObjCImpDecl, HasTemplateArgs); 1501 1502 return ExprError(Diag(MemberLoc, diag::err_property_not_found) 1503 << MemberName << BaseType); 1504 } 1505 1506 // Normal property access. 1507 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, 1508 MemberName, MemberLoc, 1509 SourceLocation(), QualType(), false); 1510 } 1511 1512 // Handle 'field access' to vectors, such as 'V.xx'. 1513 if (BaseType->isExtVectorType()) { 1514 // FIXME: this expr should store IsArrow. 1515 IdentifierInfo *Member = MemberName.getAsIdentifierInfo(); 1516 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind()); 1517 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc, 1518 Member, MemberLoc); 1519 if (ret.isNull()) 1520 return ExprError(); 1521 1522 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(), 1523 *Member, MemberLoc)); 1524 } 1525 1526 // Adjust builtin-sel to the appropriate redefinition type if that's 1527 // not just a pointer to builtin-sel again. 1528 if (IsArrow && 1529 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) && 1530 !Context.getObjCSelRedefinitionType()->isObjCSelType()) { 1531 BaseExpr = ImpCastExprToType(BaseExpr.take(), 1532 Context.getObjCSelRedefinitionType(), 1533 CK_BitCast); 1534 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1535 ObjCImpDecl, HasTemplateArgs); 1536 } 1537 1538 // Failure cases. 1539 fail: 1540 1541 // Recover from dot accesses to pointers, e.g.: 1542 // type *foo; 1543 // foo.bar 1544 // This is actually well-formed in two cases: 1545 // - 'type' is an Objective C type 1546 // - 'bar' is a pseudo-destructor name which happens to refer to 1547 // the appropriate pointer type 1548 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) { 1549 if (!IsArrow && Ptr->getPointeeType()->isRecordType() && 1550 MemberName.getNameKind() != DeclarationName::CXXDestructorName) { 1551 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion) 1552 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange() 1553 << FixItHint::CreateReplacement(OpLoc, "->"); 1554 1555 // Recurse as an -> access. 1556 IsArrow = true; 1557 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1558 ObjCImpDecl, HasTemplateArgs); 1559 } 1560 } 1561 1562 // If the user is trying to apply -> or . to a function name, it's probably 1563 // because they forgot parentheses to call that function. 1564 if (tryToRecoverWithCall(BaseExpr, 1565 PDiag(diag::err_member_reference_needs_call), 1566 /*complain*/ false, 1567 IsArrow ? &isPointerToRecordType : &isRecordType)) { 1568 if (BaseExpr.isInvalid()) 1569 return ExprError(); 1570 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take()); 1571 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS, 1572 ObjCImpDecl, HasTemplateArgs); 1573 } 1574 1575 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union) 1576 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc; 1577 1578 return ExprError(); 1579 } 1580 1581 /// The main callback when the parser finds something like 1582 /// expression . [nested-name-specifier] identifier 1583 /// expression -> [nested-name-specifier] identifier 1584 /// where 'identifier' encompasses a fairly broad spectrum of 1585 /// possibilities, including destructor and operator references. 1586 /// 1587 /// \param OpKind either tok::arrow or tok::period 1588 /// \param HasTrailingLParen whether the next token is '(', which 1589 /// is used to diagnose mis-uses of special members that can 1590 /// only be called 1591 /// \param ObjCImpDecl the current Objective-C \@implementation 1592 /// decl; this is an ugly hack around the fact that Objective-C 1593 /// \@implementations aren't properly put in the context chain 1594 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base, 1595 SourceLocation OpLoc, 1596 tok::TokenKind OpKind, 1597 CXXScopeSpec &SS, 1598 SourceLocation TemplateKWLoc, 1599 UnqualifiedId &Id, 1600 Decl *ObjCImpDecl, 1601 bool HasTrailingLParen) { 1602 if (SS.isSet() && SS.isInvalid()) 1603 return ExprError(); 1604 1605 // Warn about the explicit constructor calls Microsoft extension. 1606 if (getLangOpts().MicrosoftExt && 1607 Id.getKind() == UnqualifiedId::IK_ConstructorName) 1608 Diag(Id.getSourceRange().getBegin(), 1609 diag::ext_ms_explicit_constructor_call); 1610 1611 TemplateArgumentListInfo TemplateArgsBuffer; 1612 1613 // Decompose the name into its component parts. 1614 DeclarationNameInfo NameInfo; 1615 const TemplateArgumentListInfo *TemplateArgs; 1616 DecomposeUnqualifiedId(Id, TemplateArgsBuffer, 1617 NameInfo, TemplateArgs); 1618 1619 DeclarationName Name = NameInfo.getName(); 1620 bool IsArrow = (OpKind == tok::arrow); 1621 1622 NamedDecl *FirstQualifierInScope 1623 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S, SS.getScopeRep())); 1624 1625 // This is a postfix expression, so get rid of ParenListExprs. 1626 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base); 1627 if (Result.isInvalid()) return ExprError(); 1628 Base = Result.take(); 1629 1630 if (Base->getType()->isDependentType() || Name.isDependentName() || 1631 isDependentScopeSpecifier(SS)) { 1632 Result = ActOnDependentMemberExpr(Base, Base->getType(), 1633 IsArrow, OpLoc, 1634 SS, TemplateKWLoc, FirstQualifierInScope, 1635 NameInfo, TemplateArgs); 1636 } else { 1637 LookupResult R(*this, NameInfo, LookupMemberName); 1638 ExprResult BaseResult = Owned(Base); 1639 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc, 1640 SS, ObjCImpDecl, TemplateArgs != 0); 1641 if (BaseResult.isInvalid()) 1642 return ExprError(); 1643 Base = BaseResult.take(); 1644 1645 if (Result.isInvalid()) { 1646 Owned(Base); 1647 return ExprError(); 1648 } 1649 1650 if (Result.get()) { 1651 // The only way a reference to a destructor can be used is to 1652 // immediately call it, which falls into this case. If the 1653 // next token is not a '(', produce a diagnostic and build the 1654 // call now. 1655 if (!HasTrailingLParen && 1656 Id.getKind() == UnqualifiedId::IK_DestructorName) 1657 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get()); 1658 1659 return Result; 1660 } 1661 1662 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen}; 1663 Result = BuildMemberReferenceExpr(Base, Base->getType(), 1664 OpLoc, IsArrow, SS, TemplateKWLoc, 1665 FirstQualifierInScope, R, TemplateArgs, 1666 false, &ExtraArgs); 1667 } 1668 1669 return Result; 1670 } 1671 1672 static ExprResult 1673 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow, 1674 const CXXScopeSpec &SS, FieldDecl *Field, 1675 DeclAccessPair FoundDecl, 1676 const DeclarationNameInfo &MemberNameInfo) { 1677 // x.a is an l-value if 'a' has a reference type. Otherwise: 1678 // x.a is an l-value/x-value/pr-value if the base is (and note 1679 // that *x is always an l-value), except that if the base isn't 1680 // an ordinary object then we must have an rvalue. 1681 ExprValueKind VK = VK_LValue; 1682 ExprObjectKind OK = OK_Ordinary; 1683 if (!IsArrow) { 1684 if (BaseExpr->getObjectKind() == OK_Ordinary) 1685 VK = BaseExpr->getValueKind(); 1686 else 1687 VK = VK_RValue; 1688 } 1689 if (VK != VK_RValue && Field->isBitField()) 1690 OK = OK_BitField; 1691 1692 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref] 1693 QualType MemberType = Field->getType(); 1694 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) { 1695 MemberType = Ref->getPointeeType(); 1696 VK = VK_LValue; 1697 } else { 1698 QualType BaseType = BaseExpr->getType(); 1699 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType(); 1700 1701 Qualifiers BaseQuals = BaseType.getQualifiers(); 1702 1703 // GC attributes are never picked up by members. 1704 BaseQuals.removeObjCGCAttr(); 1705 1706 // CVR attributes from the base are picked up by members, 1707 // except that 'mutable' members don't pick up 'const'. 1708 if (Field->isMutable()) BaseQuals.removeConst(); 1709 1710 Qualifiers MemberQuals 1711 = S.Context.getCanonicalType(MemberType).getQualifiers(); 1712 1713 assert(!MemberQuals.hasAddressSpace()); 1714 1715 1716 Qualifiers Combined = BaseQuals + MemberQuals; 1717 if (Combined != MemberQuals) 1718 MemberType = S.Context.getQualifiedType(MemberType, Combined); 1719 } 1720 1721 S.UnusedPrivateFields.remove(Field); 1722 1723 ExprResult Base = 1724 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(), 1725 FoundDecl, Field); 1726 if (Base.isInvalid()) 1727 return ExprError(); 1728 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS, 1729 /*TemplateKWLoc=*/SourceLocation(), 1730 Field, FoundDecl, MemberNameInfo, 1731 MemberType, VK, OK)); 1732 } 1733 1734 /// Builds an implicit member access expression. The current context 1735 /// is known to be an instance method, and the given unqualified lookup 1736 /// set is known to contain only instance members, at least one of which 1737 /// is from an appropriate type. 1738 ExprResult 1739 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS, 1740 SourceLocation TemplateKWLoc, 1741 LookupResult &R, 1742 const TemplateArgumentListInfo *TemplateArgs, 1743 bool IsKnownInstance) { 1744 assert(!R.empty() && !R.isAmbiguous()); 1745 1746 SourceLocation loc = R.getNameLoc(); 1747 1748 // If this is known to be an instance access, go ahead and build an 1749 // implicit 'this' expression now. 1750 // 'this' expression now. 1751 QualType ThisTy = getCurrentThisType(); 1752 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'"); 1753 1754 Expr *baseExpr = 0; // null signifies implicit access 1755 if (IsKnownInstance) { 1756 SourceLocation Loc = R.getNameLoc(); 1757 if (SS.getRange().isValid()) 1758 Loc = SS.getRange().getBegin(); 1759 CheckCXXThisCapture(Loc); 1760 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true); 1761 } 1762 1763 return BuildMemberReferenceExpr(baseExpr, ThisTy, 1764 /*OpLoc*/ SourceLocation(), 1765 /*IsArrow*/ true, 1766 SS, TemplateKWLoc, 1767 /*FirstQualifierInScope*/ 0, 1768 R, TemplateArgs); 1769 } 1770