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/AST/DeclCXX.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/DeclTemplate.h"
17 #include "clang/AST/ExprCXX.h"
18 #include "clang/AST/ExprObjC.h"
19 #include "clang/Lex/Preprocessor.h"
20 #include "clang/Sema/Lookup.h"
21 #include "clang/Sema/Scope.h"
22 #include "clang/Sema/ScopeInfo.h"
24 using namespace clang;
27 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
28 static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
29 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
30 return !Bases.count(Base->getCanonicalDecl());
33 /// Determines if the given class is provably not derived from all of
34 /// the prospective base classes.
35 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
36 const BaseSet &Bases) {
37 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
38 return BaseIsNotInSet(Record, BasesPtr) &&
39 Record->forallBases(BaseIsNotInSet, BasesPtr);
43 /// The reference is definitely not an instance member access.
46 /// The reference may be an implicit instance member access.
49 /// The reference may be to an instance member, but it might be invalid if
50 /// so, because the context is not an instance method.
51 IMA_Mixed_StaticContext,
53 /// The reference may be to an instance member, but it is invalid if
54 /// so, because the context is from an unrelated class.
57 /// The reference is definitely an implicit instance member access.
60 /// The reference may be to an unresolved using declaration.
63 /// The reference is a contextually-permitted abstract member reference.
66 /// The reference may be to an unresolved using declaration and the
67 /// context is not an instance method.
68 IMA_Unresolved_StaticContext,
70 // The reference refers to a field which is not a member of the containing
71 // class, which is allowed because we're in C++11 mode and the context is
73 IMA_Field_Uneval_Context,
75 /// All possible referrents are instance members and the current
76 /// context is not an instance method.
77 IMA_Error_StaticContext,
79 /// All possible referrents are instance members of an unrelated
84 /// The given lookup names class member(s) and is not being used for
85 /// an address-of-member expression. Classify the type of access
86 /// according to whether it's possible that this reference names an
87 /// instance member. This is best-effort in dependent contexts; it is okay to
88 /// conservatively answer "yes", in which case some errors will simply
89 /// not be caught until template-instantiation.
90 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
92 const LookupResult &R) {
93 assert(!R.empty() && (*R.begin())->isCXXClassMember());
95 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
97 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
98 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
100 if (R.isUnresolvableResult())
101 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
103 // Collect all the declaring classes of instance members we find.
104 bool hasNonInstance = false;
105 bool isField = false;
107 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
110 if (D->isCXXInstanceMember()) {
111 if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
112 || dyn_cast<IndirectFieldDecl>(D))
115 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
116 Classes.insert(R->getCanonicalDecl());
119 hasNonInstance = true;
122 // If we didn't find any instance members, it can't be an implicit
127 // C++11 [expr.prim.general]p12:
128 // An id-expression that denotes a non-static data member or non-static
129 // member function of a class can only be used:
131 // - if that id-expression denotes a non-static data member and it
132 // appears in an unevaluated operand.
134 // This rule is specific to C++11. However, we also permit this form
135 // in unevaluated inline assembly operands, like the operand to a SIZE.
136 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
137 assert(!AbstractInstanceResult);
138 switch (SemaRef.ExprEvalContexts.back().Context) {
139 case Sema::Unevaluated:
140 if (isField && SemaRef.getLangOpts().CPlusPlus11)
141 AbstractInstanceResult = IMA_Field_Uneval_Context;
144 case Sema::UnevaluatedAbstract:
145 AbstractInstanceResult = IMA_Abstract;
148 case Sema::ConstantEvaluated:
149 case Sema::PotentiallyEvaluated:
150 case Sema::PotentiallyEvaluatedIfUsed:
154 // If the current context is not an instance method, it can't be
155 // an implicit member reference.
156 if (isStaticContext) {
158 return IMA_Mixed_StaticContext;
160 return AbstractInstanceResult ? AbstractInstanceResult
161 : IMA_Error_StaticContext;
164 CXXRecordDecl *contextClass;
165 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
166 contextClass = MD->getParent()->getCanonicalDecl();
168 contextClass = cast<CXXRecordDecl>(DC);
170 // [class.mfct.non-static]p3:
171 // ...is used in the body of a non-static member function of class X,
172 // if name lookup (3.4.1) resolves the name in the id-expression to a
173 // non-static non-type member of some class C [...]
174 // ...if C is not X or a base class of X, the class member access expression
176 if (R.getNamingClass() &&
177 contextClass->getCanonicalDecl() !=
178 R.getNamingClass()->getCanonicalDecl()) {
179 // If the naming class is not the current context, this was a qualified
180 // member name lookup, and it's sufficient to check that we have the naming
181 // class as a base class.
183 Classes.insert(R.getNamingClass()->getCanonicalDecl());
186 // If we can prove that the current context is unrelated to all the
187 // declaring classes, it can't be an implicit member reference (in
188 // which case it's an error if any of those members are selected).
189 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
190 return hasNonInstance ? IMA_Mixed_Unrelated :
191 AbstractInstanceResult ? AbstractInstanceResult :
194 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
197 /// Diagnose a reference to a field with no object available.
198 static void diagnoseInstanceReference(Sema &SemaRef,
199 const CXXScopeSpec &SS,
201 const DeclarationNameInfo &nameInfo) {
202 SourceLocation Loc = nameInfo.getLoc();
203 SourceRange Range(Loc);
204 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
206 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
207 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
208 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
209 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
211 bool InStaticMethod = Method && Method->isStatic();
212 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
214 if (IsField && InStaticMethod)
215 // "invalid use of member 'x' in static member function"
216 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
217 << Range << nameInfo.getName();
218 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
219 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
220 // Unqualified lookup in a non-static member function found a member of an
222 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
223 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
226 << nameInfo.getName() << Range;
228 SemaRef.Diag(Loc, diag::err_member_call_without_object)
232 /// Builds an expression which might be an implicit member expression.
234 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
235 SourceLocation TemplateKWLoc,
237 const TemplateArgumentListInfo *TemplateArgs) {
238 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
240 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
243 case IMA_Mixed_Unrelated:
245 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
247 case IMA_Field_Uneval_Context:
248 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
249 << R.getLookupNameInfo().getName();
253 case IMA_Mixed_StaticContext:
254 case IMA_Unresolved_StaticContext:
255 if (TemplateArgs || TemplateKWLoc.isValid())
256 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
257 return BuildDeclarationNameExpr(SS, R, false);
259 case IMA_Error_StaticContext:
260 case IMA_Error_Unrelated:
261 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
262 R.getLookupNameInfo());
266 llvm_unreachable("unexpected instance member access kind");
269 /// Check an ext-vector component access expression.
271 /// VK should be set in advance to the value kind of the base
274 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
275 SourceLocation OpLoc, const IdentifierInfo *CompName,
276 SourceLocation CompLoc) {
277 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
280 // FIXME: This logic can be greatly simplified by splitting it along
281 // halving/not halving and reworking the component checking.
282 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
284 // The vector accessor can't exceed the number of elements.
285 const char *compStr = CompName->getNameStart();
287 // This flag determines whether or not the component is one of the four
288 // special names that indicate a subset of exactly half the elements are
290 bool HalvingSwizzle = false;
292 // This flag determines whether or not CompName has an 's' char prefix,
293 // indicating that it is a string of hex values to be used as vector indices.
294 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
296 bool HasRepeated = false;
297 bool HasIndex[16] = {};
301 // Check that we've found one of the special components, or that the component
302 // names must come from the same set.
303 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
304 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
305 HalvingSwizzle = true;
306 } else if (!HexSwizzle &&
307 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
309 if (HasIndex[Idx]) HasRepeated = true;
310 HasIndex[Idx] = true;
312 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
314 if (HexSwizzle) compStr++;
315 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
316 if (HasIndex[Idx]) HasRepeated = true;
317 HasIndex[Idx] = true;
322 if (!HalvingSwizzle && *compStr) {
323 // We didn't get to the end of the string. This means the component names
324 // didn't come from the same set *or* we encountered an illegal name.
325 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
326 << StringRef(compStr, 1) << SourceRange(CompLoc);
330 // Ensure no component accessor exceeds the width of the vector type it
332 if (!HalvingSwizzle) {
333 compStr = CompName->getNameStart();
339 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
340 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
341 << baseType << SourceRange(CompLoc);
347 // The component accessor looks fine - now we need to compute the actual type.
348 // The vector type is implied by the component accessor. For example,
349 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
350 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
351 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
352 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
353 : CompName->getLength();
358 return vecType->getElementType();
360 if (HasRepeated) VK = VK_RValue;
362 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
363 // Now look up the TypeDefDecl from the vector type. Without this,
364 // diagostics look bad. We want extended vector types to appear built-in.
365 for (Sema::ExtVectorDeclsType::iterator
366 I = S.ExtVectorDecls.begin(S.getExternalSource()),
367 E = S.ExtVectorDecls.end();
369 if ((*I)->getUnderlyingType() == VT)
370 return S.Context.getTypedefType(*I);
373 return VT; // should never get here (a typedef type should always be found).
376 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
377 IdentifierInfo *Member,
379 ASTContext &Context) {
381 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
383 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
386 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
387 E = PDecl->protocol_end(); I != E; ++I) {
388 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
395 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
396 IdentifierInfo *Member,
398 ASTContext &Context) {
399 // Check protocols on qualified interfaces.
401 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
402 E = QIdTy->qual_end(); I != E; ++I) {
404 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
408 // Also must look for a getter or setter name which uses property syntax.
409 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
415 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
416 E = QIdTy->qual_end(); I != E; ++I) {
417 // Search in the protocol-qualifier list of current protocol.
418 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
428 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
429 bool IsArrow, SourceLocation OpLoc,
430 const CXXScopeSpec &SS,
431 SourceLocation TemplateKWLoc,
432 NamedDecl *FirstQualifierInScope,
433 const DeclarationNameInfo &NameInfo,
434 const TemplateArgumentListInfo *TemplateArgs) {
435 // Even in dependent contexts, try to diagnose base expressions with
436 // obviously wrong types, e.g.:
441 // In Obj-C++, however, the above expression is valid, since it could be
442 // accessing the 'f' property if T is an Obj-C interface. The extra check
443 // allows this, while still reporting an error if T is a struct pointer.
445 const PointerType *PT = BaseType->getAs<PointerType>();
446 if (PT && (!getLangOpts().ObjC1 ||
447 PT->getPointeeType()->isRecordType())) {
448 assert(BaseExpr && "cannot happen with implicit member accesses");
449 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
450 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
455 assert(BaseType->isDependentType() ||
456 NameInfo.getName().isDependentName() ||
457 isDependentScopeSpecifier(SS));
459 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
460 // must have pointer type, and the accessed type is the pointee.
461 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
463 SS.getWithLocInContext(Context),
465 FirstQualifierInScope,
466 NameInfo, TemplateArgs));
469 /// We know that the given qualified member reference points only to
470 /// declarations which do not belong to the static type of the base
471 /// expression. Diagnose the problem.
472 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
475 const CXXScopeSpec &SS,
477 const DeclarationNameInfo &nameInfo) {
478 // If this is an implicit member access, use a different set of
481 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
483 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
484 << SS.getRange() << rep << BaseType;
487 // Check whether the declarations we found through a nested-name
488 // specifier in a member expression are actually members of the base
489 // type. The restriction here is:
492 // ... In these cases, the id-expression shall name a
493 // member of the class or of one of its base classes.
495 // So it's perfectly legitimate for the nested-name specifier to name
496 // an unrelated class, and for us to find an overload set including
497 // decls from classes which are not superclasses, as long as the decl
498 // we actually pick through overload resolution is from a superclass.
499 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
501 const CXXScopeSpec &SS,
502 const LookupResult &R) {
503 CXXRecordDecl *BaseRecord =
504 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
506 // We can't check this yet because the base type is still
508 assert(BaseType->isDependentType());
512 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
513 // If this is an implicit member reference and we find a
514 // non-instance member, it's not an error.
515 if (!BaseExpr && !(*I)->isCXXInstanceMember())
518 // Note that we use the DC of the decl, not the underlying decl.
519 DeclContext *DC = (*I)->getDeclContext();
520 while (DC->isTransparentContext())
521 DC = DC->getParent();
526 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
527 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
528 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
532 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
533 R.getRepresentativeDecl(),
534 R.getLookupNameInfo());
540 // Callback to only accept typo corrections that are either a ValueDecl or a
541 // FunctionTemplateDecl.
542 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
544 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
545 NamedDecl *ND = candidate.getCorrectionDecl();
546 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
553 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
554 SourceRange BaseRange, const RecordType *RTy,
555 SourceLocation OpLoc, CXXScopeSpec &SS,
556 bool HasTemplateArgs) {
557 RecordDecl *RDecl = RTy->getDecl();
558 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
559 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
560 diag::err_typecheck_incomplete_tag,
564 if (HasTemplateArgs) {
565 // LookupTemplateName doesn't expect these both to exist simultaneously.
566 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
569 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
573 DeclContext *DC = RDecl;
575 // If the member name was a qualified-id, look into the
576 // nested-name-specifier.
577 DC = SemaRef.computeDeclContext(SS, false);
579 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
580 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
581 << SS.getRange() << DC;
585 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
587 if (!isa<TypeDecl>(DC)) {
588 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
589 << DC << SS.getRange();
594 // The record definition is complete, now look up the member.
595 SemaRef.LookupQualifiedName(R, DC);
600 // We didn't find anything with the given name, so try to correct
602 DeclarationName Name = R.getLookupName();
603 RecordMemberExprValidatorCCC Validator;
604 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
605 R.getLookupKind(), NULL,
608 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
609 std::string CorrectedStr(
610 Corrected.getAsString(SemaRef.getLangOpts()));
611 std::string CorrectedQuotedStr(
612 Corrected.getQuoted(SemaRef.getLangOpts()));
613 R.setLookupName(Corrected.getCorrection());
615 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
616 << Name << DC << CorrectedQuotedStr << SS.getRange()
617 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
619 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
620 << ND->getDeclName();
627 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
628 SourceLocation OpLoc, bool IsArrow,
630 SourceLocation TemplateKWLoc,
631 NamedDecl *FirstQualifierInScope,
632 const DeclarationNameInfo &NameInfo,
633 const TemplateArgumentListInfo *TemplateArgs) {
634 if (BaseType->isDependentType() ||
635 (SS.isSet() && isDependentScopeSpecifier(SS)))
636 return ActOnDependentMemberExpr(Base, BaseType,
638 SS, TemplateKWLoc, FirstQualifierInScope,
639 NameInfo, TemplateArgs);
641 LookupResult R(*this, NameInfo, LookupMemberName);
643 // Implicit member accesses.
645 QualType RecordTy = BaseType;
646 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
647 if (LookupMemberExprInRecord(*this, R, SourceRange(),
648 RecordTy->getAs<RecordType>(),
649 OpLoc, SS, TemplateArgs != 0))
652 // Explicit member accesses.
654 ExprResult BaseResult = Owned(Base);
656 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
657 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
659 if (BaseResult.isInvalid())
661 Base = BaseResult.take();
663 if (Result.isInvalid()) {
671 // LookupMemberExpr can modify Base, and thus change BaseType
672 BaseType = Base->getType();
675 return BuildMemberReferenceExpr(Base, BaseType,
676 OpLoc, IsArrow, SS, TemplateKWLoc,
677 FirstQualifierInScope, R, TemplateArgs);
681 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
682 const CXXScopeSpec &SS, FieldDecl *Field,
683 DeclAccessPair FoundDecl,
684 const DeclarationNameInfo &MemberNameInfo);
687 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
689 IndirectFieldDecl *indirectField,
690 Expr *baseObjectExpr,
691 SourceLocation opLoc) {
692 // First, build the expression that refers to the base object.
694 bool baseObjectIsPointer = false;
695 Qualifiers baseQuals;
697 // Case 1: the base of the indirect field is not a field.
698 VarDecl *baseVariable = indirectField->getVarDecl();
699 CXXScopeSpec EmptySS;
701 assert(baseVariable->getType()->isRecordType());
703 // In principle we could have a member access expression that
704 // accesses an anonymous struct/union that's a static member of
705 // the base object's class. However, under the current standard,
706 // static data members cannot be anonymous structs or unions.
707 // Supporting this is as easy as building a MemberExpr here.
708 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
710 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
713 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
714 if (result.isInvalid()) return ExprError();
716 baseObjectExpr = result.take();
717 baseObjectIsPointer = false;
718 baseQuals = baseObjectExpr->getType().getQualifiers();
720 // Case 2: the base of the indirect field is a field and the user
721 // wrote a member expression.
722 } else if (baseObjectExpr) {
723 // The caller provided the base object expression. Determine
724 // whether its a pointer and whether it adds any qualifiers to the
725 // anonymous struct/union fields we're looking into.
726 QualType objectType = baseObjectExpr->getType();
728 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
729 baseObjectIsPointer = true;
730 objectType = ptr->getPointeeType();
732 baseObjectIsPointer = false;
734 baseQuals = objectType.getQualifiers();
736 // Case 3: the base of the indirect field is a field and we should
737 // build an implicit member access.
739 // We've found a member of an anonymous struct/union that is
740 // inside a non-anonymous struct/union, so in a well-formed
741 // program our base object expression is "this".
742 QualType ThisTy = getCurrentThisType();
743 if (ThisTy.isNull()) {
744 Diag(loc, diag::err_invalid_member_use_in_static_method)
745 << indirectField->getDeclName();
749 // Our base object expression is "this".
750 CheckCXXThisCapture(loc);
752 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
753 baseObjectIsPointer = true;
754 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
757 // Build the implicit member references to the field of the
758 // anonymous struct/union.
759 Expr *result = baseObjectExpr;
760 IndirectFieldDecl::chain_iterator
761 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
763 // Build the first member access in the chain with full information.
765 FieldDecl *field = cast<FieldDecl>(*FI);
767 // FIXME: use the real found-decl info!
768 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
770 // Make a nameInfo that properly uses the anonymous name.
771 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
773 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
774 EmptySS, field, foundDecl,
775 memberNameInfo).take();
776 baseObjectIsPointer = false;
778 // FIXME: check qualified member access
781 // In all cases, we should now skip the first declaration in the chain.
785 FieldDecl *field = cast<FieldDecl>(*FI++);
787 // FIXME: these are somewhat meaningless
788 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
789 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
791 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
792 (FI == FEnd? SS : EmptySS), field,
793 foundDecl, memberNameInfo).take();
796 return Owned(result);
800 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
801 const CXXScopeSpec &SS,
803 const DeclarationNameInfo &NameInfo) {
804 // Property names are always simple identifiers and therefore never
805 // require any interesting additional storage.
806 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
807 S.Context.PseudoObjectTy, VK_LValue,
808 SS.getWithLocInContext(S.Context),
812 /// \brief Build a MemberExpr AST node.
813 static MemberExpr *BuildMemberExpr(Sema &SemaRef,
814 ASTContext &C, Expr *Base, bool isArrow,
815 const CXXScopeSpec &SS,
816 SourceLocation TemplateKWLoc,
818 DeclAccessPair FoundDecl,
819 const DeclarationNameInfo &MemberNameInfo,
821 ExprValueKind VK, ExprObjectKind OK,
822 const TemplateArgumentListInfo *TemplateArgs = 0) {
823 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
825 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
826 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
827 TemplateArgs, Ty, VK, OK);
828 SemaRef.MarkMemberReferenced(E);
833 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
834 SourceLocation OpLoc, bool IsArrow,
835 const CXXScopeSpec &SS,
836 SourceLocation TemplateKWLoc,
837 NamedDecl *FirstQualifierInScope,
839 const TemplateArgumentListInfo *TemplateArgs,
840 bool SuppressQualifierCheck,
841 ActOnMemberAccessExtraArgs *ExtraArgs) {
842 QualType BaseType = BaseExprType;
844 assert(BaseType->isPointerType());
845 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
847 R.setBaseObjectType(BaseType);
849 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
850 DeclarationName MemberName = MemberNameInfo.getName();
851 SourceLocation MemberLoc = MemberNameInfo.getLoc();
857 // Rederive where we looked up.
858 DeclContext *DC = (SS.isSet()
859 ? computeDeclContext(SS, false)
860 : BaseType->getAs<RecordType>()->getDecl());
863 ExprResult RetryExpr;
864 if (!IsArrow && BaseExpr) {
865 SFINAETrap Trap(*this, true);
866 ParsedType ObjectType;
867 bool MayBePseudoDestructor = false;
868 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
869 OpLoc, tok::arrow, ObjectType,
870 MayBePseudoDestructor);
871 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
872 CXXScopeSpec TempSS(SS);
873 RetryExpr = ActOnMemberAccessExpr(
874 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
875 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
876 ExtraArgs->HasTrailingLParen);
878 if (Trap.hasErrorOccurred())
879 RetryExpr = ExprError();
881 if (RetryExpr.isUsable()) {
882 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
883 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
888 Diag(R.getNameLoc(), diag::err_no_member)
890 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
894 // Diagnose lookups that find only declarations from a non-base
895 // type. This is possible for either qualified lookups (which may
896 // have been qualified with an unrelated type) or implicit member
897 // expressions (which were found with unqualified lookup and thus
898 // may have come from an enclosing scope). Note that it's okay for
899 // lookup to find declarations from a non-base type as long as those
900 // aren't the ones picked by overload resolution.
901 if ((SS.isSet() || !BaseExpr ||
902 (isa<CXXThisExpr>(BaseExpr) &&
903 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
904 !SuppressQualifierCheck &&
905 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
908 // Construct an unresolved result if we in fact got an unresolved
910 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
911 // Suppress any lookup-related diagnostics; we'll do these when we
913 R.suppressDiagnostics();
915 UnresolvedMemberExpr *MemExpr
916 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
917 BaseExpr, BaseExprType,
919 SS.getWithLocInContext(Context),
920 TemplateKWLoc, MemberNameInfo,
921 TemplateArgs, R.begin(), R.end());
923 return Owned(MemExpr);
926 assert(R.isSingleResult());
927 DeclAccessPair FoundDecl = R.begin().getPair();
928 NamedDecl *MemberDecl = R.getFoundDecl();
930 // FIXME: diagnose the presence of template arguments now.
932 // If the decl being referenced had an error, return an error for this
933 // sub-expr without emitting another error, in order to avoid cascading
935 if (MemberDecl->isInvalidDecl())
938 // Handle the implicit-member-access case.
940 // If this is not an instance member, convert to a non-member access.
941 if (!MemberDecl->isCXXInstanceMember())
942 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
944 SourceLocation Loc = R.getNameLoc();
945 if (SS.getRange().isValid())
946 Loc = SS.getRange().getBegin();
947 CheckCXXThisCapture(Loc);
948 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
951 bool ShouldCheckUse = true;
952 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
953 // Don't diagnose the use of a virtual member function unless it's
954 // explicitly qualified.
955 if (MD->isVirtual() && !SS.isSet())
956 ShouldCheckUse = false;
959 // Check the use of this member.
960 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
965 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
966 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
967 SS, FD, FoundDecl, MemberNameInfo);
969 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
970 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
973 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
974 // We may have found a field within an anonymous union or struct
975 // (C++ [class.union]).
976 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
979 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
980 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
981 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
982 Var->getType().getNonReferenceType(),
983 VK_LValue, OK_Ordinary));
986 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
987 ExprValueKind valueKind;
989 if (MemberFn->isInstance()) {
990 valueKind = VK_RValue;
991 type = Context.BoundMemberTy;
993 valueKind = VK_LValue;
994 type = MemberFn->getType();
997 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
998 TemplateKWLoc, MemberFn, FoundDecl,
999 MemberNameInfo, type, valueKind,
1002 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1004 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1005 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1006 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1007 Enum->getType(), VK_RValue, OK_Ordinary));
1012 // We found something that we didn't expect. Complain.
1013 if (isa<TypeDecl>(MemberDecl))
1014 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1015 << MemberName << BaseType << int(IsArrow);
1017 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1018 << MemberName << BaseType << int(IsArrow);
1020 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1022 R.suppressDiagnostics();
1026 /// Given that normal member access failed on the given expression,
1027 /// and given that the expression's type involves builtin-id or
1028 /// builtin-Class, decide whether substituting in the redefinition
1029 /// types would be profitable. The redefinition type is whatever
1030 /// this translation unit tried to typedef to id/Class; we store
1031 /// it to the side and then re-use it in places like this.
1032 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1033 const ObjCObjectPointerType *opty
1034 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1035 if (!opty) return false;
1037 const ObjCObjectType *ty = opty->getObjectType();
1040 if (ty->isObjCId()) {
1041 redef = S.Context.getObjCIdRedefinitionType();
1042 } else if (ty->isObjCClass()) {
1043 redef = S.Context.getObjCClassRedefinitionType();
1048 // Do the substitution as long as the redefinition type isn't just a
1049 // possibly-qualified pointer to builtin-id or builtin-Class again.
1050 opty = redef->getAs<ObjCObjectPointerType>();
1051 if (opty && !opty->getObjectType()->getInterface())
1054 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1058 static bool isRecordType(QualType T) {
1059 return T->isRecordType();
1061 static bool isPointerToRecordType(QualType T) {
1062 if (const PointerType *PT = T->getAs<PointerType>())
1063 return PT->getPointeeType()->isRecordType();
1067 /// Perform conversions on the LHS of a member access expression.
1069 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1070 if (IsArrow && !Base->getType()->isFunctionType())
1071 return DefaultFunctionArrayLvalueConversion(Base);
1073 return CheckPlaceholderExpr(Base);
1076 /// Look up the given member of the given non-type-dependent
1077 /// expression. This can return in one of two ways:
1078 /// * If it returns a sentinel null-but-valid result, the caller will
1079 /// assume that lookup was performed and the results written into
1080 /// the provided structure. It will take over from there.
1081 /// * Otherwise, the returned expression will be produced in place of
1082 /// an ordinary member expression.
1084 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1085 /// fixed for ObjC++.
1087 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1088 bool &IsArrow, SourceLocation OpLoc,
1090 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1091 assert(BaseExpr.get() && "no base expression");
1093 // Perform default conversions.
1094 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
1095 if (BaseExpr.isInvalid())
1098 QualType BaseType = BaseExpr.get()->getType();
1099 assert(!BaseType->isDependentType());
1101 DeclarationName MemberName = R.getLookupName();
1102 SourceLocation MemberLoc = R.getNameLoc();
1104 // For later type-checking purposes, turn arrow accesses into dot
1105 // accesses. The only access type we support that doesn't follow
1106 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1107 // and those never use arrows, so this is unaffected.
1109 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1110 BaseType = Ptr->getPointeeType();
1111 else if (const ObjCObjectPointerType *Ptr
1112 = BaseType->getAs<ObjCObjectPointerType>())
1113 BaseType = Ptr->getPointeeType();
1114 else if (BaseType->isRecordType()) {
1115 // Recover from arrow accesses to records, e.g.:
1116 // struct MyRecord foo;
1118 // This is actually well-formed in C++ if MyRecord has an
1119 // overloaded operator->, but that should have been dealt with
1121 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1122 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1123 << FixItHint::CreateReplacement(OpLoc, ".");
1125 } else if (BaseType->isFunctionType()) {
1128 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1129 << BaseType << BaseExpr.get()->getSourceRange();
1134 // Handle field access to simple records.
1135 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1136 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1137 RTy, OpLoc, SS, HasTemplateArgs))
1140 // Returning valid-but-null is how we indicate to the caller that
1141 // the lookup result was filled in.
1142 return Owned((Expr*) 0);
1145 // Handle ivar access to Objective-C objects.
1146 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1147 if (!SS.isEmpty() && !SS.isInvalid()) {
1148 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1149 << 1 << SS.getScopeRep()
1150 << FixItHint::CreateRemoval(SS.getRange());
1154 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1156 // There are three cases for the base type:
1157 // - builtin id (qualified or unqualified)
1158 // - builtin Class (qualified or unqualified)
1160 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1162 if (getLangOpts().ObjCAutoRefCount &&
1163 (OTy->isObjCId() || OTy->isObjCClass()))
1165 // There's an implicit 'isa' ivar on all objects.
1166 // But we only actually find it this way on objects of type 'id',
1168 if (OTy->isObjCId() && Member->isStr("isa"))
1169 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1171 Context.getObjCClassType()));
1172 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1173 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1174 ObjCImpDecl, HasTemplateArgs);
1178 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1182 ObjCInterfaceDecl *ClassDeclared = 0;
1183 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1186 // Attempt to correct for typos in ivar names.
1187 DeclFilterCCC<ObjCIvarDecl> Validator;
1188 Validator.IsObjCIvarLookup = IsArrow;
1189 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1190 LookupMemberName, NULL, NULL,
1191 Validator, IDecl)) {
1192 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1193 Diag(R.getNameLoc(),
1194 diag::err_typecheck_member_reference_ivar_suggest)
1195 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1196 << FixItHint::CreateReplacement(R.getNameLoc(),
1197 IV->getNameAsString());
1198 Diag(IV->getLocation(), diag::note_previous_decl)
1199 << IV->getDeclName();
1201 // Figure out the class that declares the ivar.
1202 assert(!ClassDeclared);
1203 Decl *D = cast<Decl>(IV->getDeclContext());
1204 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1205 D = CAT->getClassInterface();
1206 ClassDeclared = cast<ObjCInterfaceDecl>(D);
1208 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1210 diag::err_property_found_suggest)
1211 << Member << BaseExpr.get()->getType()
1212 << FixItHint::CreateReplacement(OpLoc, ".");
1216 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1217 << IDecl->getDeclName() << MemberName
1218 << BaseExpr.get()->getSourceRange();
1223 assert(ClassDeclared);
1225 // If the decl being referenced had an error, return an error for this
1226 // sub-expr without emitting another error, in order to avoid cascading
1228 if (IV->isInvalidDecl())
1231 // Check whether we can reference this field.
1232 if (DiagnoseUseOfDecl(IV, MemberLoc))
1234 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1235 IV->getAccessControl() != ObjCIvarDecl::Package) {
1236 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1237 if (ObjCMethodDecl *MD = getCurMethodDecl())
1238 ClassOfMethodDecl = MD->getClassInterface();
1239 else if (ObjCImpDecl && getCurFunctionDecl()) {
1240 // Case of a c-function declared inside an objc implementation.
1241 // FIXME: For a c-style function nested inside an objc implementation
1242 // class, there is no implementation context available, so we pass
1243 // down the context as argument to this routine. Ideally, this context
1244 // need be passed down in the AST node and somehow calculated from the
1245 // AST for a function decl.
1246 if (ObjCImplementationDecl *IMPD =
1247 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1248 ClassOfMethodDecl = IMPD->getClassInterface();
1249 else if (ObjCCategoryImplDecl* CatImplClass =
1250 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1251 ClassOfMethodDecl = CatImplClass->getClassInterface();
1253 if (!getLangOpts().DebuggerSupport) {
1254 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1255 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1256 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1257 Diag(MemberLoc, diag::error_private_ivar_access)
1258 << IV->getDeclName();
1259 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1261 Diag(MemberLoc, diag::error_protected_ivar_access)
1262 << IV->getDeclName();
1266 if (getLangOpts().ObjCAutoRefCount) {
1267 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1268 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1269 if (UO->getOpcode() == UO_Deref)
1270 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1272 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1273 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1274 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1279 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1280 ObjCMethodFamily MF = MD->getMethodFamily();
1281 warn = (MF != OMF_init && MF != OMF_dealloc &&
1282 MF != OMF_finalize &&
1283 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1286 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1289 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1294 if (getLangOpts().ObjCAutoRefCount) {
1295 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1296 DiagnosticsEngine::Level Level =
1297 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1299 if (Level != DiagnosticsEngine::Ignored)
1300 getCurFunction()->recordUseOfWeak(Result);
1304 return Owned(Result);
1307 // Objective-C property access.
1308 const ObjCObjectPointerType *OPT;
1309 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1310 if (!SS.isEmpty() && !SS.isInvalid()) {
1311 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1312 << 0 << SS.getScopeRep()
1313 << FixItHint::CreateRemoval(SS.getRange());
1317 // This actually uses the base as an r-value.
1318 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1319 if (BaseExpr.isInvalid())
1322 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1324 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1326 const ObjCObjectType *OT = OPT->getObjectType();
1328 // id, with and without qualifiers.
1329 if (OT->isObjCId()) {
1330 // Check protocols on qualified interfaces.
1331 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1332 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1333 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1334 // Check the use of this declaration
1335 if (DiagnoseUseOfDecl(PD, MemberLoc))
1338 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1339 Context.PseudoObjectTy,
1346 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1347 // Check the use of this method.
1348 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1350 Selector SetterSel =
1351 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1352 PP.getSelectorTable(), Member);
1353 ObjCMethodDecl *SMD = 0;
1354 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1355 SetterSel, Context))
1356 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1358 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1359 Context.PseudoObjectTy,
1360 VK_LValue, OK_ObjCProperty,
1361 MemberLoc, BaseExpr.take()));
1364 // Use of id.member can only be for a property reference. Do not
1365 // use the 'id' redefinition in this case.
1366 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1367 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1368 ObjCImpDecl, HasTemplateArgs);
1370 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1371 << MemberName << BaseType);
1374 // 'Class', unqualified only.
1375 if (OT->isObjCClass()) {
1376 // Only works in a method declaration (??!).
1377 ObjCMethodDecl *MD = getCurMethodDecl();
1379 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1380 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1381 ObjCImpDecl, HasTemplateArgs);
1386 // Also must look for a getter name which uses property syntax.
1387 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1388 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1389 ObjCMethodDecl *Getter;
1390 if ((Getter = IFace->lookupClassMethod(Sel))) {
1391 // Check the use of this method.
1392 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1395 Getter = IFace->lookupPrivateMethod(Sel, false);
1396 // If we found a getter then this may be a valid dot-reference, we
1397 // will look for the matching setter, in case it is needed.
1398 Selector SetterSel =
1399 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1400 PP.getSelectorTable(), Member);
1401 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1403 // If this reference is in an @implementation, also check for 'private'
1405 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1408 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1411 if (Getter || Setter) {
1412 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1413 Context.PseudoObjectTy,
1414 VK_LValue, OK_ObjCProperty,
1415 MemberLoc, BaseExpr.take()));
1418 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1419 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1420 ObjCImpDecl, HasTemplateArgs);
1422 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1423 << MemberName << BaseType);
1426 // Normal property access.
1427 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1428 MemberName, MemberLoc,
1429 SourceLocation(), QualType(), false);
1432 // Handle 'field access' to vectors, such as 'V.xx'.
1433 if (BaseType->isExtVectorType()) {
1434 // FIXME: this expr should store IsArrow.
1435 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1436 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1437 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1442 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1443 *Member, MemberLoc));
1446 // Adjust builtin-sel to the appropriate redefinition type if that's
1447 // not just a pointer to builtin-sel again.
1449 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1450 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1451 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1452 Context.getObjCSelRedefinitionType(),
1454 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1455 ObjCImpDecl, HasTemplateArgs);
1461 // Recover from dot accesses to pointers, e.g.:
1464 // This is actually well-formed in two cases:
1465 // - 'type' is an Objective C type
1466 // - 'bar' is a pseudo-destructor name which happens to refer to
1467 // the appropriate pointer type
1468 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1469 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1470 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1471 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1472 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1473 << FixItHint::CreateReplacement(OpLoc, "->");
1475 // Recurse as an -> access.
1477 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1478 ObjCImpDecl, HasTemplateArgs);
1482 // If the user is trying to apply -> or . to a function name, it's probably
1483 // because they forgot parentheses to call that function.
1484 if (tryToRecoverWithCall(BaseExpr,
1485 PDiag(diag::err_member_reference_needs_call),
1487 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1488 if (BaseExpr.isInvalid())
1490 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1491 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1492 ObjCImpDecl, HasTemplateArgs);
1495 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1496 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1501 /// The main callback when the parser finds something like
1502 /// expression . [nested-name-specifier] identifier
1503 /// expression -> [nested-name-specifier] identifier
1504 /// where 'identifier' encompasses a fairly broad spectrum of
1505 /// possibilities, including destructor and operator references.
1507 /// \param OpKind either tok::arrow or tok::period
1508 /// \param HasTrailingLParen whether the next token is '(', which
1509 /// is used to diagnose mis-uses of special members that can
1511 /// \param ObjCImpDecl the current Objective-C \@implementation
1512 /// decl; this is an ugly hack around the fact that Objective-C
1513 /// \@implementations aren't properly put in the context chain
1514 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1515 SourceLocation OpLoc,
1516 tok::TokenKind OpKind,
1518 SourceLocation TemplateKWLoc,
1521 bool HasTrailingLParen) {
1522 if (SS.isSet() && SS.isInvalid())
1525 // Warn about the explicit constructor calls Microsoft extension.
1526 if (getLangOpts().MicrosoftExt &&
1527 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1528 Diag(Id.getSourceRange().getBegin(),
1529 diag::ext_ms_explicit_constructor_call);
1531 TemplateArgumentListInfo TemplateArgsBuffer;
1533 // Decompose the name into its component parts.
1534 DeclarationNameInfo NameInfo;
1535 const TemplateArgumentListInfo *TemplateArgs;
1536 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1537 NameInfo, TemplateArgs);
1539 DeclarationName Name = NameInfo.getName();
1540 bool IsArrow = (OpKind == tok::arrow);
1542 NamedDecl *FirstQualifierInScope
1543 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1544 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1546 // This is a postfix expression, so get rid of ParenListExprs.
1547 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1548 if (Result.isInvalid()) return ExprError();
1549 Base = Result.take();
1551 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1552 isDependentScopeSpecifier(SS)) {
1553 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1555 SS, TemplateKWLoc, FirstQualifierInScope,
1556 NameInfo, TemplateArgs);
1558 LookupResult R(*this, NameInfo, LookupMemberName);
1559 ExprResult BaseResult = Owned(Base);
1560 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1561 SS, ObjCImpDecl, TemplateArgs != 0);
1562 if (BaseResult.isInvalid())
1564 Base = BaseResult.take();
1566 if (Result.isInvalid()) {
1572 // The only way a reference to a destructor can be used is to
1573 // immediately call it, which falls into this case. If the
1574 // next token is not a '(', produce a diagnostic and build the
1576 if (!HasTrailingLParen &&
1577 Id.getKind() == UnqualifiedId::IK_DestructorName)
1578 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1583 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
1584 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1585 OpLoc, IsArrow, SS, TemplateKWLoc,
1586 FirstQualifierInScope, R, TemplateArgs,
1594 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1595 const CXXScopeSpec &SS, FieldDecl *Field,
1596 DeclAccessPair FoundDecl,
1597 const DeclarationNameInfo &MemberNameInfo) {
1598 // x.a is an l-value if 'a' has a reference type. Otherwise:
1599 // x.a is an l-value/x-value/pr-value if the base is (and note
1600 // that *x is always an l-value), except that if the base isn't
1601 // an ordinary object then we must have an rvalue.
1602 ExprValueKind VK = VK_LValue;
1603 ExprObjectKind OK = OK_Ordinary;
1605 if (BaseExpr->getObjectKind() == OK_Ordinary)
1606 VK = BaseExpr->getValueKind();
1610 if (VK != VK_RValue && Field->isBitField())
1613 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1614 QualType MemberType = Field->getType();
1615 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1616 MemberType = Ref->getPointeeType();
1619 QualType BaseType = BaseExpr->getType();
1620 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1622 Qualifiers BaseQuals = BaseType.getQualifiers();
1624 // GC attributes are never picked up by members.
1625 BaseQuals.removeObjCGCAttr();
1627 // CVR attributes from the base are picked up by members,
1628 // except that 'mutable' members don't pick up 'const'.
1629 if (Field->isMutable()) BaseQuals.removeConst();
1631 Qualifiers MemberQuals
1632 = S.Context.getCanonicalType(MemberType).getQualifiers();
1634 assert(!MemberQuals.hasAddressSpace());
1637 Qualifiers Combined = BaseQuals + MemberQuals;
1638 if (Combined != MemberQuals)
1639 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1642 S.UnusedPrivateFields.remove(Field);
1645 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1647 if (Base.isInvalid())
1649 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
1650 /*TemplateKWLoc=*/SourceLocation(),
1651 Field, FoundDecl, MemberNameInfo,
1652 MemberType, VK, OK));
1655 /// Builds an implicit member access expression. The current context
1656 /// is known to be an instance method, and the given unqualified lookup
1657 /// set is known to contain only instance members, at least one of which
1658 /// is from an appropriate type.
1660 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1661 SourceLocation TemplateKWLoc,
1663 const TemplateArgumentListInfo *TemplateArgs,
1664 bool IsKnownInstance) {
1665 assert(!R.empty() && !R.isAmbiguous());
1667 SourceLocation loc = R.getNameLoc();
1669 // We may have found a field within an anonymous union or struct
1670 // (C++ [class.union]).
1671 // FIXME: template-ids inside anonymous structs?
1672 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1673 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1675 // If this is known to be an instance access, go ahead and build an
1676 // implicit 'this' expression now.
1677 // 'this' expression now.
1678 QualType ThisTy = getCurrentThisType();
1679 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1681 Expr *baseExpr = 0; // null signifies implicit access
1682 if (IsKnownInstance) {
1683 SourceLocation Loc = R.getNameLoc();
1684 if (SS.getRange().isValid())
1685 Loc = SS.getRange().getBegin();
1686 CheckCXXThisCapture(Loc);
1687 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1690 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1691 /*OpLoc*/ SourceLocation(),
1694 /*FirstQualifierInScope*/ 0,