1 //===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis member access expressions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/SemaInternal.h"
14 #include "clang/Sema/Lookup.h"
15 #include "clang/Sema/Scope.h"
16 #include "clang/Sema/ScopeInfo.h"
17 #include "clang/AST/DeclCXX.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/DeclTemplate.h"
20 #include "clang/AST/ExprCXX.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Lex/Preprocessor.h"
24 using namespace clang;
27 /// Determines if the given class is provably not derived from all of
28 /// the prospective base classes.
29 static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
30 CXXRecordDecl *Record,
31 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
32 if (Bases.count(Record->getCanonicalDecl()))
35 RecordDecl *RD = Record->getDefinition();
36 if (!RD) return false;
37 Record = cast<CXXRecordDecl>(RD);
39 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
40 E = Record->bases_end(); I != E; ++I) {
41 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
42 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
43 if (!BaseRT) return false;
45 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
46 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
54 /// The reference is definitely not an instance member access.
57 /// The reference may be an implicit instance member access.
60 /// The reference may be to an instance member, but it might be invalid if
61 /// so, because the context is not an instance method.
62 IMA_Mixed_StaticContext,
64 /// The reference may be to an instance member, but it is invalid if
65 /// so, because the context is from an unrelated class.
68 /// The reference is definitely an implicit instance member access.
71 /// The reference may be to an unresolved using declaration.
74 /// The reference may be to an unresolved using declaration and the
75 /// context is not an instance method.
76 IMA_Unresolved_StaticContext,
78 // The reference refers to a field which is not a member of the containing
79 // class, which is allowed because we're in C++11 mode and the context is
81 IMA_Field_Uneval_Context,
83 /// All possible referrents are instance members and the current
84 /// context is not an instance method.
85 IMA_Error_StaticContext,
87 /// All possible referrents are instance members of an unrelated
92 /// The given lookup names class member(s) and is not being used for
93 /// an address-of-member expression. Classify the type of access
94 /// according to whether it's possible that this reference names an
95 /// instance member. This is best-effort in dependent contexts; it is okay to
96 /// conservatively answer "yes", in which case some errors will simply
97 /// not be caught until template-instantiation.
98 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
100 const LookupResult &R) {
101 assert(!R.empty() && (*R.begin())->isCXXClassMember());
103 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
105 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
106 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
108 if (R.isUnresolvableResult())
109 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
111 // Collect all the declaring classes of instance members we find.
112 bool hasNonInstance = false;
113 bool isField = false;
114 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
115 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
118 if (D->isCXXInstanceMember()) {
119 if (dyn_cast<FieldDecl>(D) || dyn_cast<IndirectFieldDecl>(D))
122 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
123 Classes.insert(R->getCanonicalDecl());
126 hasNonInstance = true;
129 // If we didn't find any instance members, it can't be an implicit
134 bool IsCXX11UnevaluatedField = false;
135 if (SemaRef.getLangOpts().CPlusPlus0x && isField) {
136 // C++11 [expr.prim.general]p12:
137 // An id-expression that denotes a non-static data member or non-static
138 // member function of a class can only be used:
140 // - if that id-expression denotes a non-static data member and it
141 // appears in an unevaluated operand.
142 const Sema::ExpressionEvaluationContextRecord& record
143 = SemaRef.ExprEvalContexts.back();
144 if (record.Context == Sema::Unevaluated)
145 IsCXX11UnevaluatedField = true;
148 // If the current context is not an instance method, it can't be
149 // an implicit member reference.
150 if (isStaticContext) {
152 return IMA_Mixed_StaticContext;
154 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
155 : IMA_Error_StaticContext;
158 CXXRecordDecl *contextClass;
159 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
160 contextClass = MD->getParent()->getCanonicalDecl();
162 contextClass = cast<CXXRecordDecl>(DC);
164 // [class.mfct.non-static]p3:
165 // ...is used in the body of a non-static member function of class X,
166 // if name lookup (3.4.1) resolves the name in the id-expression to a
167 // non-static non-type member of some class C [...]
168 // ...if C is not X or a base class of X, the class member access expression
170 if (R.getNamingClass() &&
171 contextClass->getCanonicalDecl() !=
172 R.getNamingClass()->getCanonicalDecl() &&
173 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
174 return hasNonInstance ? IMA_Mixed_Unrelated :
175 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
178 // If we can prove that the current context is unrelated to all the
179 // declaring classes, it can't be an implicit member reference (in
180 // which case it's an error if any of those members are selected).
181 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
182 return hasNonInstance ? IMA_Mixed_Unrelated :
183 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
186 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
189 /// Diagnose a reference to a field with no object available.
190 static void diagnoseInstanceReference(Sema &SemaRef,
191 const CXXScopeSpec &SS,
193 const DeclarationNameInfo &nameInfo) {
194 SourceLocation Loc = nameInfo.getLoc();
195 SourceRange Range(Loc);
196 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
198 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
199 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
200 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
201 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
203 bool InStaticMethod = Method && Method->isStatic();
204 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
206 if (IsField && InStaticMethod)
207 // "invalid use of member 'x' in static member function"
208 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
209 << Range << nameInfo.getName();
210 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
211 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
212 // Unqualified lookup in a non-static member function found a member of an
214 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
215 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
217 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
218 << nameInfo.getName() << Range;
220 SemaRef.Diag(Loc, diag::err_member_call_without_object)
224 /// Builds an expression which might be an implicit member expression.
226 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
227 SourceLocation TemplateKWLoc,
229 const TemplateArgumentListInfo *TemplateArgs) {
230 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
232 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
235 case IMA_Mixed_Unrelated:
237 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
239 case IMA_Field_Uneval_Context:
240 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
241 << R.getLookupNameInfo().getName();
244 case IMA_Mixed_StaticContext:
245 case IMA_Unresolved_StaticContext:
246 if (TemplateArgs || TemplateKWLoc.isValid())
247 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
248 return BuildDeclarationNameExpr(SS, R, false);
250 case IMA_Error_StaticContext:
251 case IMA_Error_Unrelated:
252 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
253 R.getLookupNameInfo());
257 llvm_unreachable("unexpected instance member access kind");
260 /// Check an ext-vector component access expression.
262 /// VK should be set in advance to the value kind of the base
265 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
266 SourceLocation OpLoc, const IdentifierInfo *CompName,
267 SourceLocation CompLoc) {
268 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
271 // FIXME: This logic can be greatly simplified by splitting it along
272 // halving/not halving and reworking the component checking.
273 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
275 // The vector accessor can't exceed the number of elements.
276 const char *compStr = CompName->getNameStart();
278 // This flag determines whether or not the component is one of the four
279 // special names that indicate a subset of exactly half the elements are
281 bool HalvingSwizzle = false;
283 // This flag determines whether or not CompName has an 's' char prefix,
284 // indicating that it is a string of hex values to be used as vector indices.
285 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
287 bool HasRepeated = false;
288 bool HasIndex[16] = {};
292 // Check that we've found one of the special components, or that the component
293 // names must come from the same set.
294 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
295 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
296 HalvingSwizzle = true;
297 } else if (!HexSwizzle &&
298 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
300 if (HasIndex[Idx]) HasRepeated = true;
301 HasIndex[Idx] = true;
303 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
305 if (HexSwizzle) compStr++;
306 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
307 if (HasIndex[Idx]) HasRepeated = true;
308 HasIndex[Idx] = true;
313 if (!HalvingSwizzle && *compStr) {
314 // We didn't get to the end of the string. This means the component names
315 // didn't come from the same set *or* we encountered an illegal name.
316 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
317 << StringRef(compStr, 1) << SourceRange(CompLoc);
321 // Ensure no component accessor exceeds the width of the vector type it
323 if (!HalvingSwizzle) {
324 compStr = CompName->getNameStart();
330 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
331 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
332 << baseType << SourceRange(CompLoc);
338 // The component accessor looks fine - now we need to compute the actual type.
339 // The vector type is implied by the component accessor. For example,
340 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
341 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
342 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
343 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
344 : CompName->getLength();
349 return vecType->getElementType();
351 if (HasRepeated) VK = VK_RValue;
353 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
354 // Now look up the TypeDefDecl from the vector type. Without this,
355 // diagostics look bad. We want extended vector types to appear built-in.
356 for (Sema::ExtVectorDeclsType::iterator
357 I = S.ExtVectorDecls.begin(S.getExternalSource()),
358 E = S.ExtVectorDecls.end();
360 if ((*I)->getUnderlyingType() == VT)
361 return S.Context.getTypedefType(*I);
364 return VT; // should never get here (a typedef type should always be found).
367 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
368 IdentifierInfo *Member,
370 ASTContext &Context) {
372 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
374 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
377 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
378 E = PDecl->protocol_end(); I != E; ++I) {
379 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
386 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
387 IdentifierInfo *Member,
389 ASTContext &Context) {
390 // Check protocols on qualified interfaces.
392 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
393 E = QIdTy->qual_end(); I != E; ++I) {
395 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
399 // Also must look for a getter or setter name which uses property syntax.
400 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
406 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
407 E = QIdTy->qual_end(); I != E; ++I) {
408 // Search in the protocol-qualifier list of current protocol.
409 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
419 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
420 bool IsArrow, SourceLocation OpLoc,
421 const CXXScopeSpec &SS,
422 SourceLocation TemplateKWLoc,
423 NamedDecl *FirstQualifierInScope,
424 const DeclarationNameInfo &NameInfo,
425 const TemplateArgumentListInfo *TemplateArgs) {
426 // Even in dependent contexts, try to diagnose base expressions with
427 // obviously wrong types, e.g.:
432 // In Obj-C++, however, the above expression is valid, since it could be
433 // accessing the 'f' property if T is an Obj-C interface. The extra check
434 // allows this, while still reporting an error if T is a struct pointer.
436 const PointerType *PT = BaseType->getAs<PointerType>();
437 if (PT && (!getLangOpts().ObjC1 ||
438 PT->getPointeeType()->isRecordType())) {
439 assert(BaseExpr && "cannot happen with implicit member accesses");
440 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
441 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
446 assert(BaseType->isDependentType() ||
447 NameInfo.getName().isDependentName() ||
448 isDependentScopeSpecifier(SS));
450 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
451 // must have pointer type, and the accessed type is the pointee.
452 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
454 SS.getWithLocInContext(Context),
456 FirstQualifierInScope,
457 NameInfo, TemplateArgs));
460 /// We know that the given qualified member reference points only to
461 /// declarations which do not belong to the static type of the base
462 /// expression. Diagnose the problem.
463 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
466 const CXXScopeSpec &SS,
468 const DeclarationNameInfo &nameInfo) {
469 // If this is an implicit member access, use a different set of
472 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
474 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
475 << SS.getRange() << rep << BaseType;
478 // Check whether the declarations we found through a nested-name
479 // specifier in a member expression are actually members of the base
480 // type. The restriction here is:
483 // ... In these cases, the id-expression shall name a
484 // member of the class or of one of its base classes.
486 // So it's perfectly legitimate for the nested-name specifier to name
487 // an unrelated class, and for us to find an overload set including
488 // decls from classes which are not superclasses, as long as the decl
489 // we actually pick through overload resolution is from a superclass.
490 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
492 const CXXScopeSpec &SS,
493 const LookupResult &R) {
494 const RecordType *BaseRT = BaseType->getAs<RecordType>();
496 // We can't check this yet because the base type is still
498 assert(BaseType->isDependentType());
501 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
503 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
504 // If this is an implicit member reference and we find a
505 // non-instance member, it's not an error.
506 if (!BaseExpr && !(*I)->isCXXInstanceMember())
509 // Note that we use the DC of the decl, not the underlying decl.
510 DeclContext *DC = (*I)->getDeclContext();
511 while (DC->isTransparentContext())
512 DC = DC->getParent();
517 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
518 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
520 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
524 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
525 R.getRepresentativeDecl(),
526 R.getLookupNameInfo());
532 // Callback to only accept typo corrections that are either a ValueDecl or a
533 // FunctionTemplateDecl.
534 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
536 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
537 NamedDecl *ND = candidate.getCorrectionDecl();
538 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
545 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
546 SourceRange BaseRange, const RecordType *RTy,
547 SourceLocation OpLoc, CXXScopeSpec &SS,
548 bool HasTemplateArgs) {
549 RecordDecl *RDecl = RTy->getDecl();
550 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
551 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
552 diag::err_typecheck_incomplete_tag,
556 if (HasTemplateArgs) {
557 // LookupTemplateName doesn't expect these both to exist simultaneously.
558 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
561 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
565 DeclContext *DC = RDecl;
567 // If the member name was a qualified-id, look into the
568 // nested-name-specifier.
569 DC = SemaRef.computeDeclContext(SS, false);
571 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
572 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
573 << SS.getRange() << DC;
577 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
579 if (!isa<TypeDecl>(DC)) {
580 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
581 << DC << SS.getRange();
586 // The record definition is complete, now look up the member.
587 SemaRef.LookupQualifiedName(R, DC);
592 // We didn't find anything with the given name, so try to correct
594 DeclarationName Name = R.getLookupName();
595 RecordMemberExprValidatorCCC Validator;
596 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
597 R.getLookupKind(), NULL,
600 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
601 std::string CorrectedStr(
602 Corrected.getAsString(SemaRef.getLangOpts()));
603 std::string CorrectedQuotedStr(
604 Corrected.getQuoted(SemaRef.getLangOpts()));
605 R.setLookupName(Corrected.getCorrection());
607 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
608 << Name << DC << CorrectedQuotedStr << SS.getRange()
609 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
611 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
612 << ND->getDeclName();
619 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
620 SourceLocation OpLoc, bool IsArrow,
622 SourceLocation TemplateKWLoc,
623 NamedDecl *FirstQualifierInScope,
624 const DeclarationNameInfo &NameInfo,
625 const TemplateArgumentListInfo *TemplateArgs) {
626 if (BaseType->isDependentType() ||
627 (SS.isSet() && isDependentScopeSpecifier(SS)))
628 return ActOnDependentMemberExpr(Base, BaseType,
630 SS, TemplateKWLoc, FirstQualifierInScope,
631 NameInfo, TemplateArgs);
633 LookupResult R(*this, NameInfo, LookupMemberName);
635 // Implicit member accesses.
637 QualType RecordTy = BaseType;
638 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
639 if (LookupMemberExprInRecord(*this, R, SourceRange(),
640 RecordTy->getAs<RecordType>(),
641 OpLoc, SS, TemplateArgs != 0))
644 // Explicit member accesses.
646 ExprResult BaseResult = Owned(Base);
648 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
649 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
651 if (BaseResult.isInvalid())
653 Base = BaseResult.take();
655 if (Result.isInvalid()) {
663 // LookupMemberExpr can modify Base, and thus change BaseType
664 BaseType = Base->getType();
667 return BuildMemberReferenceExpr(Base, BaseType,
668 OpLoc, IsArrow, SS, TemplateKWLoc,
669 FirstQualifierInScope, R, TemplateArgs);
673 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
674 const CXXScopeSpec &SS, FieldDecl *Field,
675 DeclAccessPair FoundDecl,
676 const DeclarationNameInfo &MemberNameInfo);
679 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
681 IndirectFieldDecl *indirectField,
682 Expr *baseObjectExpr,
683 SourceLocation opLoc) {
684 // First, build the expression that refers to the base object.
686 bool baseObjectIsPointer = false;
687 Qualifiers baseQuals;
689 // Case 1: the base of the indirect field is not a field.
690 VarDecl *baseVariable = indirectField->getVarDecl();
691 CXXScopeSpec EmptySS;
693 assert(baseVariable->getType()->isRecordType());
695 // In principle we could have a member access expression that
696 // accesses an anonymous struct/union that's a static member of
697 // the base object's class. However, under the current standard,
698 // static data members cannot be anonymous structs or unions.
699 // Supporting this is as easy as building a MemberExpr here.
700 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
702 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
705 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
706 if (result.isInvalid()) return ExprError();
708 baseObjectExpr = result.take();
709 baseObjectIsPointer = false;
710 baseQuals = baseObjectExpr->getType().getQualifiers();
712 // Case 2: the base of the indirect field is a field and the user
713 // wrote a member expression.
714 } else if (baseObjectExpr) {
715 // The caller provided the base object expression. Determine
716 // whether its a pointer and whether it adds any qualifiers to the
717 // anonymous struct/union fields we're looking into.
718 QualType objectType = baseObjectExpr->getType();
720 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
721 baseObjectIsPointer = true;
722 objectType = ptr->getPointeeType();
724 baseObjectIsPointer = false;
726 baseQuals = objectType.getQualifiers();
728 // Case 3: the base of the indirect field is a field and we should
729 // build an implicit member access.
731 // We've found a member of an anonymous struct/union that is
732 // inside a non-anonymous struct/union, so in a well-formed
733 // program our base object expression is "this".
734 QualType ThisTy = getCurrentThisType();
735 if (ThisTy.isNull()) {
736 Diag(loc, diag::err_invalid_member_use_in_static_method)
737 << indirectField->getDeclName();
741 // Our base object expression is "this".
742 CheckCXXThisCapture(loc);
744 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
745 baseObjectIsPointer = true;
746 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
749 // Build the implicit member references to the field of the
750 // anonymous struct/union.
751 Expr *result = baseObjectExpr;
752 IndirectFieldDecl::chain_iterator
753 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
755 // Build the first member access in the chain with full information.
757 FieldDecl *field = cast<FieldDecl>(*FI);
759 // FIXME: use the real found-decl info!
760 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
762 // Make a nameInfo that properly uses the anonymous name.
763 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
765 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
766 EmptySS, field, foundDecl,
767 memberNameInfo).take();
768 baseObjectIsPointer = false;
770 // FIXME: check qualified member access
773 // In all cases, we should now skip the first declaration in the chain.
777 FieldDecl *field = cast<FieldDecl>(*FI++);
779 // FIXME: these are somewhat meaningless
780 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
781 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
783 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
784 (FI == FEnd? SS : EmptySS), field,
785 foundDecl, memberNameInfo).take();
788 return Owned(result);
791 /// \brief Build a MemberExpr AST node.
792 static MemberExpr *BuildMemberExpr(Sema &SemaRef,
793 ASTContext &C, Expr *Base, bool isArrow,
794 const CXXScopeSpec &SS,
795 SourceLocation TemplateKWLoc,
797 DeclAccessPair FoundDecl,
798 const DeclarationNameInfo &MemberNameInfo,
800 ExprValueKind VK, ExprObjectKind OK,
801 const TemplateArgumentListInfo *TemplateArgs = 0) {
802 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
804 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
805 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
806 TemplateArgs, Ty, VK, OK);
807 SemaRef.MarkMemberReferenced(E);
812 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
813 SourceLocation OpLoc, bool IsArrow,
814 const CXXScopeSpec &SS,
815 SourceLocation TemplateKWLoc,
816 NamedDecl *FirstQualifierInScope,
818 const TemplateArgumentListInfo *TemplateArgs,
819 bool SuppressQualifierCheck,
820 ActOnMemberAccessExtraArgs *ExtraArgs) {
821 QualType BaseType = BaseExprType;
823 assert(BaseType->isPointerType());
824 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
826 R.setBaseObjectType(BaseType);
828 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
829 DeclarationName MemberName = MemberNameInfo.getName();
830 SourceLocation MemberLoc = MemberNameInfo.getLoc();
836 // Rederive where we looked up.
837 DeclContext *DC = (SS.isSet()
838 ? computeDeclContext(SS, false)
839 : BaseType->getAs<RecordType>()->getDecl());
842 ExprResult RetryExpr;
843 if (!IsArrow && BaseExpr) {
844 SFINAETrap Trap(*this, true);
845 ParsedType ObjectType;
846 bool MayBePseudoDestructor = false;
847 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
848 OpLoc, tok::arrow, ObjectType,
849 MayBePseudoDestructor);
850 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
851 CXXScopeSpec TempSS(SS);
852 RetryExpr = ActOnMemberAccessExpr(
853 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
854 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
855 ExtraArgs->HasTrailingLParen);
857 if (Trap.hasErrorOccurred())
858 RetryExpr = ExprError();
860 if (RetryExpr.isUsable()) {
861 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
862 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
867 Diag(R.getNameLoc(), diag::err_no_member)
869 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
873 // Diagnose lookups that find only declarations from a non-base
874 // type. This is possible for either qualified lookups (which may
875 // have been qualified with an unrelated type) or implicit member
876 // expressions (which were found with unqualified lookup and thus
877 // may have come from an enclosing scope). Note that it's okay for
878 // lookup to find declarations from a non-base type as long as those
879 // aren't the ones picked by overload resolution.
880 if ((SS.isSet() || !BaseExpr ||
881 (isa<CXXThisExpr>(BaseExpr) &&
882 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
883 !SuppressQualifierCheck &&
884 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
887 // Construct an unresolved result if we in fact got an unresolved
889 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
890 // Suppress any lookup-related diagnostics; we'll do these when we
892 R.suppressDiagnostics();
894 UnresolvedMemberExpr *MemExpr
895 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
896 BaseExpr, BaseExprType,
898 SS.getWithLocInContext(Context),
899 TemplateKWLoc, MemberNameInfo,
900 TemplateArgs, R.begin(), R.end());
902 return Owned(MemExpr);
905 assert(R.isSingleResult());
906 DeclAccessPair FoundDecl = R.begin().getPair();
907 NamedDecl *MemberDecl = R.getFoundDecl();
909 // FIXME: diagnose the presence of template arguments now.
911 // If the decl being referenced had an error, return an error for this
912 // sub-expr without emitting another error, in order to avoid cascading
914 if (MemberDecl->isInvalidDecl())
917 // Handle the implicit-member-access case.
919 // If this is not an instance member, convert to a non-member access.
920 if (!MemberDecl->isCXXInstanceMember())
921 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
923 SourceLocation Loc = R.getNameLoc();
924 if (SS.getRange().isValid())
925 Loc = SS.getRange().getBegin();
926 CheckCXXThisCapture(Loc);
927 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
930 bool ShouldCheckUse = true;
931 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
932 // Don't diagnose the use of a virtual member function unless it's
933 // explicitly qualified.
934 if (MD->isVirtual() && !SS.isSet())
935 ShouldCheckUse = false;
938 // Check the use of this member.
939 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
944 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
945 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
946 SS, FD, FoundDecl, MemberNameInfo);
948 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
949 // We may have found a field within an anonymous union or struct
950 // (C++ [class.union]).
951 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
954 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
955 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
956 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
957 Var->getType().getNonReferenceType(),
958 VK_LValue, OK_Ordinary));
961 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
962 ExprValueKind valueKind;
964 if (MemberFn->isInstance()) {
965 valueKind = VK_RValue;
966 type = Context.BoundMemberTy;
968 valueKind = VK_LValue;
969 type = MemberFn->getType();
972 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
973 TemplateKWLoc, MemberFn, FoundDecl,
974 MemberNameInfo, type, valueKind,
977 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
979 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
980 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
981 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
982 Enum->getType(), VK_RValue, OK_Ordinary));
987 // We found something that we didn't expect. Complain.
988 if (isa<TypeDecl>(MemberDecl))
989 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
990 << MemberName << BaseType << int(IsArrow);
992 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
993 << MemberName << BaseType << int(IsArrow);
995 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
997 R.suppressDiagnostics();
1001 /// Given that normal member access failed on the given expression,
1002 /// and given that the expression's type involves builtin-id or
1003 /// builtin-Class, decide whether substituting in the redefinition
1004 /// types would be profitable. The redefinition type is whatever
1005 /// this translation unit tried to typedef to id/Class; we store
1006 /// it to the side and then re-use it in places like this.
1007 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1008 const ObjCObjectPointerType *opty
1009 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1010 if (!opty) return false;
1012 const ObjCObjectType *ty = opty->getObjectType();
1015 if (ty->isObjCId()) {
1016 redef = S.Context.getObjCIdRedefinitionType();
1017 } else if (ty->isObjCClass()) {
1018 redef = S.Context.getObjCClassRedefinitionType();
1023 // Do the substitution as long as the redefinition type isn't just a
1024 // possibly-qualified pointer to builtin-id or builtin-Class again.
1025 opty = redef->getAs<ObjCObjectPointerType>();
1026 if (opty && !opty->getObjectType()->getInterface())
1029 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1033 static bool isRecordType(QualType T) {
1034 return T->isRecordType();
1036 static bool isPointerToRecordType(QualType T) {
1037 if (const PointerType *PT = T->getAs<PointerType>())
1038 return PT->getPointeeType()->isRecordType();
1042 /// Perform conversions on the LHS of a member access expression.
1044 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1045 if (IsArrow && !Base->getType()->isFunctionType())
1046 return DefaultFunctionArrayLvalueConversion(Base);
1048 return CheckPlaceholderExpr(Base);
1051 /// Look up the given member of the given non-type-dependent
1052 /// expression. This can return in one of two ways:
1053 /// * If it returns a sentinel null-but-valid result, the caller will
1054 /// assume that lookup was performed and the results written into
1055 /// the provided structure. It will take over from there.
1056 /// * Otherwise, the returned expression will be produced in place of
1057 /// an ordinary member expression.
1059 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1060 /// fixed for ObjC++.
1062 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1063 bool &IsArrow, SourceLocation OpLoc,
1065 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1066 assert(BaseExpr.get() && "no base expression");
1068 // Perform default conversions.
1069 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
1070 if (BaseExpr.isInvalid())
1073 QualType BaseType = BaseExpr.get()->getType();
1074 assert(!BaseType->isDependentType());
1076 DeclarationName MemberName = R.getLookupName();
1077 SourceLocation MemberLoc = R.getNameLoc();
1079 // For later type-checking purposes, turn arrow accesses into dot
1080 // accesses. The only access type we support that doesn't follow
1081 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1082 // and those never use arrows, so this is unaffected.
1084 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1085 BaseType = Ptr->getPointeeType();
1086 else if (const ObjCObjectPointerType *Ptr
1087 = BaseType->getAs<ObjCObjectPointerType>())
1088 BaseType = Ptr->getPointeeType();
1089 else if (BaseType->isRecordType()) {
1090 // Recover from arrow accesses to records, e.g.:
1091 // struct MyRecord foo;
1093 // This is actually well-formed in C++ if MyRecord has an
1094 // overloaded operator->, but that should have been dealt with
1096 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1097 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1098 << FixItHint::CreateReplacement(OpLoc, ".");
1100 } else if (BaseType->isFunctionType()) {
1103 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1104 << BaseType << BaseExpr.get()->getSourceRange();
1109 // Handle field access to simple records.
1110 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1111 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1112 RTy, OpLoc, SS, HasTemplateArgs))
1115 // Returning valid-but-null is how we indicate to the caller that
1116 // the lookup result was filled in.
1117 return Owned((Expr*) 0);
1120 // Handle ivar access to Objective-C objects.
1121 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1122 if (!SS.isEmpty() && !SS.isInvalid()) {
1123 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1124 << 1 << SS.getScopeRep()
1125 << FixItHint::CreateRemoval(SS.getRange());
1129 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1131 // There are three cases for the base type:
1132 // - builtin id (qualified or unqualified)
1133 // - builtin Class (qualified or unqualified)
1135 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1137 if (getLangOpts().ObjCAutoRefCount &&
1138 (OTy->isObjCId() || OTy->isObjCClass()))
1140 // There's an implicit 'isa' ivar on all objects.
1141 // But we only actually find it this way on objects of type 'id',
1143 if (OTy->isObjCId() && Member->isStr("isa")) {
1144 Diag(MemberLoc, diag::warn_objc_isa_use);
1145 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1146 Context.getObjCClassType()));
1149 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1150 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1151 ObjCImpDecl, HasTemplateArgs);
1154 else if (Member && Member->isStr("isa")) {
1155 // If an ivar is (1) the first ivar in a root class and (2) named `isa`,
1156 // then issue the same deprecated warning that id->isa gets.
1157 ObjCInterfaceDecl *ClassDeclared = 0;
1158 if (ObjCIvarDecl *IV =
1159 IDecl->lookupInstanceVariable(Member, ClassDeclared)) {
1160 if (!ClassDeclared->getSuperClass()
1161 && (*ClassDeclared->ivar_begin()) == IV) {
1162 Diag(MemberLoc, diag::warn_objc_isa_use);
1163 Diag(IV->getLocation(), diag::note_ivar_decl);
1168 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1172 ObjCInterfaceDecl *ClassDeclared = 0;
1173 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1176 // Attempt to correct for typos in ivar names.
1177 DeclFilterCCC<ObjCIvarDecl> Validator;
1178 Validator.IsObjCIvarLookup = IsArrow;
1179 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1180 LookupMemberName, NULL, NULL,
1181 Validator, IDecl)) {
1182 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1183 Diag(R.getNameLoc(),
1184 diag::err_typecheck_member_reference_ivar_suggest)
1185 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1186 << FixItHint::CreateReplacement(R.getNameLoc(),
1187 IV->getNameAsString());
1188 Diag(IV->getLocation(), diag::note_previous_decl)
1189 << IV->getDeclName();
1191 // Figure out the class that declares the ivar.
1192 assert(!ClassDeclared);
1193 Decl *D = cast<Decl>(IV->getDeclContext());
1194 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1195 D = CAT->getClassInterface();
1196 ClassDeclared = cast<ObjCInterfaceDecl>(D);
1198 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1200 diag::err_property_found_suggest)
1201 << Member << BaseExpr.get()->getType()
1202 << FixItHint::CreateReplacement(OpLoc, ".");
1206 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1207 << IDecl->getDeclName() << MemberName
1208 << BaseExpr.get()->getSourceRange();
1213 assert(ClassDeclared);
1215 // If the decl being referenced had an error, return an error for this
1216 // sub-expr without emitting another error, in order to avoid cascading
1218 if (IV->isInvalidDecl())
1221 // Check whether we can reference this field.
1222 if (DiagnoseUseOfDecl(IV, MemberLoc))
1224 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1225 IV->getAccessControl() != ObjCIvarDecl::Package) {
1226 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1227 if (ObjCMethodDecl *MD = getCurMethodDecl())
1228 ClassOfMethodDecl = MD->getClassInterface();
1229 else if (ObjCImpDecl && getCurFunctionDecl()) {
1230 // Case of a c-function declared inside an objc implementation.
1231 // FIXME: For a c-style function nested inside an objc implementation
1232 // class, there is no implementation context available, so we pass
1233 // down the context as argument to this routine. Ideally, this context
1234 // need be passed down in the AST node and somehow calculated from the
1235 // AST for a function decl.
1236 if (ObjCImplementationDecl *IMPD =
1237 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1238 ClassOfMethodDecl = IMPD->getClassInterface();
1239 else if (ObjCCategoryImplDecl* CatImplClass =
1240 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1241 ClassOfMethodDecl = CatImplClass->getClassInterface();
1243 if (!getLangOpts().DebuggerSupport) {
1244 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1245 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1246 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1247 Diag(MemberLoc, diag::error_private_ivar_access)
1248 << IV->getDeclName();
1249 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1251 Diag(MemberLoc, diag::error_protected_ivar_access)
1252 << IV->getDeclName();
1256 if (getLangOpts().ObjCAutoRefCount) {
1257 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1258 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1259 if (UO->getOpcode() == UO_Deref)
1260 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1262 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1263 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1264 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1269 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1270 ObjCMethodFamily MF = MD->getMethodFamily();
1271 warn = (MF != OMF_init && MF != OMF_dealloc &&
1272 MF != OMF_finalize);
1275 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1278 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1283 if (getLangOpts().ObjCAutoRefCount) {
1284 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1285 DiagnosticsEngine::Level Level =
1286 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1288 if (Level != DiagnosticsEngine::Ignored)
1289 getCurFunction()->recordUseOfWeak(Result);
1293 return Owned(Result);
1296 // Objective-C property access.
1297 const ObjCObjectPointerType *OPT;
1298 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1299 if (!SS.isEmpty() && !SS.isInvalid()) {
1300 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1301 << 0 << SS.getScopeRep()
1302 << FixItHint::CreateRemoval(SS.getRange());
1306 // This actually uses the base as an r-value.
1307 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1308 if (BaseExpr.isInvalid())
1311 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1313 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1315 const ObjCObjectType *OT = OPT->getObjectType();
1317 // id, with and without qualifiers.
1318 if (OT->isObjCId()) {
1319 // Check protocols on qualified interfaces.
1320 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1321 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1322 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1323 // Check the use of this declaration
1324 if (DiagnoseUseOfDecl(PD, MemberLoc))
1327 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1328 Context.PseudoObjectTy,
1335 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1336 // Check the use of this method.
1337 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1339 Selector SetterSel =
1340 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1341 PP.getSelectorTable(), Member);
1342 ObjCMethodDecl *SMD = 0;
1343 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1344 SetterSel, Context))
1345 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1347 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1348 Context.PseudoObjectTy,
1349 VK_LValue, OK_ObjCProperty,
1350 MemberLoc, BaseExpr.take()));
1353 // Use of id.member can only be for a property reference. Do not
1354 // use the 'id' redefinition in this case.
1355 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1356 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1357 ObjCImpDecl, HasTemplateArgs);
1359 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1360 << MemberName << BaseType);
1363 // 'Class', unqualified only.
1364 if (OT->isObjCClass()) {
1365 // Only works in a method declaration (??!).
1366 ObjCMethodDecl *MD = getCurMethodDecl();
1368 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1369 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1370 ObjCImpDecl, HasTemplateArgs);
1375 // Also must look for a getter name which uses property syntax.
1376 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1377 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1378 ObjCMethodDecl *Getter;
1379 if ((Getter = IFace->lookupClassMethod(Sel))) {
1380 // Check the use of this method.
1381 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1384 Getter = IFace->lookupPrivateMethod(Sel, false);
1385 // If we found a getter then this may be a valid dot-reference, we
1386 // will look for the matching setter, in case it is needed.
1387 Selector SetterSel =
1388 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1389 PP.getSelectorTable(), Member);
1390 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1392 // If this reference is in an @implementation, also check for 'private'
1394 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1397 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1400 if (Getter || Setter) {
1401 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1402 Context.PseudoObjectTy,
1403 VK_LValue, OK_ObjCProperty,
1404 MemberLoc, BaseExpr.take()));
1407 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1408 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1409 ObjCImpDecl, HasTemplateArgs);
1411 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1412 << MemberName << BaseType);
1415 // Normal property access.
1416 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1417 MemberName, MemberLoc,
1418 SourceLocation(), QualType(), false);
1421 // Handle 'field access' to vectors, such as 'V.xx'.
1422 if (BaseType->isExtVectorType()) {
1423 // FIXME: this expr should store IsArrow.
1424 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1425 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1426 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1431 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1432 *Member, MemberLoc));
1435 // Adjust builtin-sel to the appropriate redefinition type if that's
1436 // not just a pointer to builtin-sel again.
1438 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1439 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1440 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1441 Context.getObjCSelRedefinitionType(),
1443 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1444 ObjCImpDecl, HasTemplateArgs);
1450 // Recover from dot accesses to pointers, e.g.:
1453 // This is actually well-formed in two cases:
1454 // - 'type' is an Objective C type
1455 // - 'bar' is a pseudo-destructor name which happens to refer to
1456 // the appropriate pointer type
1457 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1458 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1459 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1460 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1461 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1462 << FixItHint::CreateReplacement(OpLoc, "->");
1464 // Recurse as an -> access.
1466 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1467 ObjCImpDecl, HasTemplateArgs);
1471 // If the user is trying to apply -> or . to a function name, it's probably
1472 // because they forgot parentheses to call that function.
1473 if (tryToRecoverWithCall(BaseExpr,
1474 PDiag(diag::err_member_reference_needs_call),
1476 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1477 if (BaseExpr.isInvalid())
1479 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1480 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1481 ObjCImpDecl, HasTemplateArgs);
1484 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1485 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1490 /// The main callback when the parser finds something like
1491 /// expression . [nested-name-specifier] identifier
1492 /// expression -> [nested-name-specifier] identifier
1493 /// where 'identifier' encompasses a fairly broad spectrum of
1494 /// possibilities, including destructor and operator references.
1496 /// \param OpKind either tok::arrow or tok::period
1497 /// \param HasTrailingLParen whether the next token is '(', which
1498 /// is used to diagnose mis-uses of special members that can
1500 /// \param ObjCImpDecl the current Objective-C \@implementation
1501 /// decl; this is an ugly hack around the fact that Objective-C
1502 /// \@implementations aren't properly put in the context chain
1503 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1504 SourceLocation OpLoc,
1505 tok::TokenKind OpKind,
1507 SourceLocation TemplateKWLoc,
1510 bool HasTrailingLParen) {
1511 if (SS.isSet() && SS.isInvalid())
1514 // Warn about the explicit constructor calls Microsoft extension.
1515 if (getLangOpts().MicrosoftExt &&
1516 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1517 Diag(Id.getSourceRange().getBegin(),
1518 diag::ext_ms_explicit_constructor_call);
1520 TemplateArgumentListInfo TemplateArgsBuffer;
1522 // Decompose the name into its component parts.
1523 DeclarationNameInfo NameInfo;
1524 const TemplateArgumentListInfo *TemplateArgs;
1525 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1526 NameInfo, TemplateArgs);
1528 DeclarationName Name = NameInfo.getName();
1529 bool IsArrow = (OpKind == tok::arrow);
1531 NamedDecl *FirstQualifierInScope
1532 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1533 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1535 // This is a postfix expression, so get rid of ParenListExprs.
1536 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1537 if (Result.isInvalid()) return ExprError();
1538 Base = Result.take();
1540 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1541 isDependentScopeSpecifier(SS)) {
1542 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1544 SS, TemplateKWLoc, FirstQualifierInScope,
1545 NameInfo, TemplateArgs);
1547 LookupResult R(*this, NameInfo, LookupMemberName);
1548 ExprResult BaseResult = Owned(Base);
1549 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1550 SS, ObjCImpDecl, TemplateArgs != 0);
1551 if (BaseResult.isInvalid())
1553 Base = BaseResult.take();
1555 if (Result.isInvalid()) {
1561 // The only way a reference to a destructor can be used is to
1562 // immediately call it, which falls into this case. If the
1563 // next token is not a '(', produce a diagnostic and build the
1565 if (!HasTrailingLParen &&
1566 Id.getKind() == UnqualifiedId::IK_DestructorName)
1567 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1572 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
1573 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1574 OpLoc, IsArrow, SS, TemplateKWLoc,
1575 FirstQualifierInScope, R, TemplateArgs,
1583 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1584 const CXXScopeSpec &SS, FieldDecl *Field,
1585 DeclAccessPair FoundDecl,
1586 const DeclarationNameInfo &MemberNameInfo) {
1587 // x.a is an l-value if 'a' has a reference type. Otherwise:
1588 // x.a is an l-value/x-value/pr-value if the base is (and note
1589 // that *x is always an l-value), except that if the base isn't
1590 // an ordinary object then we must have an rvalue.
1591 ExprValueKind VK = VK_LValue;
1592 ExprObjectKind OK = OK_Ordinary;
1594 if (BaseExpr->getObjectKind() == OK_Ordinary)
1595 VK = BaseExpr->getValueKind();
1599 if (VK != VK_RValue && Field->isBitField())
1602 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1603 QualType MemberType = Field->getType();
1604 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1605 MemberType = Ref->getPointeeType();
1608 QualType BaseType = BaseExpr->getType();
1609 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1611 Qualifiers BaseQuals = BaseType.getQualifiers();
1613 // GC attributes are never picked up by members.
1614 BaseQuals.removeObjCGCAttr();
1616 // CVR attributes from the base are picked up by members,
1617 // except that 'mutable' members don't pick up 'const'.
1618 if (Field->isMutable()) BaseQuals.removeConst();
1620 Qualifiers MemberQuals
1621 = S.Context.getCanonicalType(MemberType).getQualifiers();
1623 // TR 18037 does not allow fields to be declared with address spaces.
1624 assert(!MemberQuals.hasAddressSpace());
1626 Qualifiers Combined = BaseQuals + MemberQuals;
1627 if (Combined != MemberQuals)
1628 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1631 S.UnusedPrivateFields.remove(Field);
1634 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1636 if (Base.isInvalid())
1638 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
1639 /*TemplateKWLoc=*/SourceLocation(),
1640 Field, FoundDecl, MemberNameInfo,
1641 MemberType, VK, OK));
1644 /// Builds an implicit member access expression. The current context
1645 /// is known to be an instance method, and the given unqualified lookup
1646 /// set is known to contain only instance members, at least one of which
1647 /// is from an appropriate type.
1649 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1650 SourceLocation TemplateKWLoc,
1652 const TemplateArgumentListInfo *TemplateArgs,
1653 bool IsKnownInstance) {
1654 assert(!R.empty() && !R.isAmbiguous());
1656 SourceLocation loc = R.getNameLoc();
1658 // We may have found a field within an anonymous union or struct
1659 // (C++ [class.union]).
1660 // FIXME: template-ids inside anonymous structs?
1661 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1662 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1664 // If this is known to be an instance access, go ahead and build an
1665 // implicit 'this' expression now.
1666 // 'this' expression now.
1667 QualType ThisTy = getCurrentThisType();
1668 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1670 Expr *baseExpr = 0; // null signifies implicit access
1671 if (IsKnownInstance) {
1672 SourceLocation Loc = R.getNameLoc();
1673 if (SS.getRange().isValid())
1674 Loc = SS.getRange().getBegin();
1675 CheckCXXThisCapture(Loc);
1676 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1679 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1680 /*OpLoc*/ SourceLocation(),
1683 /*FirstQualifierInScope*/ 0,