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/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"
23 using namespace clang;
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()))
34 RecordDecl *RD = Record->getDefinition();
35 if (!RD) return false;
36 Record = cast<CXXRecordDecl>(RD);
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;
44 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
45 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
53 /// The reference is definitely not an instance member access.
56 /// The reference may be an implicit instance member access.
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,
63 /// The reference may be to an instance member, but it is invalid if
64 /// so, because the context is from an unrelated class.
67 /// The reference is definitely an implicit instance member access.
70 /// The reference may be to an unresolved using declaration.
73 /// The reference may be to an unresolved using declaration and the
74 /// context is not an instance method.
75 IMA_Unresolved_StaticContext,
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
80 IMA_Field_Uneval_Context,
82 /// All possible referrents are instance members and the current
83 /// context is not an instance method.
84 IMA_Error_StaticContext,
86 /// All possible referrents are instance members of an unrelated
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,
99 const LookupResult &R) {
100 assert(!R.empty() && (*R.begin())->isCXXClassMember());
102 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
104 bool isStaticContext =
105 (!isa<CXXMethodDecl>(DC) ||
106 cast<CXXMethodDecl>(DC)->isStatic());
108 // C++0x [expr.prim]p4:
109 // Otherwise, if a member-declarator declares a non-static data member
110 // of a class X, the expression this is a prvalue of type "pointer to X"
111 // within the optional brace-or-equal-initializer.
112 if (CurScope->getFlags() & Scope::ThisScope)
113 isStaticContext = false;
115 if (R.isUnresolvableResult())
116 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
118 // Collect all the declaring classes of instance members we find.
119 bool hasNonInstance = false;
120 bool isField = false;
121 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
122 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
125 if (D->isCXXInstanceMember()) {
126 if (dyn_cast<FieldDecl>(D))
129 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
130 Classes.insert(R->getCanonicalDecl());
133 hasNonInstance = true;
136 // If we didn't find any instance members, it can't be an implicit
141 bool IsCXX11UnevaluatedField = false;
142 if (SemaRef.getLangOpts().CPlusPlus0x && isField) {
143 // C++11 [expr.prim.general]p12:
144 // An id-expression that denotes a non-static data member or non-static
145 // member function of a class can only be used:
147 // - if that id-expression denotes a non-static data member and it
148 // appears in an unevaluated operand.
149 const Sema::ExpressionEvaluationContextRecord& record
150 = SemaRef.ExprEvalContexts.back();
151 if (record.Context == Sema::Unevaluated)
152 IsCXX11UnevaluatedField = true;
155 // If the current context is not an instance method, it can't be
156 // an implicit member reference.
157 if (isStaticContext) {
159 return IMA_Mixed_StaticContext;
161 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
162 : IMA_Error_StaticContext;
165 CXXRecordDecl *contextClass;
166 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
167 contextClass = MD->getParent()->getCanonicalDecl();
169 contextClass = cast<CXXRecordDecl>(DC);
171 // [class.mfct.non-static]p3:
172 // ...is used in the body of a non-static member function of class X,
173 // if name lookup (3.4.1) resolves the name in the id-expression to a
174 // non-static non-type member of some class C [...]
175 // ...if C is not X or a base class of X, the class member access expression
177 if (R.getNamingClass() &&
178 contextClass->getCanonicalDecl() !=
179 R.getNamingClass()->getCanonicalDecl() &&
180 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
181 return hasNonInstance ? IMA_Mixed_Unrelated :
182 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
185 // If we can prove that the current context is unrelated to all the
186 // declaring classes, it can't be an implicit member reference (in
187 // which case it's an error if any of those members are selected).
188 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
189 return hasNonInstance ? IMA_Mixed_Unrelated :
190 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
193 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
196 /// Diagnose a reference to a field with no object available.
197 static void diagnoseInstanceReference(Sema &SemaRef,
198 const CXXScopeSpec &SS,
200 const DeclarationNameInfo &nameInfo) {
201 SourceLocation Loc = nameInfo.getLoc();
202 SourceRange Range(Loc);
203 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
205 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
206 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
207 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
208 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
210 bool InStaticMethod = Method && Method->isStatic();
211 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
213 if (IsField && InStaticMethod)
214 // "invalid use of member 'x' in static member function"
215 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
216 << Range << nameInfo.getName();
217 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
218 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
219 // Unqualified lookup in a non-static member function found a member of an
221 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
222 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
224 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
225 << nameInfo.getName() << Range;
227 SemaRef.Diag(Loc, diag::err_member_call_without_object)
231 /// Builds an expression which might be an implicit member expression.
233 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
234 SourceLocation TemplateKWLoc,
236 const TemplateArgumentListInfo *TemplateArgs) {
237 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
239 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
242 case IMA_Mixed_Unrelated:
244 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
246 case IMA_Field_Uneval_Context:
247 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
248 << R.getLookupNameInfo().getName();
251 case IMA_Mixed_StaticContext:
252 case IMA_Unresolved_StaticContext:
253 if (TemplateArgs || TemplateKWLoc.isValid())
254 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
255 return BuildDeclarationNameExpr(SS, R, false);
257 case IMA_Error_StaticContext:
258 case IMA_Error_Unrelated:
259 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
260 R.getLookupNameInfo());
264 llvm_unreachable("unexpected instance member access kind");
267 /// Check an ext-vector component access expression.
269 /// VK should be set in advance to the value kind of the base
272 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
273 SourceLocation OpLoc, const IdentifierInfo *CompName,
274 SourceLocation CompLoc) {
275 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
278 // FIXME: This logic can be greatly simplified by splitting it along
279 // halving/not halving and reworking the component checking.
280 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
282 // The vector accessor can't exceed the number of elements.
283 const char *compStr = CompName->getNameStart();
285 // This flag determines whether or not the component is one of the four
286 // special names that indicate a subset of exactly half the elements are
288 bool HalvingSwizzle = false;
290 // This flag determines whether or not CompName has an 's' char prefix,
291 // indicating that it is a string of hex values to be used as vector indices.
292 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
294 bool HasRepeated = false;
295 bool HasIndex[16] = {};
299 // Check that we've found one of the special components, or that the component
300 // names must come from the same set.
301 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
302 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
303 HalvingSwizzle = true;
304 } else if (!HexSwizzle &&
305 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
307 if (HasIndex[Idx]) HasRepeated = true;
308 HasIndex[Idx] = true;
310 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
312 if (HexSwizzle) compStr++;
313 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
314 if (HasIndex[Idx]) HasRepeated = true;
315 HasIndex[Idx] = true;
320 if (!HalvingSwizzle && *compStr) {
321 // We didn't get to the end of the string. This means the component names
322 // didn't come from the same set *or* we encountered an illegal name.
323 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
324 << StringRef(compStr, 1) << SourceRange(CompLoc);
328 // Ensure no component accessor exceeds the width of the vector type it
330 if (!HalvingSwizzle) {
331 compStr = CompName->getNameStart();
337 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
338 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
339 << baseType << SourceRange(CompLoc);
345 // The component accessor looks fine - now we need to compute the actual type.
346 // The vector type is implied by the component accessor. For example,
347 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
348 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
349 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
350 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
351 : CompName->getLength();
356 return vecType->getElementType();
358 if (HasRepeated) VK = VK_RValue;
360 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
361 // Now look up the TypeDefDecl from the vector type. Without this,
362 // diagostics look bad. We want extended vector types to appear built-in.
363 for (Sema::ExtVectorDeclsType::iterator
364 I = S.ExtVectorDecls.begin(S.ExternalSource),
365 E = S.ExtVectorDecls.end();
367 if ((*I)->getUnderlyingType() == VT)
368 return S.Context.getTypedefType(*I);
371 return VT; // should never get here (a typedef type should always be found).
374 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
375 IdentifierInfo *Member,
377 ASTContext &Context) {
379 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
381 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
384 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
385 E = PDecl->protocol_end(); I != E; ++I) {
386 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
393 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
394 IdentifierInfo *Member,
396 ASTContext &Context) {
397 // Check protocols on qualified interfaces.
399 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
400 E = QIdTy->qual_end(); I != E; ++I) {
402 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
406 // Also must look for a getter or setter name which uses property syntax.
407 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
413 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
414 E = QIdTy->qual_end(); I != E; ++I) {
415 // Search in the protocol-qualifier list of current protocol.
416 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
426 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
427 bool IsArrow, SourceLocation OpLoc,
428 const CXXScopeSpec &SS,
429 SourceLocation TemplateKWLoc,
430 NamedDecl *FirstQualifierInScope,
431 const DeclarationNameInfo &NameInfo,
432 const TemplateArgumentListInfo *TemplateArgs) {
433 // Even in dependent contexts, try to diagnose base expressions with
434 // obviously wrong types, e.g.:
439 // In Obj-C++, however, the above expression is valid, since it could be
440 // accessing the 'f' property if T is an Obj-C interface. The extra check
441 // allows this, while still reporting an error if T is a struct pointer.
443 const PointerType *PT = BaseType->getAs<PointerType>();
444 if (PT && (!getLangOpts().ObjC1 ||
445 PT->getPointeeType()->isRecordType())) {
446 assert(BaseExpr && "cannot happen with implicit member accesses");
447 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
448 << BaseType << BaseExpr->getSourceRange();
453 assert(BaseType->isDependentType() ||
454 NameInfo.getName().isDependentName() ||
455 isDependentScopeSpecifier(SS));
457 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
458 // must have pointer type, and the accessed type is the pointee.
459 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
461 SS.getWithLocInContext(Context),
463 FirstQualifierInScope,
464 NameInfo, TemplateArgs));
467 /// We know that the given qualified member reference points only to
468 /// declarations which do not belong to the static type of the base
469 /// expression. Diagnose the problem.
470 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
473 const CXXScopeSpec &SS,
475 const DeclarationNameInfo &nameInfo) {
476 // If this is an implicit member access, use a different set of
479 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
481 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
482 << SS.getRange() << rep << BaseType;
485 // Check whether the declarations we found through a nested-name
486 // specifier in a member expression are actually members of the base
487 // type. The restriction here is:
490 // ... In these cases, the id-expression shall name a
491 // member of the class or of one of its base classes.
493 // So it's perfectly legitimate for the nested-name specifier to name
494 // an unrelated class, and for us to find an overload set including
495 // decls from classes which are not superclasses, as long as the decl
496 // we actually pick through overload resolution is from a superclass.
497 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
499 const CXXScopeSpec &SS,
500 const LookupResult &R) {
501 const RecordType *BaseRT = BaseType->getAs<RecordType>();
503 // We can't check this yet because the base type is still
505 assert(BaseType->isDependentType());
508 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
511 // If this is an implicit member reference and we find a
512 // non-instance member, it's not an error.
513 if (!BaseExpr && !(*I)->isCXXInstanceMember())
516 // Note that we use the DC of the decl, not the underlying decl.
517 DeclContext *DC = (*I)->getDeclContext();
518 while (DC->isTransparentContext())
519 DC = DC->getParent();
524 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
525 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
527 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
531 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
532 R.getRepresentativeDecl(),
533 R.getLookupNameInfo());
539 // Callback to only accept typo corrections that are either a ValueDecl or a
540 // FunctionTemplateDecl.
541 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
544 NamedDecl *ND = candidate.getCorrectionDecl();
545 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
552 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
553 SourceRange BaseRange, const RecordType *RTy,
554 SourceLocation OpLoc, CXXScopeSpec &SS,
555 bool HasTemplateArgs) {
556 RecordDecl *RDecl = RTy->getDecl();
557 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
558 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
562 if (HasTemplateArgs) {
563 // LookupTemplateName doesn't expect these both to exist simultaneously.
564 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
567 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
571 DeclContext *DC = RDecl;
573 // If the member name was a qualified-id, look into the
574 // nested-name-specifier.
575 DC = SemaRef.computeDeclContext(SS, false);
577 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
578 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
579 << SS.getRange() << DC;
583 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
585 if (!isa<TypeDecl>(DC)) {
586 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
587 << DC << SS.getRange();
592 // The record definition is complete, now look up the member.
593 SemaRef.LookupQualifiedName(R, DC);
598 // We didn't find anything with the given name, so try to correct
600 DeclarationName Name = R.getLookupName();
601 RecordMemberExprValidatorCCC Validator;
602 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
603 R.getLookupKind(), NULL,
606 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
607 std::string CorrectedStr(
608 Corrected.getAsString(SemaRef.getLangOpts()));
609 std::string CorrectedQuotedStr(
610 Corrected.getQuoted(SemaRef.getLangOpts()));
611 R.setLookupName(Corrected.getCorrection());
613 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
614 << Name << DC << CorrectedQuotedStr << SS.getRange()
615 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
616 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
617 << ND->getDeclName();
624 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
625 SourceLocation OpLoc, bool IsArrow,
627 SourceLocation TemplateKWLoc,
628 NamedDecl *FirstQualifierInScope,
629 const DeclarationNameInfo &NameInfo,
630 const TemplateArgumentListInfo *TemplateArgs) {
631 if (BaseType->isDependentType() ||
632 (SS.isSet() && isDependentScopeSpecifier(SS)))
633 return ActOnDependentMemberExpr(Base, BaseType,
635 SS, TemplateKWLoc, FirstQualifierInScope,
636 NameInfo, TemplateArgs);
638 LookupResult R(*this, NameInfo, LookupMemberName);
640 // Implicit member accesses.
642 QualType RecordTy = BaseType;
643 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
644 if (LookupMemberExprInRecord(*this, R, SourceRange(),
645 RecordTy->getAs<RecordType>(),
646 OpLoc, SS, TemplateArgs != 0))
649 // Explicit member accesses.
651 ExprResult BaseResult = Owned(Base);
653 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
654 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
656 if (BaseResult.isInvalid())
658 Base = BaseResult.take();
660 if (Result.isInvalid()) {
668 // LookupMemberExpr can modify Base, and thus change BaseType
669 BaseType = Base->getType();
672 return BuildMemberReferenceExpr(Base, BaseType,
673 OpLoc, IsArrow, SS, TemplateKWLoc,
674 FirstQualifierInScope, R, TemplateArgs);
678 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
679 const CXXScopeSpec &SS, FieldDecl *Field,
680 DeclAccessPair FoundDecl,
681 const DeclarationNameInfo &MemberNameInfo);
684 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
686 IndirectFieldDecl *indirectField,
687 Expr *baseObjectExpr,
688 SourceLocation opLoc) {
689 // First, build the expression that refers to the base object.
691 bool baseObjectIsPointer = false;
692 Qualifiers baseQuals;
694 // Case 1: the base of the indirect field is not a field.
695 VarDecl *baseVariable = indirectField->getVarDecl();
696 CXXScopeSpec EmptySS;
698 assert(baseVariable->getType()->isRecordType());
700 // In principle we could have a member access expression that
701 // accesses an anonymous struct/union that's a static member of
702 // the base object's class. However, under the current standard,
703 // static data members cannot be anonymous structs or unions.
704 // Supporting this is as easy as building a MemberExpr here.
705 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
707 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
710 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
711 if (result.isInvalid()) return ExprError();
713 baseObjectExpr = result.take();
714 baseObjectIsPointer = false;
715 baseQuals = baseObjectExpr->getType().getQualifiers();
717 // Case 2: the base of the indirect field is a field and the user
718 // wrote a member expression.
719 } else if (baseObjectExpr) {
720 // The caller provided the base object expression. Determine
721 // whether its a pointer and whether it adds any qualifiers to the
722 // anonymous struct/union fields we're looking into.
723 QualType objectType = baseObjectExpr->getType();
725 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
726 baseObjectIsPointer = true;
727 objectType = ptr->getPointeeType();
729 baseObjectIsPointer = false;
731 baseQuals = objectType.getQualifiers();
733 // Case 3: the base of the indirect field is a field and we should
734 // build an implicit member access.
736 // We've found a member of an anonymous struct/union that is
737 // inside a non-anonymous struct/union, so in a well-formed
738 // program our base object expression is "this".
739 QualType ThisTy = getCurrentThisType();
740 if (ThisTy.isNull()) {
741 Diag(loc, diag::err_invalid_member_use_in_static_method)
742 << indirectField->getDeclName();
746 // Our base object expression is "this".
747 CheckCXXThisCapture(loc);
749 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
750 baseObjectIsPointer = true;
751 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
754 // Build the implicit member references to the field of the
755 // anonymous struct/union.
756 Expr *result = baseObjectExpr;
757 IndirectFieldDecl::chain_iterator
758 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
760 // Build the first member access in the chain with full information.
762 FieldDecl *field = cast<FieldDecl>(*FI);
764 // FIXME: use the real found-decl info!
765 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
767 // Make a nameInfo that properly uses the anonymous name.
768 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
770 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
771 EmptySS, field, foundDecl,
772 memberNameInfo).take();
773 baseObjectIsPointer = false;
775 // FIXME: check qualified member access
778 // In all cases, we should now skip the first declaration in the chain.
782 FieldDecl *field = cast<FieldDecl>(*FI++);
784 // FIXME: these are somewhat meaningless
785 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
786 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
788 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
789 (FI == FEnd? SS : EmptySS), field,
790 foundDecl, memberNameInfo).take();
793 return Owned(result);
796 /// \brief Build a MemberExpr AST node.
797 static MemberExpr *BuildMemberExpr(Sema &SemaRef,
798 ASTContext &C, Expr *Base, bool isArrow,
799 const CXXScopeSpec &SS,
800 SourceLocation TemplateKWLoc,
802 DeclAccessPair FoundDecl,
803 const DeclarationNameInfo &MemberNameInfo,
805 ExprValueKind VK, ExprObjectKind OK,
806 const TemplateArgumentListInfo *TemplateArgs = 0) {
807 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
809 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
810 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
811 TemplateArgs, Ty, VK, OK);
812 SemaRef.MarkMemberReferenced(E);
817 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
818 SourceLocation OpLoc, bool IsArrow,
819 const CXXScopeSpec &SS,
820 SourceLocation TemplateKWLoc,
821 NamedDecl *FirstQualifierInScope,
823 const TemplateArgumentListInfo *TemplateArgs,
824 bool SuppressQualifierCheck) {
825 QualType BaseType = BaseExprType;
827 assert(BaseType->isPointerType());
828 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
830 R.setBaseObjectType(BaseType);
832 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
833 DeclarationName MemberName = MemberNameInfo.getName();
834 SourceLocation MemberLoc = MemberNameInfo.getLoc();
840 // Rederive where we looked up.
841 DeclContext *DC = (SS.isSet()
842 ? computeDeclContext(SS, false)
843 : BaseType->getAs<RecordType>()->getDecl());
845 Diag(R.getNameLoc(), diag::err_no_member)
847 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
851 // Diagnose lookups that find only declarations from a non-base
852 // type. This is possible for either qualified lookups (which may
853 // have been qualified with an unrelated type) or implicit member
854 // expressions (which were found with unqualified lookup and thus
855 // may have come from an enclosing scope). Note that it's okay for
856 // lookup to find declarations from a non-base type as long as those
857 // aren't the ones picked by overload resolution.
858 if ((SS.isSet() || !BaseExpr ||
859 (isa<CXXThisExpr>(BaseExpr) &&
860 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
861 !SuppressQualifierCheck &&
862 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
865 // Construct an unresolved result if we in fact got an unresolved
867 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
868 // Suppress any lookup-related diagnostics; we'll do these when we
870 R.suppressDiagnostics();
872 UnresolvedMemberExpr *MemExpr
873 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
874 BaseExpr, BaseExprType,
876 SS.getWithLocInContext(Context),
877 TemplateKWLoc, MemberNameInfo,
878 TemplateArgs, R.begin(), R.end());
880 return Owned(MemExpr);
883 assert(R.isSingleResult());
884 DeclAccessPair FoundDecl = R.begin().getPair();
885 NamedDecl *MemberDecl = R.getFoundDecl();
887 // FIXME: diagnose the presence of template arguments now.
889 // If the decl being referenced had an error, return an error for this
890 // sub-expr without emitting another error, in order to avoid cascading
892 if (MemberDecl->isInvalidDecl())
895 // Handle the implicit-member-access case.
897 // If this is not an instance member, convert to a non-member access.
898 if (!MemberDecl->isCXXInstanceMember())
899 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
901 SourceLocation Loc = R.getNameLoc();
902 if (SS.getRange().isValid())
903 Loc = SS.getRange().getBegin();
904 CheckCXXThisCapture(Loc);
905 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
908 bool ShouldCheckUse = true;
909 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
910 // Don't diagnose the use of a virtual member function unless it's
911 // explicitly qualified.
912 if (MD->isVirtual() && !SS.isSet())
913 ShouldCheckUse = false;
916 // Check the use of this member.
917 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
922 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
923 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
924 SS, FD, FoundDecl, MemberNameInfo);
926 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
927 // We may have found a field within an anonymous union or struct
928 // (C++ [class.union]).
929 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
932 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
933 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
934 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
935 Var->getType().getNonReferenceType(),
936 VK_LValue, OK_Ordinary));
939 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
940 ExprValueKind valueKind;
942 if (MemberFn->isInstance()) {
943 valueKind = VK_RValue;
944 type = Context.BoundMemberTy;
946 valueKind = VK_LValue;
947 type = MemberFn->getType();
950 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
951 TemplateKWLoc, MemberFn, FoundDecl,
952 MemberNameInfo, type, valueKind,
955 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
957 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
958 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
959 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
960 Enum->getType(), VK_RValue, OK_Ordinary));
965 // We found something that we didn't expect. Complain.
966 if (isa<TypeDecl>(MemberDecl))
967 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
968 << MemberName << BaseType << int(IsArrow);
970 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
971 << MemberName << BaseType << int(IsArrow);
973 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
975 R.suppressDiagnostics();
979 /// Given that normal member access failed on the given expression,
980 /// and given that the expression's type involves builtin-id or
981 /// builtin-Class, decide whether substituting in the redefinition
982 /// types would be profitable. The redefinition type is whatever
983 /// this translation unit tried to typedef to id/Class; we store
984 /// it to the side and then re-use it in places like this.
985 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
986 const ObjCObjectPointerType *opty
987 = base.get()->getType()->getAs<ObjCObjectPointerType>();
988 if (!opty) return false;
990 const ObjCObjectType *ty = opty->getObjectType();
993 if (ty->isObjCId()) {
994 redef = S.Context.getObjCIdRedefinitionType();
995 } else if (ty->isObjCClass()) {
996 redef = S.Context.getObjCClassRedefinitionType();
1001 // Do the substitution as long as the redefinition type isn't just a
1002 // possibly-qualified pointer to builtin-id or builtin-Class again.
1003 opty = redef->getAs<ObjCObjectPointerType>();
1004 if (opty && !opty->getObjectType()->getInterface() != 0)
1007 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1011 static bool isRecordType(QualType T) {
1012 return T->isRecordType();
1014 static bool isPointerToRecordType(QualType T) {
1015 if (const PointerType *PT = T->getAs<PointerType>())
1016 return PT->getPointeeType()->isRecordType();
1020 /// Perform conversions on the LHS of a member access expression.
1022 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1023 if (IsArrow && !Base->getType()->isFunctionType())
1024 return DefaultFunctionArrayLvalueConversion(Base);
1026 return CheckPlaceholderExpr(Base);
1029 /// Look up the given member of the given non-type-dependent
1030 /// expression. This can return in one of two ways:
1031 /// * If it returns a sentinel null-but-valid result, the caller will
1032 /// assume that lookup was performed and the results written into
1033 /// the provided structure. It will take over from there.
1034 /// * Otherwise, the returned expression will be produced in place of
1035 /// an ordinary member expression.
1037 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1038 /// fixed for ObjC++.
1040 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1041 bool &IsArrow, SourceLocation OpLoc,
1043 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1044 assert(BaseExpr.get() && "no base expression");
1046 // Perform default conversions.
1047 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
1048 if (BaseExpr.isInvalid())
1051 QualType BaseType = BaseExpr.get()->getType();
1052 assert(!BaseType->isDependentType());
1054 DeclarationName MemberName = R.getLookupName();
1055 SourceLocation MemberLoc = R.getNameLoc();
1057 // For later type-checking purposes, turn arrow accesses into dot
1058 // accesses. The only access type we support that doesn't follow
1059 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1060 // and those never use arrows, so this is unaffected.
1062 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1063 BaseType = Ptr->getPointeeType();
1064 else if (const ObjCObjectPointerType *Ptr
1065 = BaseType->getAs<ObjCObjectPointerType>())
1066 BaseType = Ptr->getPointeeType();
1067 else if (BaseType->isRecordType()) {
1068 // Recover from arrow accesses to records, e.g.:
1069 // struct MyRecord foo;
1071 // This is actually well-formed in C++ if MyRecord has an
1072 // overloaded operator->, but that should have been dealt with
1074 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1075 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1076 << FixItHint::CreateReplacement(OpLoc, ".");
1078 } else if (BaseType->isFunctionType()) {
1081 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1082 << BaseType << BaseExpr.get()->getSourceRange();
1087 // Handle field access to simple records.
1088 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1089 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1090 RTy, OpLoc, SS, HasTemplateArgs))
1093 // Returning valid-but-null is how we indicate to the caller that
1094 // the lookup result was filled in.
1095 return Owned((Expr*) 0);
1098 // Handle ivar access to Objective-C objects.
1099 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1100 if (!SS.isEmpty() && !SS.isInvalid()) {
1101 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1102 << 1 << SS.getScopeRep()
1103 << FixItHint::CreateRemoval(SS.getRange());
1107 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1109 // There are three cases for the base type:
1110 // - builtin id (qualified or unqualified)
1111 // - builtin Class (qualified or unqualified)
1113 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1115 if (getLangOpts().ObjCAutoRefCount &&
1116 (OTy->isObjCId() || OTy->isObjCClass()))
1118 // There's an implicit 'isa' ivar on all objects.
1119 // But we only actually find it this way on objects of type 'id',
1121 if (OTy->isObjCId() && Member->isStr("isa")) {
1122 Diag(MemberLoc, diag::warn_objc_isa_use);
1123 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1124 Context.getObjCClassType()));
1127 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1128 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1129 ObjCImpDecl, HasTemplateArgs);
1133 if (RequireCompleteType(OpLoc, BaseType,
1134 PDiag(diag::err_typecheck_incomplete_tag)
1135 << BaseExpr.get()->getSourceRange()))
1138 ObjCInterfaceDecl *ClassDeclared = 0;
1139 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1142 // Attempt to correct for typos in ivar names.
1143 DeclFilterCCC<ObjCIvarDecl> Validator;
1144 Validator.IsObjCIvarLookup = IsArrow;
1145 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1146 LookupMemberName, NULL, NULL,
1147 Validator, IDecl)) {
1148 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1149 Diag(R.getNameLoc(),
1150 diag::err_typecheck_member_reference_ivar_suggest)
1151 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1152 << FixItHint::CreateReplacement(R.getNameLoc(),
1153 IV->getNameAsString());
1154 Diag(IV->getLocation(), diag::note_previous_decl)
1155 << IV->getDeclName();
1157 // Figure out the class that declares the ivar.
1158 assert(!ClassDeclared);
1159 Decl *D = cast<Decl>(IV->getDeclContext());
1160 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1161 D = CAT->getClassInterface();
1162 ClassDeclared = cast<ObjCInterfaceDecl>(D);
1164 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1166 diag::err_property_found_suggest)
1167 << Member << BaseExpr.get()->getType()
1168 << FixItHint::CreateReplacement(OpLoc, ".");
1172 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1173 << IDecl->getDeclName() << MemberName
1174 << BaseExpr.get()->getSourceRange();
1179 assert(ClassDeclared);
1181 // If the decl being referenced had an error, return an error for this
1182 // sub-expr without emitting another error, in order to avoid cascading
1184 if (IV->isInvalidDecl())
1187 // Check whether we can reference this field.
1188 if (DiagnoseUseOfDecl(IV, MemberLoc))
1190 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1191 IV->getAccessControl() != ObjCIvarDecl::Package) {
1192 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1193 if (ObjCMethodDecl *MD = getCurMethodDecl())
1194 ClassOfMethodDecl = MD->getClassInterface();
1195 else if (ObjCImpDecl && getCurFunctionDecl()) {
1196 // Case of a c-function declared inside an objc implementation.
1197 // FIXME: For a c-style function nested inside an objc implementation
1198 // class, there is no implementation context available, so we pass
1199 // down the context as argument to this routine. Ideally, this context
1200 // need be passed down in the AST node and somehow calculated from the
1201 // AST for a function decl.
1202 if (ObjCImplementationDecl *IMPD =
1203 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1204 ClassOfMethodDecl = IMPD->getClassInterface();
1205 else if (ObjCCategoryImplDecl* CatImplClass =
1206 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1207 ClassOfMethodDecl = CatImplClass->getClassInterface();
1209 if (!getLangOpts().DebuggerSupport) {
1210 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1211 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1212 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1213 Diag(MemberLoc, diag::error_private_ivar_access)
1214 << IV->getDeclName();
1215 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1217 Diag(MemberLoc, diag::error_protected_ivar_access)
1218 << IV->getDeclName();
1221 if (getLangOpts().ObjCAutoRefCount) {
1222 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1223 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1224 if (UO->getOpcode() == UO_Deref)
1225 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1227 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1228 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1229 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1232 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1233 MemberLoc, BaseExpr.take(),
1237 // Objective-C property access.
1238 const ObjCObjectPointerType *OPT;
1239 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1240 if (!SS.isEmpty() && !SS.isInvalid()) {
1241 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1242 << 0 << SS.getScopeRep()
1243 << FixItHint::CreateRemoval(SS.getRange());
1247 // This actually uses the base as an r-value.
1248 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1249 if (BaseExpr.isInvalid())
1252 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1254 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1256 const ObjCObjectType *OT = OPT->getObjectType();
1258 // id, with and without qualifiers.
1259 if (OT->isObjCId()) {
1260 // Check protocols on qualified interfaces.
1261 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1262 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1263 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1264 // Check the use of this declaration
1265 if (DiagnoseUseOfDecl(PD, MemberLoc))
1268 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1269 Context.PseudoObjectTy,
1276 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1277 // Check the use of this method.
1278 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1280 Selector SetterSel =
1281 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1282 PP.getSelectorTable(), Member);
1283 ObjCMethodDecl *SMD = 0;
1284 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1285 SetterSel, Context))
1286 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1288 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1289 Context.PseudoObjectTy,
1290 VK_LValue, OK_ObjCProperty,
1291 MemberLoc, BaseExpr.take()));
1294 // Use of id.member can only be for a property reference. Do not
1295 // use the 'id' redefinition in this case.
1296 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1297 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1298 ObjCImpDecl, HasTemplateArgs);
1300 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1301 << MemberName << BaseType);
1304 // 'Class', unqualified only.
1305 if (OT->isObjCClass()) {
1306 // Only works in a method declaration (??!).
1307 ObjCMethodDecl *MD = getCurMethodDecl();
1309 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1310 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1311 ObjCImpDecl, HasTemplateArgs);
1316 // Also must look for a getter name which uses property syntax.
1317 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1318 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1319 ObjCMethodDecl *Getter;
1320 if ((Getter = IFace->lookupClassMethod(Sel))) {
1321 // Check the use of this method.
1322 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1325 Getter = IFace->lookupPrivateMethod(Sel, false);
1326 // If we found a getter then this may be a valid dot-reference, we
1327 // will look for the matching setter, in case it is needed.
1328 Selector SetterSel =
1329 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1330 PP.getSelectorTable(), Member);
1331 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1333 // If this reference is in an @implementation, also check for 'private'
1335 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1337 // Look through local category implementations associated with the class.
1339 Setter = IFace->getCategoryClassMethod(SetterSel);
1341 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1344 if (Getter || Setter) {
1345 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1346 Context.PseudoObjectTy,
1347 VK_LValue, OK_ObjCProperty,
1348 MemberLoc, BaseExpr.take()));
1351 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1352 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1353 ObjCImpDecl, HasTemplateArgs);
1355 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1356 << MemberName << BaseType);
1359 // Normal property access.
1360 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1361 MemberName, MemberLoc,
1362 SourceLocation(), QualType(), false);
1365 // Handle 'field access' to vectors, such as 'V.xx'.
1366 if (BaseType->isExtVectorType()) {
1367 // FIXME: this expr should store IsArrow.
1368 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1369 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1370 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1375 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1376 *Member, MemberLoc));
1379 // Adjust builtin-sel to the appropriate redefinition type if that's
1380 // not just a pointer to builtin-sel again.
1382 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1383 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1384 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1385 Context.getObjCSelRedefinitionType(),
1387 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1388 ObjCImpDecl, HasTemplateArgs);
1394 // Recover from dot accesses to pointers, e.g.:
1397 // This is actually well-formed in two cases:
1398 // - 'type' is an Objective C type
1399 // - 'bar' is a pseudo-destructor name which happens to refer to
1400 // the appropriate pointer type
1401 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1402 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1403 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1404 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1405 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1406 << FixItHint::CreateReplacement(OpLoc, "->");
1408 // Recurse as an -> access.
1410 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1411 ObjCImpDecl, HasTemplateArgs);
1415 // If the user is trying to apply -> or . to a function name, it's probably
1416 // because they forgot parentheses to call that function.
1417 if (tryToRecoverWithCall(BaseExpr,
1418 PDiag(diag::err_member_reference_needs_call),
1420 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1421 if (BaseExpr.isInvalid())
1423 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1424 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1425 ObjCImpDecl, HasTemplateArgs);
1428 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1429 << BaseType << BaseExpr.get()->getSourceRange();
1434 /// The main callback when the parser finds something like
1435 /// expression . [nested-name-specifier] identifier
1436 /// expression -> [nested-name-specifier] identifier
1437 /// where 'identifier' encompasses a fairly broad spectrum of
1438 /// possibilities, including destructor and operator references.
1440 /// \param OpKind either tok::arrow or tok::period
1441 /// \param HasTrailingLParen whether the next token is '(', which
1442 /// is used to diagnose mis-uses of special members that can
1444 /// \param ObjCImpDecl the current ObjC @implementation decl;
1445 /// this is an ugly hack around the fact that ObjC @implementations
1446 /// aren't properly put in the context chain
1447 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1448 SourceLocation OpLoc,
1449 tok::TokenKind OpKind,
1451 SourceLocation TemplateKWLoc,
1454 bool HasTrailingLParen) {
1455 if (SS.isSet() && SS.isInvalid())
1458 // Warn about the explicit constructor calls Microsoft extension.
1459 if (getLangOpts().MicrosoftExt &&
1460 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1461 Diag(Id.getSourceRange().getBegin(),
1462 diag::ext_ms_explicit_constructor_call);
1464 TemplateArgumentListInfo TemplateArgsBuffer;
1466 // Decompose the name into its component parts.
1467 DeclarationNameInfo NameInfo;
1468 const TemplateArgumentListInfo *TemplateArgs;
1469 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1470 NameInfo, TemplateArgs);
1472 DeclarationName Name = NameInfo.getName();
1473 bool IsArrow = (OpKind == tok::arrow);
1475 NamedDecl *FirstQualifierInScope
1476 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1477 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1479 // This is a postfix expression, so get rid of ParenListExprs.
1480 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1481 if (Result.isInvalid()) return ExprError();
1482 Base = Result.take();
1484 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1485 isDependentScopeSpecifier(SS)) {
1486 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1488 SS, TemplateKWLoc, FirstQualifierInScope,
1489 NameInfo, TemplateArgs);
1491 LookupResult R(*this, NameInfo, LookupMemberName);
1492 ExprResult BaseResult = Owned(Base);
1493 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1494 SS, ObjCImpDecl, TemplateArgs != 0);
1495 if (BaseResult.isInvalid())
1497 Base = BaseResult.take();
1499 if (Result.isInvalid()) {
1505 // The only way a reference to a destructor can be used is to
1506 // immediately call it, which falls into this case. If the
1507 // next token is not a '(', produce a diagnostic and build the
1509 if (!HasTrailingLParen &&
1510 Id.getKind() == UnqualifiedId::IK_DestructorName)
1511 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1513 return move(Result);
1516 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1517 OpLoc, IsArrow, SS, TemplateKWLoc,
1518 FirstQualifierInScope, R, TemplateArgs);
1521 return move(Result);
1525 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1526 const CXXScopeSpec &SS, FieldDecl *Field,
1527 DeclAccessPair FoundDecl,
1528 const DeclarationNameInfo &MemberNameInfo) {
1529 // x.a is an l-value if 'a' has a reference type. Otherwise:
1530 // x.a is an l-value/x-value/pr-value if the base is (and note
1531 // that *x is always an l-value), except that if the base isn't
1532 // an ordinary object then we must have an rvalue.
1533 ExprValueKind VK = VK_LValue;
1534 ExprObjectKind OK = OK_Ordinary;
1536 if (BaseExpr->getObjectKind() == OK_Ordinary)
1537 VK = BaseExpr->getValueKind();
1541 if (VK != VK_RValue && Field->isBitField())
1544 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1545 QualType MemberType = Field->getType();
1546 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1547 MemberType = Ref->getPointeeType();
1550 QualType BaseType = BaseExpr->getType();
1551 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1553 Qualifiers BaseQuals = BaseType.getQualifiers();
1555 // GC attributes are never picked up by members.
1556 BaseQuals.removeObjCGCAttr();
1558 // CVR attributes from the base are picked up by members,
1559 // except that 'mutable' members don't pick up 'const'.
1560 if (Field->isMutable()) BaseQuals.removeConst();
1562 Qualifiers MemberQuals
1563 = S.Context.getCanonicalType(MemberType).getQualifiers();
1565 // TR 18037 does not allow fields to be declared with address spaces.
1566 assert(!MemberQuals.hasAddressSpace());
1568 Qualifiers Combined = BaseQuals + MemberQuals;
1569 if (Combined != MemberQuals)
1570 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1574 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1576 if (Base.isInvalid())
1578 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
1579 /*TemplateKWLoc=*/SourceLocation(),
1580 Field, FoundDecl, MemberNameInfo,
1581 MemberType, VK, OK));
1584 /// Builds an implicit member access expression. The current context
1585 /// is known to be an instance method, and the given unqualified lookup
1586 /// set is known to contain only instance members, at least one of which
1587 /// is from an appropriate type.
1589 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1590 SourceLocation TemplateKWLoc,
1592 const TemplateArgumentListInfo *TemplateArgs,
1593 bool IsKnownInstance) {
1594 assert(!R.empty() && !R.isAmbiguous());
1596 SourceLocation loc = R.getNameLoc();
1598 // We may have found a field within an anonymous union or struct
1599 // (C++ [class.union]).
1600 // FIXME: template-ids inside anonymous structs?
1601 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1602 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1604 // If this is known to be an instance access, go ahead and build an
1605 // implicit 'this' expression now.
1606 // 'this' expression now.
1607 QualType ThisTy = getCurrentThisType();
1608 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1610 Expr *baseExpr = 0; // null signifies implicit access
1611 if (IsKnownInstance) {
1612 SourceLocation Loc = R.getNameLoc();
1613 if (SS.getRange().isValid())
1614 Loc = SS.getRange().getBegin();
1615 CheckCXXThisCapture(Loc);
1616 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1619 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1620 /*OpLoc*/ SourceLocation(),
1623 /*FirstQualifierInScope*/ 0,