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 = SemaRef.CXXThisTypeOverride.isNull() &&
105 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
107 if (R.isUnresolvableResult())
108 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
110 // Collect all the declaring classes of instance members we find.
111 bool hasNonInstance = false;
112 bool isField = false;
113 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
114 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
117 if (D->isCXXInstanceMember()) {
118 if (dyn_cast<FieldDecl>(D))
121 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
122 Classes.insert(R->getCanonicalDecl());
125 hasNonInstance = true;
128 // If we didn't find any instance members, it can't be an implicit
133 bool IsCXX11UnevaluatedField = false;
134 if (SemaRef.getLangOpts().CPlusPlus0x && isField) {
135 // C++11 [expr.prim.general]p12:
136 // An id-expression that denotes a non-static data member or non-static
137 // member function of a class can only be used:
139 // - if that id-expression denotes a non-static data member and it
140 // appears in an unevaluated operand.
141 const Sema::ExpressionEvaluationContextRecord& record
142 = SemaRef.ExprEvalContexts.back();
143 if (record.Context == Sema::Unevaluated)
144 IsCXX11UnevaluatedField = true;
147 // If the current context is not an instance method, it can't be
148 // an implicit member reference.
149 if (isStaticContext) {
151 return IMA_Mixed_StaticContext;
153 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
154 : IMA_Error_StaticContext;
157 CXXRecordDecl *contextClass;
158 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
159 contextClass = MD->getParent()->getCanonicalDecl();
161 contextClass = cast<CXXRecordDecl>(DC);
163 // [class.mfct.non-static]p3:
164 // ...is used in the body of a non-static member function of class X,
165 // if name lookup (3.4.1) resolves the name in the id-expression to a
166 // non-static non-type member of some class C [...]
167 // ...if C is not X or a base class of X, the class member access expression
169 if (R.getNamingClass() &&
170 contextClass->getCanonicalDecl() !=
171 R.getNamingClass()->getCanonicalDecl() &&
172 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
173 return hasNonInstance ? IMA_Mixed_Unrelated :
174 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
177 // If we can prove that the current context is unrelated to all the
178 // declaring classes, it can't be an implicit member reference (in
179 // which case it's an error if any of those members are selected).
180 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
181 return hasNonInstance ? IMA_Mixed_Unrelated :
182 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
185 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
188 /// Diagnose a reference to a field with no object available.
189 static void diagnoseInstanceReference(Sema &SemaRef,
190 const CXXScopeSpec &SS,
192 const DeclarationNameInfo &nameInfo) {
193 SourceLocation Loc = nameInfo.getLoc();
194 SourceRange Range(Loc);
195 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
197 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
198 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
199 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
200 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
202 bool InStaticMethod = Method && Method->isStatic();
203 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
205 if (IsField && InStaticMethod)
206 // "invalid use of member 'x' in static member function"
207 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
208 << Range << nameInfo.getName();
209 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
210 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
211 // Unqualified lookup in a non-static member function found a member of an
213 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
214 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
216 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
217 << nameInfo.getName() << Range;
219 SemaRef.Diag(Loc, diag::err_member_call_without_object)
223 /// Builds an expression which might be an implicit member expression.
225 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
226 SourceLocation TemplateKWLoc,
228 const TemplateArgumentListInfo *TemplateArgs) {
229 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
231 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
234 case IMA_Mixed_Unrelated:
236 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
238 case IMA_Field_Uneval_Context:
239 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
240 << R.getLookupNameInfo().getName();
243 case IMA_Mixed_StaticContext:
244 case IMA_Unresolved_StaticContext:
245 if (TemplateArgs || TemplateKWLoc.isValid())
246 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
247 return BuildDeclarationNameExpr(SS, R, false);
249 case IMA_Error_StaticContext:
250 case IMA_Error_Unrelated:
251 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
252 R.getLookupNameInfo());
256 llvm_unreachable("unexpected instance member access kind");
259 /// Check an ext-vector component access expression.
261 /// VK should be set in advance to the value kind of the base
264 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
265 SourceLocation OpLoc, const IdentifierInfo *CompName,
266 SourceLocation CompLoc) {
267 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
270 // FIXME: This logic can be greatly simplified by splitting it along
271 // halving/not halving and reworking the component checking.
272 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
274 // The vector accessor can't exceed the number of elements.
275 const char *compStr = CompName->getNameStart();
277 // This flag determines whether or not the component is one of the four
278 // special names that indicate a subset of exactly half the elements are
280 bool HalvingSwizzle = false;
282 // This flag determines whether or not CompName has an 's' char prefix,
283 // indicating that it is a string of hex values to be used as vector indices.
284 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
286 bool HasRepeated = false;
287 bool HasIndex[16] = {};
291 // Check that we've found one of the special components, or that the component
292 // names must come from the same set.
293 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
294 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
295 HalvingSwizzle = true;
296 } else if (!HexSwizzle &&
297 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
299 if (HasIndex[Idx]) HasRepeated = true;
300 HasIndex[Idx] = true;
302 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
304 if (HexSwizzle) compStr++;
305 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
306 if (HasIndex[Idx]) HasRepeated = true;
307 HasIndex[Idx] = true;
312 if (!HalvingSwizzle && *compStr) {
313 // We didn't get to the end of the string. This means the component names
314 // didn't come from the same set *or* we encountered an illegal name.
315 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
316 << StringRef(compStr, 1) << SourceRange(CompLoc);
320 // Ensure no component accessor exceeds the width of the vector type it
322 if (!HalvingSwizzle) {
323 compStr = CompName->getNameStart();
329 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
330 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
331 << baseType << SourceRange(CompLoc);
337 // The component accessor looks fine - now we need to compute the actual type.
338 // The vector type is implied by the component accessor. For example,
339 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
340 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
341 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
342 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
343 : CompName->getLength();
348 return vecType->getElementType();
350 if (HasRepeated) VK = VK_RValue;
352 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
353 // Now look up the TypeDefDecl from the vector type. Without this,
354 // diagostics look bad. We want extended vector types to appear built-in.
355 for (Sema::ExtVectorDeclsType::iterator
356 I = S.ExtVectorDecls.begin(S.ExternalSource),
357 E = S.ExtVectorDecls.end();
359 if ((*I)->getUnderlyingType() == VT)
360 return S.Context.getTypedefType(*I);
363 return VT; // should never get here (a typedef type should always be found).
366 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
367 IdentifierInfo *Member,
369 ASTContext &Context) {
371 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
373 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
376 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
377 E = PDecl->protocol_end(); I != E; ++I) {
378 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
385 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
386 IdentifierInfo *Member,
388 ASTContext &Context) {
389 // Check protocols on qualified interfaces.
391 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
392 E = QIdTy->qual_end(); I != E; ++I) {
394 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
398 // Also must look for a getter or setter name which uses property syntax.
399 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
405 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
406 E = QIdTy->qual_end(); I != E; ++I) {
407 // Search in the protocol-qualifier list of current protocol.
408 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
418 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
419 bool IsArrow, SourceLocation OpLoc,
420 const CXXScopeSpec &SS,
421 SourceLocation TemplateKWLoc,
422 NamedDecl *FirstQualifierInScope,
423 const DeclarationNameInfo &NameInfo,
424 const TemplateArgumentListInfo *TemplateArgs) {
425 // Even in dependent contexts, try to diagnose base expressions with
426 // obviously wrong types, e.g.:
431 // In Obj-C++, however, the above expression is valid, since it could be
432 // accessing the 'f' property if T is an Obj-C interface. The extra check
433 // allows this, while still reporting an error if T is a struct pointer.
435 const PointerType *PT = BaseType->getAs<PointerType>();
436 if (PT && (!getLangOpts().ObjC1 ||
437 PT->getPointeeType()->isRecordType())) {
438 assert(BaseExpr && "cannot happen with implicit member accesses");
439 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
440 << BaseType << BaseExpr->getSourceRange();
445 assert(BaseType->isDependentType() ||
446 NameInfo.getName().isDependentName() ||
447 isDependentScopeSpecifier(SS));
449 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
450 // must have pointer type, and the accessed type is the pointee.
451 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
453 SS.getWithLocInContext(Context),
455 FirstQualifierInScope,
456 NameInfo, TemplateArgs));
459 /// We know that the given qualified member reference points only to
460 /// declarations which do not belong to the static type of the base
461 /// expression. Diagnose the problem.
462 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
465 const CXXScopeSpec &SS,
467 const DeclarationNameInfo &nameInfo) {
468 // If this is an implicit member access, use a different set of
471 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
473 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
474 << SS.getRange() << rep << BaseType;
477 // Check whether the declarations we found through a nested-name
478 // specifier in a member expression are actually members of the base
479 // type. The restriction here is:
482 // ... In these cases, the id-expression shall name a
483 // member of the class or of one of its base classes.
485 // So it's perfectly legitimate for the nested-name specifier to name
486 // an unrelated class, and for us to find an overload set including
487 // decls from classes which are not superclasses, as long as the decl
488 // we actually pick through overload resolution is from a superclass.
489 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
491 const CXXScopeSpec &SS,
492 const LookupResult &R) {
493 const RecordType *BaseRT = BaseType->getAs<RecordType>();
495 // We can't check this yet because the base type is still
497 assert(BaseType->isDependentType());
500 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
502 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
503 // If this is an implicit member reference and we find a
504 // non-instance member, it's not an error.
505 if (!BaseExpr && !(*I)->isCXXInstanceMember())
508 // Note that we use the DC of the decl, not the underlying decl.
509 DeclContext *DC = (*I)->getDeclContext();
510 while (DC->isTransparentContext())
511 DC = DC->getParent();
516 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
517 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
519 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
523 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
524 R.getRepresentativeDecl(),
525 R.getLookupNameInfo());
531 // Callback to only accept typo corrections that are either a ValueDecl or a
532 // FunctionTemplateDecl.
533 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
535 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
536 NamedDecl *ND = candidate.getCorrectionDecl();
537 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
544 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
545 SourceRange BaseRange, const RecordType *RTy,
546 SourceLocation OpLoc, CXXScopeSpec &SS,
547 bool HasTemplateArgs) {
548 RecordDecl *RDecl = RTy->getDecl();
549 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
550 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
551 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
555 if (HasTemplateArgs) {
556 // LookupTemplateName doesn't expect these both to exist simultaneously.
557 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
560 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
564 DeclContext *DC = RDecl;
566 // If the member name was a qualified-id, look into the
567 // nested-name-specifier.
568 DC = SemaRef.computeDeclContext(SS, false);
570 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
571 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
572 << SS.getRange() << DC;
576 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
578 if (!isa<TypeDecl>(DC)) {
579 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
580 << DC << SS.getRange();
585 // The record definition is complete, now look up the member.
586 SemaRef.LookupQualifiedName(R, DC);
591 // We didn't find anything with the given name, so try to correct
593 DeclarationName Name = R.getLookupName();
594 RecordMemberExprValidatorCCC Validator;
595 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
596 R.getLookupKind(), NULL,
599 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
600 std::string CorrectedStr(
601 Corrected.getAsString(SemaRef.getLangOpts()));
602 std::string CorrectedQuotedStr(
603 Corrected.getQuoted(SemaRef.getLangOpts()));
604 R.setLookupName(Corrected.getCorrection());
606 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
607 << Name << DC << CorrectedQuotedStr << SS.getRange()
608 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
609 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
610 << ND->getDeclName();
617 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
618 SourceLocation OpLoc, bool IsArrow,
620 SourceLocation TemplateKWLoc,
621 NamedDecl *FirstQualifierInScope,
622 const DeclarationNameInfo &NameInfo,
623 const TemplateArgumentListInfo *TemplateArgs) {
624 if (BaseType->isDependentType() ||
625 (SS.isSet() && isDependentScopeSpecifier(SS)))
626 return ActOnDependentMemberExpr(Base, BaseType,
628 SS, TemplateKWLoc, FirstQualifierInScope,
629 NameInfo, TemplateArgs);
631 LookupResult R(*this, NameInfo, LookupMemberName);
633 // Implicit member accesses.
635 QualType RecordTy = BaseType;
636 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
637 if (LookupMemberExprInRecord(*this, R, SourceRange(),
638 RecordTy->getAs<RecordType>(),
639 OpLoc, SS, TemplateArgs != 0))
642 // Explicit member accesses.
644 ExprResult BaseResult = Owned(Base);
646 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
647 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
649 if (BaseResult.isInvalid())
651 Base = BaseResult.take();
653 if (Result.isInvalid()) {
661 // LookupMemberExpr can modify Base, and thus change BaseType
662 BaseType = Base->getType();
665 return BuildMemberReferenceExpr(Base, BaseType,
666 OpLoc, IsArrow, SS, TemplateKWLoc,
667 FirstQualifierInScope, R, TemplateArgs);
671 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
672 const CXXScopeSpec &SS, FieldDecl *Field,
673 DeclAccessPair FoundDecl,
674 const DeclarationNameInfo &MemberNameInfo);
677 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
679 IndirectFieldDecl *indirectField,
680 Expr *baseObjectExpr,
681 SourceLocation opLoc) {
682 // First, build the expression that refers to the base object.
684 bool baseObjectIsPointer = false;
685 Qualifiers baseQuals;
687 // Case 1: the base of the indirect field is not a field.
688 VarDecl *baseVariable = indirectField->getVarDecl();
689 CXXScopeSpec EmptySS;
691 assert(baseVariable->getType()->isRecordType());
693 // In principle we could have a member access expression that
694 // accesses an anonymous struct/union that's a static member of
695 // the base object's class. However, under the current standard,
696 // static data members cannot be anonymous structs or unions.
697 // Supporting this is as easy as building a MemberExpr here.
698 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
700 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
703 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
704 if (result.isInvalid()) return ExprError();
706 baseObjectExpr = result.take();
707 baseObjectIsPointer = false;
708 baseQuals = baseObjectExpr->getType().getQualifiers();
710 // Case 2: the base of the indirect field is a field and the user
711 // wrote a member expression.
712 } else if (baseObjectExpr) {
713 // The caller provided the base object expression. Determine
714 // whether its a pointer and whether it adds any qualifiers to the
715 // anonymous struct/union fields we're looking into.
716 QualType objectType = baseObjectExpr->getType();
718 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
719 baseObjectIsPointer = true;
720 objectType = ptr->getPointeeType();
722 baseObjectIsPointer = false;
724 baseQuals = objectType.getQualifiers();
726 // Case 3: the base of the indirect field is a field and we should
727 // build an implicit member access.
729 // We've found a member of an anonymous struct/union that is
730 // inside a non-anonymous struct/union, so in a well-formed
731 // program our base object expression is "this".
732 QualType ThisTy = getCurrentThisType();
733 if (ThisTy.isNull()) {
734 Diag(loc, diag::err_invalid_member_use_in_static_method)
735 << indirectField->getDeclName();
739 // Our base object expression is "this".
740 CheckCXXThisCapture(loc);
742 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
743 baseObjectIsPointer = true;
744 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
747 // Build the implicit member references to the field of the
748 // anonymous struct/union.
749 Expr *result = baseObjectExpr;
750 IndirectFieldDecl::chain_iterator
751 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
753 // Build the first member access in the chain with full information.
755 FieldDecl *field = cast<FieldDecl>(*FI);
757 // FIXME: use the real found-decl info!
758 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
760 // Make a nameInfo that properly uses the anonymous name.
761 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
763 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
764 EmptySS, field, foundDecl,
765 memberNameInfo).take();
766 baseObjectIsPointer = false;
768 // FIXME: check qualified member access
771 // In all cases, we should now skip the first declaration in the chain.
775 FieldDecl *field = cast<FieldDecl>(*FI++);
777 // FIXME: these are somewhat meaningless
778 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
779 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
781 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
782 (FI == FEnd? SS : EmptySS), field,
783 foundDecl, memberNameInfo).take();
786 return Owned(result);
789 /// \brief Build a MemberExpr AST node.
790 static MemberExpr *BuildMemberExpr(Sema &SemaRef,
791 ASTContext &C, Expr *Base, bool isArrow,
792 const CXXScopeSpec &SS,
793 SourceLocation TemplateKWLoc,
795 DeclAccessPair FoundDecl,
796 const DeclarationNameInfo &MemberNameInfo,
798 ExprValueKind VK, ExprObjectKind OK,
799 const TemplateArgumentListInfo *TemplateArgs = 0) {
800 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
802 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
803 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
804 TemplateArgs, Ty, VK, OK);
805 SemaRef.MarkMemberReferenced(E);
810 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
811 SourceLocation OpLoc, bool IsArrow,
812 const CXXScopeSpec &SS,
813 SourceLocation TemplateKWLoc,
814 NamedDecl *FirstQualifierInScope,
816 const TemplateArgumentListInfo *TemplateArgs,
817 bool SuppressQualifierCheck) {
818 QualType BaseType = BaseExprType;
820 assert(BaseType->isPointerType());
821 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
823 R.setBaseObjectType(BaseType);
825 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
826 DeclarationName MemberName = MemberNameInfo.getName();
827 SourceLocation MemberLoc = MemberNameInfo.getLoc();
833 // Rederive where we looked up.
834 DeclContext *DC = (SS.isSet()
835 ? computeDeclContext(SS, false)
836 : BaseType->getAs<RecordType>()->getDecl());
838 Diag(R.getNameLoc(), diag::err_no_member)
840 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
844 // Diagnose lookups that find only declarations from a non-base
845 // type. This is possible for either qualified lookups (which may
846 // have been qualified with an unrelated type) or implicit member
847 // expressions (which were found with unqualified lookup and thus
848 // may have come from an enclosing scope). Note that it's okay for
849 // lookup to find declarations from a non-base type as long as those
850 // aren't the ones picked by overload resolution.
851 if ((SS.isSet() || !BaseExpr ||
852 (isa<CXXThisExpr>(BaseExpr) &&
853 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
854 !SuppressQualifierCheck &&
855 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
858 // Construct an unresolved result if we in fact got an unresolved
860 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
861 // Suppress any lookup-related diagnostics; we'll do these when we
863 R.suppressDiagnostics();
865 UnresolvedMemberExpr *MemExpr
866 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
867 BaseExpr, BaseExprType,
869 SS.getWithLocInContext(Context),
870 TemplateKWLoc, MemberNameInfo,
871 TemplateArgs, R.begin(), R.end());
873 return Owned(MemExpr);
876 assert(R.isSingleResult());
877 DeclAccessPair FoundDecl = R.begin().getPair();
878 NamedDecl *MemberDecl = R.getFoundDecl();
880 // FIXME: diagnose the presence of template arguments now.
882 // If the decl being referenced had an error, return an error for this
883 // sub-expr without emitting another error, in order to avoid cascading
885 if (MemberDecl->isInvalidDecl())
888 // Handle the implicit-member-access case.
890 // If this is not an instance member, convert to a non-member access.
891 if (!MemberDecl->isCXXInstanceMember())
892 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
894 SourceLocation Loc = R.getNameLoc();
895 if (SS.getRange().isValid())
896 Loc = SS.getRange().getBegin();
897 CheckCXXThisCapture(Loc);
898 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
901 bool ShouldCheckUse = true;
902 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
903 // Don't diagnose the use of a virtual member function unless it's
904 // explicitly qualified.
905 if (MD->isVirtual() && !SS.isSet())
906 ShouldCheckUse = false;
909 // Check the use of this member.
910 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
915 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
916 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
917 SS, FD, FoundDecl, MemberNameInfo);
919 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
920 // We may have found a field within an anonymous union or struct
921 // (C++ [class.union]).
922 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
925 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
926 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
927 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
928 Var->getType().getNonReferenceType(),
929 VK_LValue, OK_Ordinary));
932 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
933 ExprValueKind valueKind;
935 if (MemberFn->isInstance()) {
936 valueKind = VK_RValue;
937 type = Context.BoundMemberTy;
939 valueKind = VK_LValue;
940 type = MemberFn->getType();
943 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
944 TemplateKWLoc, MemberFn, FoundDecl,
945 MemberNameInfo, type, valueKind,
948 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
950 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
951 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
952 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
953 Enum->getType(), VK_RValue, OK_Ordinary));
958 // We found something that we didn't expect. Complain.
959 if (isa<TypeDecl>(MemberDecl))
960 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
961 << MemberName << BaseType << int(IsArrow);
963 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
964 << MemberName << BaseType << int(IsArrow);
966 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
968 R.suppressDiagnostics();
972 /// Given that normal member access failed on the given expression,
973 /// and given that the expression's type involves builtin-id or
974 /// builtin-Class, decide whether substituting in the redefinition
975 /// types would be profitable. The redefinition type is whatever
976 /// this translation unit tried to typedef to id/Class; we store
977 /// it to the side and then re-use it in places like this.
978 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
979 const ObjCObjectPointerType *opty
980 = base.get()->getType()->getAs<ObjCObjectPointerType>();
981 if (!opty) return false;
983 const ObjCObjectType *ty = opty->getObjectType();
986 if (ty->isObjCId()) {
987 redef = S.Context.getObjCIdRedefinitionType();
988 } else if (ty->isObjCClass()) {
989 redef = S.Context.getObjCClassRedefinitionType();
994 // Do the substitution as long as the redefinition type isn't just a
995 // possibly-qualified pointer to builtin-id or builtin-Class again.
996 opty = redef->getAs<ObjCObjectPointerType>();
997 if (opty && !opty->getObjectType()->getInterface() != 0)
1000 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1004 static bool isRecordType(QualType T) {
1005 return T->isRecordType();
1007 static bool isPointerToRecordType(QualType T) {
1008 if (const PointerType *PT = T->getAs<PointerType>())
1009 return PT->getPointeeType()->isRecordType();
1013 /// Perform conversions on the LHS of a member access expression.
1015 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1016 if (IsArrow && !Base->getType()->isFunctionType())
1017 return DefaultFunctionArrayLvalueConversion(Base);
1019 return CheckPlaceholderExpr(Base);
1022 /// Look up the given member of the given non-type-dependent
1023 /// expression. This can return in one of two ways:
1024 /// * If it returns a sentinel null-but-valid result, the caller will
1025 /// assume that lookup was performed and the results written into
1026 /// the provided structure. It will take over from there.
1027 /// * Otherwise, the returned expression will be produced in place of
1028 /// an ordinary member expression.
1030 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1031 /// fixed for ObjC++.
1033 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1034 bool &IsArrow, SourceLocation OpLoc,
1036 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1037 assert(BaseExpr.get() && "no base expression");
1039 // Perform default conversions.
1040 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
1041 if (BaseExpr.isInvalid())
1044 QualType BaseType = BaseExpr.get()->getType();
1045 assert(!BaseType->isDependentType());
1047 DeclarationName MemberName = R.getLookupName();
1048 SourceLocation MemberLoc = R.getNameLoc();
1050 // For later type-checking purposes, turn arrow accesses into dot
1051 // accesses. The only access type we support that doesn't follow
1052 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1053 // and those never use arrows, so this is unaffected.
1055 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1056 BaseType = Ptr->getPointeeType();
1057 else if (const ObjCObjectPointerType *Ptr
1058 = BaseType->getAs<ObjCObjectPointerType>())
1059 BaseType = Ptr->getPointeeType();
1060 else if (BaseType->isRecordType()) {
1061 // Recover from arrow accesses to records, e.g.:
1062 // struct MyRecord foo;
1064 // This is actually well-formed in C++ if MyRecord has an
1065 // overloaded operator->, but that should have been dealt with
1067 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1068 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1069 << FixItHint::CreateReplacement(OpLoc, ".");
1071 } else if (BaseType->isFunctionType()) {
1074 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1075 << BaseType << BaseExpr.get()->getSourceRange();
1080 // Handle field access to simple records.
1081 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1082 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1083 RTy, OpLoc, SS, HasTemplateArgs))
1086 // Returning valid-but-null is how we indicate to the caller that
1087 // the lookup result was filled in.
1088 return Owned((Expr*) 0);
1091 // Handle ivar access to Objective-C objects.
1092 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1093 if (!SS.isEmpty() && !SS.isInvalid()) {
1094 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1095 << 1 << SS.getScopeRep()
1096 << FixItHint::CreateRemoval(SS.getRange());
1100 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1102 // There are three cases for the base type:
1103 // - builtin id (qualified or unqualified)
1104 // - builtin Class (qualified or unqualified)
1106 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1108 if (getLangOpts().ObjCAutoRefCount &&
1109 (OTy->isObjCId() || OTy->isObjCClass()))
1111 // There's an implicit 'isa' ivar on all objects.
1112 // But we only actually find it this way on objects of type 'id',
1114 if (OTy->isObjCId() && Member->isStr("isa")) {
1115 Diag(MemberLoc, diag::warn_objc_isa_use);
1116 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1117 Context.getObjCClassType()));
1120 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1121 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1122 ObjCImpDecl, HasTemplateArgs);
1126 if (RequireCompleteType(OpLoc, BaseType,
1127 PDiag(diag::err_typecheck_incomplete_tag)
1128 << BaseExpr.get()->getSourceRange()))
1131 ObjCInterfaceDecl *ClassDeclared = 0;
1132 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1135 // Attempt to correct for typos in ivar names.
1136 DeclFilterCCC<ObjCIvarDecl> Validator;
1137 Validator.IsObjCIvarLookup = IsArrow;
1138 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1139 LookupMemberName, NULL, NULL,
1140 Validator, IDecl)) {
1141 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1142 Diag(R.getNameLoc(),
1143 diag::err_typecheck_member_reference_ivar_suggest)
1144 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1145 << FixItHint::CreateReplacement(R.getNameLoc(),
1146 IV->getNameAsString());
1147 Diag(IV->getLocation(), diag::note_previous_decl)
1148 << IV->getDeclName();
1150 // Figure out the class that declares the ivar.
1151 assert(!ClassDeclared);
1152 Decl *D = cast<Decl>(IV->getDeclContext());
1153 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1154 D = CAT->getClassInterface();
1155 ClassDeclared = cast<ObjCInterfaceDecl>(D);
1157 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1159 diag::err_property_found_suggest)
1160 << Member << BaseExpr.get()->getType()
1161 << FixItHint::CreateReplacement(OpLoc, ".");
1165 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1166 << IDecl->getDeclName() << MemberName
1167 << BaseExpr.get()->getSourceRange();
1172 assert(ClassDeclared);
1174 // If the decl being referenced had an error, return an error for this
1175 // sub-expr without emitting another error, in order to avoid cascading
1177 if (IV->isInvalidDecl())
1180 // Check whether we can reference this field.
1181 if (DiagnoseUseOfDecl(IV, MemberLoc))
1183 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1184 IV->getAccessControl() != ObjCIvarDecl::Package) {
1185 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1186 if (ObjCMethodDecl *MD = getCurMethodDecl())
1187 ClassOfMethodDecl = MD->getClassInterface();
1188 else if (ObjCImpDecl && getCurFunctionDecl()) {
1189 // Case of a c-function declared inside an objc implementation.
1190 // FIXME: For a c-style function nested inside an objc implementation
1191 // class, there is no implementation context available, so we pass
1192 // down the context as argument to this routine. Ideally, this context
1193 // need be passed down in the AST node and somehow calculated from the
1194 // AST for a function decl.
1195 if (ObjCImplementationDecl *IMPD =
1196 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1197 ClassOfMethodDecl = IMPD->getClassInterface();
1198 else if (ObjCCategoryImplDecl* CatImplClass =
1199 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1200 ClassOfMethodDecl = CatImplClass->getClassInterface();
1202 if (!getLangOpts().DebuggerSupport) {
1203 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1204 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1205 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1206 Diag(MemberLoc, diag::error_private_ivar_access)
1207 << IV->getDeclName();
1208 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1210 Diag(MemberLoc, diag::error_protected_ivar_access)
1211 << IV->getDeclName();
1214 if (getLangOpts().ObjCAutoRefCount) {
1215 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1216 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1217 if (UO->getOpcode() == UO_Deref)
1218 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1220 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1221 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1222 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1225 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1226 MemberLoc, BaseExpr.take(),
1230 // Objective-C property access.
1231 const ObjCObjectPointerType *OPT;
1232 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1233 if (!SS.isEmpty() && !SS.isInvalid()) {
1234 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1235 << 0 << SS.getScopeRep()
1236 << FixItHint::CreateRemoval(SS.getRange());
1240 // This actually uses the base as an r-value.
1241 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1242 if (BaseExpr.isInvalid())
1245 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1247 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1249 const ObjCObjectType *OT = OPT->getObjectType();
1251 // id, with and without qualifiers.
1252 if (OT->isObjCId()) {
1253 // Check protocols on qualified interfaces.
1254 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1255 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1256 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1257 // Check the use of this declaration
1258 if (DiagnoseUseOfDecl(PD, MemberLoc))
1261 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1262 Context.PseudoObjectTy,
1269 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1270 // Check the use of this method.
1271 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1273 Selector SetterSel =
1274 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1275 PP.getSelectorTable(), Member);
1276 ObjCMethodDecl *SMD = 0;
1277 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1278 SetterSel, Context))
1279 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1281 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1282 Context.PseudoObjectTy,
1283 VK_LValue, OK_ObjCProperty,
1284 MemberLoc, BaseExpr.take()));
1287 // Use of id.member can only be for a property reference. Do not
1288 // use the 'id' redefinition in this case.
1289 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1290 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1291 ObjCImpDecl, HasTemplateArgs);
1293 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1294 << MemberName << BaseType);
1297 // 'Class', unqualified only.
1298 if (OT->isObjCClass()) {
1299 // Only works in a method declaration (??!).
1300 ObjCMethodDecl *MD = getCurMethodDecl();
1302 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1303 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1304 ObjCImpDecl, HasTemplateArgs);
1309 // Also must look for a getter name which uses property syntax.
1310 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1311 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1312 ObjCMethodDecl *Getter;
1313 if ((Getter = IFace->lookupClassMethod(Sel))) {
1314 // Check the use of this method.
1315 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1318 Getter = IFace->lookupPrivateMethod(Sel, false);
1319 // If we found a getter then this may be a valid dot-reference, we
1320 // will look for the matching setter, in case it is needed.
1321 Selector SetterSel =
1322 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1323 PP.getSelectorTable(), Member);
1324 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1326 // If this reference is in an @implementation, also check for 'private'
1328 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1330 // Look through local category implementations associated with the class.
1332 Setter = IFace->getCategoryClassMethod(SetterSel);
1334 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1337 if (Getter || Setter) {
1338 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1339 Context.PseudoObjectTy,
1340 VK_LValue, OK_ObjCProperty,
1341 MemberLoc, BaseExpr.take()));
1344 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1345 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1346 ObjCImpDecl, HasTemplateArgs);
1348 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1349 << MemberName << BaseType);
1352 // Normal property access.
1353 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1354 MemberName, MemberLoc,
1355 SourceLocation(), QualType(), false);
1358 // Handle 'field access' to vectors, such as 'V.xx'.
1359 if (BaseType->isExtVectorType()) {
1360 // FIXME: this expr should store IsArrow.
1361 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1362 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1363 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1368 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1369 *Member, MemberLoc));
1372 // Adjust builtin-sel to the appropriate redefinition type if that's
1373 // not just a pointer to builtin-sel again.
1375 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1376 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1377 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1378 Context.getObjCSelRedefinitionType(),
1380 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1381 ObjCImpDecl, HasTemplateArgs);
1387 // Recover from dot accesses to pointers, e.g.:
1390 // This is actually well-formed in two cases:
1391 // - 'type' is an Objective C type
1392 // - 'bar' is a pseudo-destructor name which happens to refer to
1393 // the appropriate pointer type
1394 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1395 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1396 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1397 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1398 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1399 << FixItHint::CreateReplacement(OpLoc, "->");
1401 // Recurse as an -> access.
1403 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1404 ObjCImpDecl, HasTemplateArgs);
1408 // If the user is trying to apply -> or . to a function name, it's probably
1409 // because they forgot parentheses to call that function.
1410 if (tryToRecoverWithCall(BaseExpr,
1411 PDiag(diag::err_member_reference_needs_call),
1413 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1414 if (BaseExpr.isInvalid())
1416 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1417 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1418 ObjCImpDecl, HasTemplateArgs);
1421 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1422 << BaseType << BaseExpr.get()->getSourceRange();
1427 /// The main callback when the parser finds something like
1428 /// expression . [nested-name-specifier] identifier
1429 /// expression -> [nested-name-specifier] identifier
1430 /// where 'identifier' encompasses a fairly broad spectrum of
1431 /// possibilities, including destructor and operator references.
1433 /// \param OpKind either tok::arrow or tok::period
1434 /// \param HasTrailingLParen whether the next token is '(', which
1435 /// is used to diagnose mis-uses of special members that can
1437 /// \param ObjCImpDecl the current ObjC @implementation decl;
1438 /// this is an ugly hack around the fact that ObjC @implementations
1439 /// aren't properly put in the context chain
1440 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1441 SourceLocation OpLoc,
1442 tok::TokenKind OpKind,
1444 SourceLocation TemplateKWLoc,
1447 bool HasTrailingLParen) {
1448 if (SS.isSet() && SS.isInvalid())
1451 // Warn about the explicit constructor calls Microsoft extension.
1452 if (getLangOpts().MicrosoftExt &&
1453 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1454 Diag(Id.getSourceRange().getBegin(),
1455 diag::ext_ms_explicit_constructor_call);
1457 TemplateArgumentListInfo TemplateArgsBuffer;
1459 // Decompose the name into its component parts.
1460 DeclarationNameInfo NameInfo;
1461 const TemplateArgumentListInfo *TemplateArgs;
1462 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1463 NameInfo, TemplateArgs);
1465 DeclarationName Name = NameInfo.getName();
1466 bool IsArrow = (OpKind == tok::arrow);
1468 NamedDecl *FirstQualifierInScope
1469 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1470 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1472 // This is a postfix expression, so get rid of ParenListExprs.
1473 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1474 if (Result.isInvalid()) return ExprError();
1475 Base = Result.take();
1477 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1478 isDependentScopeSpecifier(SS)) {
1479 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1481 SS, TemplateKWLoc, FirstQualifierInScope,
1482 NameInfo, TemplateArgs);
1484 LookupResult R(*this, NameInfo, LookupMemberName);
1485 ExprResult BaseResult = Owned(Base);
1486 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1487 SS, ObjCImpDecl, TemplateArgs != 0);
1488 if (BaseResult.isInvalid())
1490 Base = BaseResult.take();
1492 if (Result.isInvalid()) {
1498 // The only way a reference to a destructor can be used is to
1499 // immediately call it, which falls into this case. If the
1500 // next token is not a '(', produce a diagnostic and build the
1502 if (!HasTrailingLParen &&
1503 Id.getKind() == UnqualifiedId::IK_DestructorName)
1504 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1506 return move(Result);
1509 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1510 OpLoc, IsArrow, SS, TemplateKWLoc,
1511 FirstQualifierInScope, R, TemplateArgs);
1514 return move(Result);
1518 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1519 const CXXScopeSpec &SS, FieldDecl *Field,
1520 DeclAccessPair FoundDecl,
1521 const DeclarationNameInfo &MemberNameInfo) {
1522 // x.a is an l-value if 'a' has a reference type. Otherwise:
1523 // x.a is an l-value/x-value/pr-value if the base is (and note
1524 // that *x is always an l-value), except that if the base isn't
1525 // an ordinary object then we must have an rvalue.
1526 ExprValueKind VK = VK_LValue;
1527 ExprObjectKind OK = OK_Ordinary;
1529 if (BaseExpr->getObjectKind() == OK_Ordinary)
1530 VK = BaseExpr->getValueKind();
1534 if (VK != VK_RValue && Field->isBitField())
1537 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1538 QualType MemberType = Field->getType();
1539 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1540 MemberType = Ref->getPointeeType();
1543 QualType BaseType = BaseExpr->getType();
1544 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1546 Qualifiers BaseQuals = BaseType.getQualifiers();
1548 // GC attributes are never picked up by members.
1549 BaseQuals.removeObjCGCAttr();
1551 // CVR attributes from the base are picked up by members,
1552 // except that 'mutable' members don't pick up 'const'.
1553 if (Field->isMutable()) BaseQuals.removeConst();
1555 Qualifiers MemberQuals
1556 = S.Context.getCanonicalType(MemberType).getQualifiers();
1558 // TR 18037 does not allow fields to be declared with address spaces.
1559 assert(!MemberQuals.hasAddressSpace());
1561 Qualifiers Combined = BaseQuals + MemberQuals;
1562 if (Combined != MemberQuals)
1563 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1567 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1569 if (Base.isInvalid())
1571 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
1572 /*TemplateKWLoc=*/SourceLocation(),
1573 Field, FoundDecl, MemberNameInfo,
1574 MemberType, VK, OK));
1577 /// Builds an implicit member access expression. The current context
1578 /// is known to be an instance method, and the given unqualified lookup
1579 /// set is known to contain only instance members, at least one of which
1580 /// is from an appropriate type.
1582 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1583 SourceLocation TemplateKWLoc,
1585 const TemplateArgumentListInfo *TemplateArgs,
1586 bool IsKnownInstance) {
1587 assert(!R.empty() && !R.isAmbiguous());
1589 SourceLocation loc = R.getNameLoc();
1591 // We may have found a field within an anonymous union or struct
1592 // (C++ [class.union]).
1593 // FIXME: template-ids inside anonymous structs?
1594 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1595 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1597 // If this is known to be an instance access, go ahead and build an
1598 // implicit 'this' expression now.
1599 // 'this' expression now.
1600 QualType ThisTy = getCurrentThisType();
1601 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1603 Expr *baseExpr = 0; // null signifies implicit access
1604 if (IsKnownInstance) {
1605 SourceLocation Loc = R.getNameLoc();
1606 if (SS.getRange().isValid())
1607 Loc = SS.getRange().getBegin();
1608 CheckCXXThisCapture(Loc);
1609 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1612 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1613 /*OpLoc*/ SourceLocation(),
1616 /*FirstQualifierInScope*/ 0,