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