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