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