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