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 is 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 /// All possible referrents are instance members and the current
78 /// context is not an instance method.
79 IMA_Error_StaticContext,
81 /// All possible referrents are instance members of an unrelated
86 /// The given lookup names class member(s) and is not being used for
87 /// an address-of-member expression. Classify the type of access
88 /// according to whether it's possible that this reference names an
89 /// instance member. This is best-effort; it is okay to
90 /// conservatively answer "yes", in which case some errors will simply
91 /// not be caught until template-instantiation.
92 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
94 const LookupResult &R) {
95 assert(!R.empty() && (*R.begin())->isCXXClassMember());
97 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
99 bool isStaticContext =
100 (!isa<CXXMethodDecl>(DC) ||
101 cast<CXXMethodDecl>(DC)->isStatic());
103 // C++0x [expr.prim]p4:
104 // Otherwise, if a member-declarator declares a non-static data member
105 // of a class X, the expression this is a prvalue of type "pointer to X"
106 // within the optional brace-or-equal-initializer.
107 if (CurScope->getFlags() & Scope::ThisScope)
108 isStaticContext = false;
110 if (R.isUnresolvableResult())
111 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
113 // Collect all the declaring classes of instance members we find.
114 bool hasNonInstance = false;
115 bool hasField = false;
116 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
117 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
120 if (D->isCXXInstanceMember()) {
121 if (dyn_cast<FieldDecl>(D))
124 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
125 Classes.insert(R->getCanonicalDecl());
128 hasNonInstance = true;
131 // If we didn't find any instance members, it can't be an implicit
136 // If the current context is not an instance method, it can't be
137 // an implicit member reference.
138 if (isStaticContext) {
140 return IMA_Mixed_StaticContext;
142 if (SemaRef.getLangOptions().CPlusPlus0x && hasField) {
143 // C++0x [expr.prim.general]p10:
144 // An id-expression that denotes a non-static data member or non-static
145 // member function of a class can only be used:
147 // - if that id-expression denotes a non-static data member and it
148 // appears in an unevaluated operand.
149 const Sema::ExpressionEvaluationContextRecord& record
150 = SemaRef.ExprEvalContexts.back();
151 bool isUnevaluatedExpression = (record.Context == Sema::Unevaluated);
152 if (isUnevaluatedExpression)
153 return IMA_Mixed_StaticContext;
156 return IMA_Error_StaticContext;
159 CXXRecordDecl *contextClass;
160 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
161 contextClass = MD->getParent()->getCanonicalDecl();
163 contextClass = cast<CXXRecordDecl>(DC);
165 // [class.mfct.non-static]p3:
166 // ...is used in the body of a non-static member function of class X,
167 // if name lookup (3.4.1) resolves the name in the id-expression to a
168 // non-static non-type member of some class C [...]
169 // ...if C is not X or a base class of X, the class member access expression
171 if (R.getNamingClass() &&
172 contextClass != R.getNamingClass()->getCanonicalDecl() &&
173 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
174 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
176 // If we can prove that the current context is unrelated to all the
177 // declaring classes, it can't be an implicit member reference (in
178 // which case it's an error if any of those members are selected).
179 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
180 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
182 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
185 /// Diagnose a reference to a field with no object available.
186 static void DiagnoseInstanceReference(Sema &SemaRef,
187 const CXXScopeSpec &SS,
189 const DeclarationNameInfo &nameInfo) {
190 SourceLocation Loc = nameInfo.getLoc();
191 SourceRange Range(Loc);
192 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
194 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
195 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
196 if (MD->isStatic()) {
197 // "invalid use of member 'x' in static member function"
198 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
199 << Range << nameInfo.getName();
204 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
205 << nameInfo.getName() << Range;
209 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
212 /// Builds an expression which might be an implicit member expression.
214 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
216 const TemplateArgumentListInfo *TemplateArgs) {
217 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
219 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
222 case IMA_Mixed_Unrelated:
224 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
227 case IMA_Mixed_StaticContext:
228 case IMA_Unresolved_StaticContext:
230 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
231 return BuildDeclarationNameExpr(SS, R, false);
233 case IMA_Error_StaticContext:
234 case IMA_Error_Unrelated:
235 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
236 R.getLookupNameInfo());
240 llvm_unreachable("unexpected instance member access kind");
244 /// Check an ext-vector component access expression.
246 /// VK should be set in advance to the value kind of the base
249 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
250 SourceLocation OpLoc, const IdentifierInfo *CompName,
251 SourceLocation CompLoc) {
252 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
255 // FIXME: This logic can be greatly simplified by splitting it along
256 // halving/not halving and reworking the component checking.
257 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
259 // The vector accessor can't exceed the number of elements.
260 const char *compStr = CompName->getNameStart();
262 // This flag determines whether or not the component is one of the four
263 // special names that indicate a subset of exactly half the elements are
265 bool HalvingSwizzle = false;
267 // This flag determines whether or not CompName has an 's' char prefix,
268 // indicating that it is a string of hex values to be used as vector indices.
269 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
271 bool HasRepeated = false;
272 bool HasIndex[16] = {};
276 // Check that we've found one of the special components, or that the component
277 // names must come from the same set.
278 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
279 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
280 HalvingSwizzle = true;
281 } else if (!HexSwizzle &&
282 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
284 if (HasIndex[Idx]) HasRepeated = true;
285 HasIndex[Idx] = true;
287 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
289 if (HexSwizzle) compStr++;
290 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
291 if (HasIndex[Idx]) HasRepeated = true;
292 HasIndex[Idx] = true;
297 if (!HalvingSwizzle && *compStr) {
298 // We didn't get to the end of the string. This means the component names
299 // didn't come from the same set *or* we encountered an illegal name.
300 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
301 << llvm::StringRef(compStr, 1) << SourceRange(CompLoc);
305 // Ensure no component accessor exceeds the width of the vector type it
307 if (!HalvingSwizzle) {
308 compStr = CompName->getNameStart();
314 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
315 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
316 << baseType << SourceRange(CompLoc);
322 // The component accessor looks fine - now we need to compute the actual type.
323 // The vector type is implied by the component accessor. For example,
324 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
325 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
326 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
327 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
328 : CompName->getLength();
333 return vecType->getElementType();
335 if (HasRepeated) VK = VK_RValue;
337 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
338 // Now look up the TypeDefDecl from the vector type. Without this,
339 // diagostics look bad. We want extended vector types to appear built-in.
340 for (unsigned i = 0, E = S.ExtVectorDecls.size(); i != E; ++i) {
341 if (S.ExtVectorDecls[i]->getUnderlyingType() == VT)
342 return S.Context.getTypedefType(S.ExtVectorDecls[i]);
344 return VT; // should never get here (a typedef type should always be found).
347 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
348 IdentifierInfo *Member,
350 ASTContext &Context) {
352 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
354 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
357 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
358 E = PDecl->protocol_end(); I != E; ++I) {
359 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
366 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
367 IdentifierInfo *Member,
369 ASTContext &Context) {
370 // Check protocols on qualified interfaces.
372 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
373 E = QIdTy->qual_end(); I != E; ++I) {
375 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
379 // Also must look for a getter or setter name which uses property syntax.
380 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
386 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
387 E = QIdTy->qual_end(); I != E; ++I) {
388 // Search in the protocol-qualifier list of current protocol.
389 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
399 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
400 bool IsArrow, SourceLocation OpLoc,
401 const CXXScopeSpec &SS,
402 NamedDecl *FirstQualifierInScope,
403 const DeclarationNameInfo &NameInfo,
404 const TemplateArgumentListInfo *TemplateArgs) {
405 // Even in dependent contexts, try to diagnose base expressions with
406 // obviously wrong types, e.g.:
411 // In Obj-C++, however, the above expression is valid, since it could be
412 // accessing the 'f' property if T is an Obj-C interface. The extra check
413 // allows this, while still reporting an error if T is a struct pointer.
415 const PointerType *PT = BaseType->getAs<PointerType>();
416 if (PT && (!getLangOptions().ObjC1 ||
417 PT->getPointeeType()->isRecordType())) {
418 assert(BaseExpr && "cannot happen with implicit member accesses");
419 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
420 << BaseType << BaseExpr->getSourceRange();
425 assert(BaseType->isDependentType() ||
426 NameInfo.getName().isDependentName() ||
427 isDependentScopeSpecifier(SS));
429 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
430 // must have pointer type, and the accessed type is the pointee.
431 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
433 SS.getWithLocInContext(Context),
434 FirstQualifierInScope,
435 NameInfo, TemplateArgs));
438 /// We know that the given qualified member reference points only to
439 /// declarations which do not belong to the static type of the base
440 /// expression. Diagnose the problem.
441 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
444 const CXXScopeSpec &SS,
446 const DeclarationNameInfo &nameInfo) {
447 // If this is an implicit member access, use a different set of
450 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
452 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
453 << SS.getRange() << rep << BaseType;
456 // Check whether the declarations we found through a nested-name
457 // specifier in a member expression are actually members of the base
458 // type. The restriction here is:
461 // ... In these cases, the id-expression shall name a
462 // member of the class or of one of its base classes.
464 // So it's perfectly legitimate for the nested-name specifier to name
465 // an unrelated class, and for us to find an overload set including
466 // decls from classes which are not superclasses, as long as the decl
467 // we actually pick through overload resolution is from a superclass.
468 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
470 const CXXScopeSpec &SS,
471 const LookupResult &R) {
472 const RecordType *BaseRT = BaseType->getAs<RecordType>();
474 // We can't check this yet because the base type is still
476 assert(BaseType->isDependentType());
479 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
481 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
482 // If this is an implicit member reference and we find a
483 // non-instance member, it's not an error.
484 if (!BaseExpr && !(*I)->isCXXInstanceMember())
487 // Note that we use the DC of the decl, not the underlying decl.
488 DeclContext *DC = (*I)->getDeclContext();
489 while (DC->isTransparentContext())
490 DC = DC->getParent();
495 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
496 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
498 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
502 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
503 R.getRepresentativeDecl(),
504 R.getLookupNameInfo());
509 LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
510 SourceRange BaseRange, const RecordType *RTy,
511 SourceLocation OpLoc, CXXScopeSpec &SS,
512 bool HasTemplateArgs) {
513 RecordDecl *RDecl = RTy->getDecl();
514 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
515 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
519 if (HasTemplateArgs) {
520 // LookupTemplateName doesn't expect these both to exist simultaneously.
521 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
524 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
528 DeclContext *DC = RDecl;
530 // If the member name was a qualified-id, look into the
531 // nested-name-specifier.
532 DC = SemaRef.computeDeclContext(SS, false);
534 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
535 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
536 << SS.getRange() << DC;
540 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
542 if (!isa<TypeDecl>(DC)) {
543 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
544 << DC << SS.getRange();
549 // The record definition is complete, now look up the member.
550 SemaRef.LookupQualifiedName(R, DC);
555 // We didn't find anything with the given name, so try to correct
557 DeclarationName Name = R.getLookupName();
558 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
559 R.getLookupKind(), NULL,
561 Sema::CTC_MemberLookup);
562 NamedDecl *ND = Corrected.getCorrectionDecl();
564 if (ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))) {
565 std::string CorrectedStr(
566 Corrected.getAsString(SemaRef.getLangOptions()));
567 std::string CorrectedQuotedStr(
568 Corrected.getQuoted(SemaRef.getLangOptions()));
569 R.setLookupName(Corrected.getCorrection());
571 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
572 << Name << DC << CorrectedQuotedStr << SS.getRange()
573 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
574 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
575 << ND->getDeclName();
582 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
583 SourceLocation OpLoc, bool IsArrow,
585 NamedDecl *FirstQualifierInScope,
586 const DeclarationNameInfo &NameInfo,
587 const TemplateArgumentListInfo *TemplateArgs) {
588 if (BaseType->isDependentType() ||
589 (SS.isSet() && isDependentScopeSpecifier(SS)))
590 return ActOnDependentMemberExpr(Base, BaseType,
592 SS, FirstQualifierInScope,
593 NameInfo, TemplateArgs);
595 LookupResult R(*this, NameInfo, LookupMemberName);
597 // Implicit member accesses.
599 QualType RecordTy = BaseType;
600 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
601 if (LookupMemberExprInRecord(*this, R, SourceRange(),
602 RecordTy->getAs<RecordType>(),
603 OpLoc, SS, TemplateArgs != 0))
606 // Explicit member accesses.
608 ExprResult BaseResult = Owned(Base);
610 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
611 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
613 if (BaseResult.isInvalid())
615 Base = BaseResult.take();
617 if (Result.isInvalid()) {
625 // LookupMemberExpr can modify Base, and thus change BaseType
626 BaseType = Base->getType();
629 return BuildMemberReferenceExpr(Base, BaseType,
630 OpLoc, IsArrow, SS, FirstQualifierInScope,
635 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
636 const CXXScopeSpec &SS, FieldDecl *Field,
637 DeclAccessPair FoundDecl,
638 const DeclarationNameInfo &MemberNameInfo);
641 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
643 IndirectFieldDecl *indirectField,
644 Expr *baseObjectExpr,
645 SourceLocation opLoc) {
646 // First, build the expression that refers to the base object.
648 bool baseObjectIsPointer = false;
649 Qualifiers baseQuals;
651 // Case 1: the base of the indirect field is not a field.
652 VarDecl *baseVariable = indirectField->getVarDecl();
653 CXXScopeSpec EmptySS;
655 assert(baseVariable->getType()->isRecordType());
657 // In principle we could have a member access expression that
658 // accesses an anonymous struct/union that's a static member of
659 // the base object's class. However, under the current standard,
660 // static data members cannot be anonymous structs or unions.
661 // Supporting this is as easy as building a MemberExpr here.
662 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
664 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
667 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
668 if (result.isInvalid()) return ExprError();
670 baseObjectExpr = result.take();
671 baseObjectIsPointer = false;
672 baseQuals = baseObjectExpr->getType().getQualifiers();
674 // Case 2: the base of the indirect field is a field and the user
675 // wrote a member expression.
676 } else if (baseObjectExpr) {
677 // The caller provided the base object expression. Determine
678 // whether its a pointer and whether it adds any qualifiers to the
679 // anonymous struct/union fields we're looking into.
680 QualType objectType = baseObjectExpr->getType();
682 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
683 baseObjectIsPointer = true;
684 objectType = ptr->getPointeeType();
686 baseObjectIsPointer = false;
688 baseQuals = objectType.getQualifiers();
690 // Case 3: the base of the indirect field is a field and we should
691 // build an implicit member access.
693 // We've found a member of an anonymous struct/union that is
694 // inside a non-anonymous struct/union, so in a well-formed
695 // program our base object expression is "this".
696 QualType ThisTy = getAndCaptureCurrentThisType();
697 if (ThisTy.isNull()) {
698 Diag(loc, diag::err_invalid_member_use_in_static_method)
699 << indirectField->getDeclName();
703 // Our base object expression is "this".
705 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
706 baseObjectIsPointer = true;
707 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
710 // Build the implicit member references to the field of the
711 // anonymous struct/union.
712 Expr *result = baseObjectExpr;
713 IndirectFieldDecl::chain_iterator
714 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
716 // Build the first member access in the chain with full information.
718 FieldDecl *field = cast<FieldDecl>(*FI);
720 // FIXME: use the real found-decl info!
721 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
723 // Make a nameInfo that properly uses the anonymous name.
724 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
726 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
727 EmptySS, field, foundDecl,
728 memberNameInfo).take();
729 baseObjectIsPointer = false;
731 // FIXME: check qualified member access
734 // In all cases, we should now skip the first declaration in the chain.
738 FieldDecl *field = cast<FieldDecl>(*FI++);
740 // FIXME: these are somewhat meaningless
741 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
742 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
744 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
745 (FI == FEnd? SS : EmptySS), field,
746 foundDecl, memberNameInfo).take();
749 return Owned(result);
752 /// \brief Build a MemberExpr AST node.
753 static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
754 const CXXScopeSpec &SS, ValueDecl *Member,
755 DeclAccessPair FoundDecl,
756 const DeclarationNameInfo &MemberNameInfo,
758 ExprValueKind VK, ExprObjectKind OK,
759 const TemplateArgumentListInfo *TemplateArgs = 0) {
760 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
761 Member, FoundDecl, MemberNameInfo,
762 TemplateArgs, Ty, VK, OK);
766 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
767 SourceLocation OpLoc, bool IsArrow,
768 const CXXScopeSpec &SS,
769 NamedDecl *FirstQualifierInScope,
771 const TemplateArgumentListInfo *TemplateArgs,
772 bool SuppressQualifierCheck) {
773 QualType BaseType = BaseExprType;
775 assert(BaseType->isPointerType());
776 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
778 R.setBaseObjectType(BaseType);
780 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
781 DeclarationName MemberName = MemberNameInfo.getName();
782 SourceLocation MemberLoc = MemberNameInfo.getLoc();
788 // Rederive where we looked up.
789 DeclContext *DC = (SS.isSet()
790 ? computeDeclContext(SS, false)
791 : BaseType->getAs<RecordType>()->getDecl());
793 Diag(R.getNameLoc(), diag::err_no_member)
795 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
799 // Diagnose lookups that find only declarations from a non-base
800 // type. This is possible for either qualified lookups (which may
801 // have been qualified with an unrelated type) or implicit member
802 // expressions (which were found with unqualified lookup and thus
803 // may have come from an enclosing scope). Note that it's okay for
804 // lookup to find declarations from a non-base type as long as those
805 // aren't the ones picked by overload resolution.
806 if ((SS.isSet() || !BaseExpr ||
807 (isa<CXXThisExpr>(BaseExpr) &&
808 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
809 !SuppressQualifierCheck &&
810 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
813 // Construct an unresolved result if we in fact got an unresolved
815 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
816 // Suppress any lookup-related diagnostics; we'll do these when we
818 R.suppressDiagnostics();
820 UnresolvedMemberExpr *MemExpr
821 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
822 BaseExpr, BaseExprType,
824 SS.getWithLocInContext(Context),
826 TemplateArgs, R.begin(), R.end());
828 return Owned(MemExpr);
831 assert(R.isSingleResult());
832 DeclAccessPair FoundDecl = R.begin().getPair();
833 NamedDecl *MemberDecl = R.getFoundDecl();
835 // FIXME: diagnose the presence of template arguments now.
837 // If the decl being referenced had an error, return an error for this
838 // sub-expr without emitting another error, in order to avoid cascading
840 if (MemberDecl->isInvalidDecl())
843 // Handle the implicit-member-access case.
845 // If this is not an instance member, convert to a non-member access.
846 if (!MemberDecl->isCXXInstanceMember())
847 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
849 SourceLocation Loc = R.getNameLoc();
850 if (SS.getRange().isValid())
851 Loc = SS.getRange().getBegin();
852 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
855 bool ShouldCheckUse = true;
856 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
857 // Don't diagnose the use of a virtual member function unless it's
858 // explicitly qualified.
859 if (MD->isVirtual() && !SS.isSet())
860 ShouldCheckUse = false;
863 // Check the use of this member.
864 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
869 // Perform a property load on the base regardless of whether we
870 // actually need it for the declaration.
871 if (BaseExpr->getObjectKind() == OK_ObjCProperty) {
872 ExprResult Result = ConvertPropertyForRValue(BaseExpr);
873 if (Result.isInvalid())
875 BaseExpr = Result.take();
878 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
879 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
880 SS, FD, FoundDecl, MemberNameInfo);
882 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
883 // We may have found a field within an anonymous union or struct
884 // (C++ [class.union]).
885 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
888 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
889 MarkDeclarationReferenced(MemberLoc, Var);
890 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
891 Var, FoundDecl, MemberNameInfo,
892 Var->getType().getNonReferenceType(),
893 VK_LValue, OK_Ordinary));
896 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
897 ExprValueKind valueKind;
899 if (MemberFn->isInstance()) {
900 valueKind = VK_RValue;
901 type = Context.BoundMemberTy;
903 valueKind = VK_LValue;
904 type = MemberFn->getType();
907 MarkDeclarationReferenced(MemberLoc, MemberDecl);
908 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
909 MemberFn, FoundDecl, MemberNameInfo,
910 type, valueKind, OK_Ordinary));
912 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
914 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
915 MarkDeclarationReferenced(MemberLoc, MemberDecl);
916 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
917 Enum, FoundDecl, MemberNameInfo,
918 Enum->getType(), VK_RValue, OK_Ordinary));
923 // We found something that we didn't expect. Complain.
924 if (isa<TypeDecl>(MemberDecl))
925 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
926 << MemberName << BaseType << int(IsArrow);
928 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
929 << MemberName << BaseType << int(IsArrow);
931 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
933 R.suppressDiagnostics();
937 /// Given that normal member access failed on the given expression,
938 /// and given that the expression's type involves builtin-id or
939 /// builtin-Class, decide whether substituting in the redefinition
940 /// types would be profitable. The redefinition type is whatever
941 /// this translation unit tried to typedef to id/Class; we store
942 /// it to the side and then re-use it in places like this.
943 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
944 const ObjCObjectPointerType *opty
945 = base.get()->getType()->getAs<ObjCObjectPointerType>();
946 if (!opty) return false;
948 const ObjCObjectType *ty = opty->getObjectType();
951 if (ty->isObjCId()) {
952 redef = S.Context.ObjCIdRedefinitionType;
953 } else if (ty->isObjCClass()) {
954 redef = S.Context.ObjCClassRedefinitionType;
959 // Do the substitution as long as the redefinition type isn't just a
960 // possibly-qualified pointer to builtin-id or builtin-Class again.
961 opty = redef->getAs<ObjCObjectPointerType>();
962 if (opty && !opty->getObjectType()->getInterface() != 0)
965 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
969 /// Look up the given member of the given non-type-dependent
970 /// expression. This can return in one of two ways:
971 /// * If it returns a sentinel null-but-valid result, the caller will
972 /// assume that lookup was performed and the results written into
973 /// the provided structure. It will take over from there.
974 /// * Otherwise, the returned expression will be produced in place of
975 /// an ordinary member expression.
977 /// The ObjCImpDecl bit is a gross hack that will need to be properly
978 /// fixed for ObjC++.
980 Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
981 bool &IsArrow, SourceLocation OpLoc,
983 Decl *ObjCImpDecl, bool HasTemplateArgs) {
984 assert(BaseExpr.get() && "no base expression");
986 // Perform default conversions.
987 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
990 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
991 if (BaseExpr.isInvalid())
995 QualType BaseType = BaseExpr.get()->getType();
996 assert(!BaseType->isDependentType());
998 DeclarationName MemberName = R.getLookupName();
999 SourceLocation MemberLoc = R.getNameLoc();
1001 // For later type-checking purposes, turn arrow accesses into dot
1002 // accesses. The only access type we support that doesn't follow
1003 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1004 // and those never use arrows, so this is unaffected.
1006 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1007 BaseType = Ptr->getPointeeType();
1008 else if (const ObjCObjectPointerType *Ptr
1009 = BaseType->getAs<ObjCObjectPointerType>())
1010 BaseType = Ptr->getPointeeType();
1011 else if (BaseType->isRecordType()) {
1012 // Recover from arrow accesses to records, e.g.:
1013 // struct MyRecord foo;
1015 // This is actually well-formed in C++ if MyRecord has an
1016 // overloaded operator->, but that should have been dealt with
1018 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1019 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1020 << FixItHint::CreateReplacement(OpLoc, ".");
1022 } else if (BaseType == Context.BoundMemberTy) {
1025 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1026 << BaseType << BaseExpr.get()->getSourceRange();
1031 // Handle field access to simple records.
1032 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1033 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1034 RTy, OpLoc, SS, HasTemplateArgs))
1037 // Returning valid-but-null is how we indicate to the caller that
1038 // the lookup result was filled in.
1039 return Owned((Expr*) 0);
1042 // Handle ivar access to Objective-C objects.
1043 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1044 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1046 // There are three cases for the base type:
1047 // - builtin id (qualified or unqualified)
1048 // - builtin Class (qualified or unqualified)
1050 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1052 if (getLangOptions().ObjCAutoRefCount &&
1053 (OTy->isObjCId() || OTy->isObjCClass()))
1055 // There's an implicit 'isa' ivar on all objects.
1056 // But we only actually find it this way on objects of type 'id',
1058 if (OTy->isObjCId() && Member->isStr("isa"))
1059 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1060 Context.getObjCClassType()));
1062 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1063 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1064 ObjCImpDecl, HasTemplateArgs);
1068 ObjCInterfaceDecl *ClassDeclared;
1069 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1072 // Attempt to correct for typos in ivar names.
1073 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
1075 TypoCorrection Corrected = CorrectTypo(
1076 R.getLookupNameInfo(), LookupMemberName, NULL, NULL, IDecl, false,
1077 IsArrow ? CTC_ObjCIvarLookup : CTC_ObjCPropertyLookup);
1078 if ((IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>())) {
1079 Diag(R.getNameLoc(),
1080 diag::err_typecheck_member_reference_ivar_suggest)
1081 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1082 << FixItHint::CreateReplacement(R.getNameLoc(),
1083 IV->getNameAsString());
1084 Diag(IV->getLocation(), diag::note_previous_decl)
1085 << IV->getDeclName();
1087 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1089 diag::err_property_found_suggest)
1090 << Member << BaseExpr.get()->getType()
1091 << FixItHint::CreateReplacement(OpLoc, ".");
1095 Res.setLookupName(Member);
1097 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1098 << IDecl->getDeclName() << MemberName
1099 << BaseExpr.get()->getSourceRange();
1104 // If the decl being referenced had an error, return an error for this
1105 // sub-expr without emitting another error, in order to avoid cascading
1107 if (IV->isInvalidDecl())
1110 // Check whether we can reference this field.
1111 if (DiagnoseUseOfDecl(IV, MemberLoc))
1113 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1114 IV->getAccessControl() != ObjCIvarDecl::Package) {
1115 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1116 if (ObjCMethodDecl *MD = getCurMethodDecl())
1117 ClassOfMethodDecl = MD->getClassInterface();
1118 else if (ObjCImpDecl && getCurFunctionDecl()) {
1119 // Case of a c-function declared inside an objc implementation.
1120 // FIXME: For a c-style function nested inside an objc implementation
1121 // class, there is no implementation context available, so we pass
1122 // down the context as argument to this routine. Ideally, this context
1123 // need be passed down in the AST node and somehow calculated from the
1124 // AST for a function decl.
1125 if (ObjCImplementationDecl *IMPD =
1126 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1127 ClassOfMethodDecl = IMPD->getClassInterface();
1128 else if (ObjCCategoryImplDecl* CatImplClass =
1129 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1130 ClassOfMethodDecl = CatImplClass->getClassInterface();
1133 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1134 if (ClassDeclared != IDecl ||
1135 ClassOfMethodDecl != ClassDeclared)
1136 Diag(MemberLoc, diag::error_private_ivar_access)
1137 << IV->getDeclName();
1138 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1140 Diag(MemberLoc, diag::error_protected_ivar_access)
1141 << IV->getDeclName();
1143 if (getLangOptions().ObjCAutoRefCount) {
1144 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1145 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1146 if (UO->getOpcode() == UO_Deref)
1147 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1149 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1150 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1151 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1154 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1155 MemberLoc, BaseExpr.take(),
1159 // Objective-C property access.
1160 const ObjCObjectPointerType *OPT;
1161 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1162 // This actually uses the base as an r-value.
1163 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1164 if (BaseExpr.isInvalid())
1167 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1169 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1171 const ObjCObjectType *OT = OPT->getObjectType();
1173 // id, with and without qualifiers.
1174 if (OT->isObjCId()) {
1175 // Check protocols on qualified interfaces.
1176 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1177 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1178 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1179 // Check the use of this declaration
1180 if (DiagnoseUseOfDecl(PD, MemberLoc))
1183 QualType T = PD->getType();
1184 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
1185 T = getMessageSendResultType(BaseType, Getter, false, false);
1187 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
1194 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1195 // Check the use of this method.
1196 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1198 Selector SetterSel =
1199 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1200 PP.getSelectorTable(), Member);
1201 ObjCMethodDecl *SMD = 0;
1202 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1203 SetterSel, Context))
1204 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1205 QualType PType = getMessageSendResultType(BaseType, OMD, false,
1208 ExprValueKind VK = VK_LValue;
1209 if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType())
1211 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
1213 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
1215 MemberLoc, BaseExpr.take()));
1218 // Use of id.member can only be for a property reference. Do not
1219 // use the 'id' redefinition in this case.
1220 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1221 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1222 ObjCImpDecl, HasTemplateArgs);
1224 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1225 << MemberName << BaseType);
1228 // 'Class', unqualified only.
1229 if (OT->isObjCClass()) {
1230 // Only works in a method declaration (??!).
1231 ObjCMethodDecl *MD = getCurMethodDecl();
1233 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1234 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1235 ObjCImpDecl, HasTemplateArgs);
1240 // Also must look for a getter name which uses property syntax.
1241 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1242 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1243 ObjCMethodDecl *Getter;
1244 if ((Getter = IFace->lookupClassMethod(Sel))) {
1245 // Check the use of this method.
1246 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1249 Getter = IFace->lookupPrivateMethod(Sel, false);
1250 // If we found a getter then this may be a valid dot-reference, we
1251 // will look for the matching setter, in case it is needed.
1252 Selector SetterSel =
1253 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1254 PP.getSelectorTable(), Member);
1255 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1257 // If this reference is in an @implementation, also check for 'private'
1259 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1261 // Look through local category implementations associated with the class.
1263 Setter = IFace->getCategoryClassMethod(SetterSel);
1265 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1268 if (Getter || Setter) {
1271 ExprValueKind VK = VK_LValue;
1273 PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
1275 if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType())
1278 // Get the expression type from Setter's incoming parameter.
1279 PType = (*(Setter->param_end() -1))->getType();
1281 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
1283 // FIXME: we must check that the setter has property type.
1284 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1286 MemberLoc, BaseExpr.take()));
1289 if (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 // Normal property access.
1298 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1299 MemberName, MemberLoc,
1300 SourceLocation(), QualType(), false);
1303 // Handle 'field access' to vectors, such as 'V.xx'.
1304 if (BaseType->isExtVectorType()) {
1305 // FIXME: this expr should store IsArrow.
1306 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1307 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1308 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1313 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1314 *Member, MemberLoc));
1317 // Adjust builtin-sel to the appropriate redefinition type if that's
1318 // not just a pointer to builtin-sel again.
1320 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1321 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
1322 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
1324 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1325 ObjCImpDecl, HasTemplateArgs);
1331 // Recover from dot accesses to pointers, e.g.:
1334 // This is actually well-formed in two cases:
1335 // - 'type' is an Objective C type
1336 // - 'bar' is a pseudo-destructor name which happens to refer to
1337 // the appropriate pointer type
1338 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1339 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1340 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1341 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1342 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1343 << FixItHint::CreateReplacement(OpLoc, "->");
1345 // Recurse as an -> access.
1347 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1348 ObjCImpDecl, HasTemplateArgs);
1352 // If the user is trying to apply -> or . to a function name, it's probably
1353 // because they forgot parentheses to call that function.
1354 QualType ZeroArgCallTy;
1355 UnresolvedSet<4> Overloads;
1356 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
1357 if (ZeroArgCallTy.isNull()) {
1358 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
1359 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
1360 UnresolvedSet<2> PlausibleOverloads;
1361 for (OverloadExpr::decls_iterator It = Overloads.begin(),
1362 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1363 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1364 QualType OverloadResultTy = OverloadDecl->getResultType();
1365 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
1366 (IsArrow && OverloadResultTy->isPointerType() &&
1367 OverloadResultTy->getPointeeType()->isRecordType()))
1368 PlausibleOverloads.addDecl(It.getDecl());
1370 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
1373 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
1374 (IsArrow && ZeroArgCallTy->isPointerType() &&
1375 ZeroArgCallTy->getPointeeType()->isRecordType())) {
1376 // At this point, we know BaseExpr looks like it's potentially callable
1377 // with 0 arguments, and that it returns something of a reasonable type,
1378 // so we can emit a fixit and carry on pretending that BaseExpr was
1379 // actually a CallExpr.
1380 SourceLocation ParenInsertionLoc =
1381 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
1382 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
1383 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
1384 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
1385 // FIXME: Try this before emitting the fixit, and suppress diagnostics
1387 ExprResult NewBase =
1388 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
1389 MultiExprArg(*this, 0, 0),
1390 ParenInsertionLoc.getFileLocWithOffset(1));
1391 if (NewBase.isInvalid())
1394 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1395 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1396 ObjCImpDecl, HasTemplateArgs);
1400 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1401 << BaseType << BaseExpr.get()->getSourceRange();
1406 /// The main callback when the parser finds something like
1407 /// expression . [nested-name-specifier] identifier
1408 /// expression -> [nested-name-specifier] identifier
1409 /// where 'identifier' encompasses a fairly broad spectrum of
1410 /// possibilities, including destructor and operator references.
1412 /// \param OpKind either tok::arrow or tok::period
1413 /// \param HasTrailingLParen whether the next token is '(', which
1414 /// is used to diagnose mis-uses of special members that can
1416 /// \param ObjCImpDecl the current ObjC @implementation decl;
1417 /// this is an ugly hack around the fact that ObjC @implementations
1418 /// aren't properly put in the context chain
1419 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1420 SourceLocation OpLoc,
1421 tok::TokenKind OpKind,
1425 bool HasTrailingLParen) {
1426 if (SS.isSet() && SS.isInvalid())
1429 // Warn about the explicit constructor calls Microsoft extension.
1430 if (getLangOptions().Microsoft &&
1431 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1432 Diag(Id.getSourceRange().getBegin(),
1433 diag::ext_ms_explicit_constructor_call);
1435 TemplateArgumentListInfo TemplateArgsBuffer;
1437 // Decompose the name into its component parts.
1438 DeclarationNameInfo NameInfo;
1439 const TemplateArgumentListInfo *TemplateArgs;
1440 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1441 NameInfo, TemplateArgs);
1443 DeclarationName Name = NameInfo.getName();
1444 bool IsArrow = (OpKind == tok::arrow);
1446 NamedDecl *FirstQualifierInScope
1447 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1448 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1450 // This is a postfix expression, so get rid of ParenListExprs.
1451 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1452 if (Result.isInvalid()) return ExprError();
1453 Base = Result.take();
1455 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1456 isDependentScopeSpecifier(SS)) {
1457 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1459 SS, FirstQualifierInScope,
1460 NameInfo, TemplateArgs);
1462 LookupResult R(*this, NameInfo, LookupMemberName);
1463 ExprResult BaseResult = Owned(Base);
1464 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1465 SS, ObjCImpDecl, TemplateArgs != 0);
1466 if (BaseResult.isInvalid())
1468 Base = BaseResult.take();
1470 if (Result.isInvalid()) {
1476 // The only way a reference to a destructor can be used is to
1477 // immediately call it, which falls into this case. If the
1478 // next token is not a '(', produce a diagnostic and build the
1480 if (!HasTrailingLParen &&
1481 Id.getKind() == UnqualifiedId::IK_DestructorName)
1482 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1484 return move(Result);
1487 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1488 OpLoc, IsArrow, SS, FirstQualifierInScope,
1492 return move(Result);
1496 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1497 const CXXScopeSpec &SS, FieldDecl *Field,
1498 DeclAccessPair FoundDecl,
1499 const DeclarationNameInfo &MemberNameInfo) {
1500 // x.a is an l-value if 'a' has a reference type. Otherwise:
1501 // x.a is an l-value/x-value/pr-value if the base is (and note
1502 // that *x is always an l-value), except that if the base isn't
1503 // an ordinary object then we must have an rvalue.
1504 ExprValueKind VK = VK_LValue;
1505 ExprObjectKind OK = OK_Ordinary;
1507 if (BaseExpr->getObjectKind() == OK_Ordinary)
1508 VK = BaseExpr->getValueKind();
1512 if (VK != VK_RValue && Field->isBitField())
1515 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1516 QualType MemberType = Field->getType();
1517 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1518 MemberType = Ref->getPointeeType();
1521 QualType BaseType = BaseExpr->getType();
1522 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1524 Qualifiers BaseQuals = BaseType.getQualifiers();
1526 // GC attributes are never picked up by members.
1527 BaseQuals.removeObjCGCAttr();
1529 // CVR attributes from the base are picked up by members,
1530 // except that 'mutable' members don't pick up 'const'.
1531 if (Field->isMutable()) BaseQuals.removeConst();
1533 Qualifiers MemberQuals
1534 = S.Context.getCanonicalType(MemberType).getQualifiers();
1536 // TR 18037 does not allow fields to be declared with address spaces.
1537 assert(!MemberQuals.hasAddressSpace());
1539 Qualifiers Combined = BaseQuals + MemberQuals;
1540 if (Combined != MemberQuals)
1541 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1544 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1546 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1548 if (Base.isInvalid())
1550 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
1551 Field, FoundDecl, MemberNameInfo,
1552 MemberType, VK, OK));
1555 /// Builds an implicit member access expression. The current context
1556 /// is known to be an instance method, and the given unqualified lookup
1557 /// set is known to contain only instance members, at least one of which
1558 /// is from an appropriate type.
1560 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1562 const TemplateArgumentListInfo *TemplateArgs,
1563 bool IsKnownInstance) {
1564 assert(!R.empty() && !R.isAmbiguous());
1566 SourceLocation loc = R.getNameLoc();
1568 // We may have found a field within an anonymous union or struct
1569 // (C++ [class.union]).
1570 // FIXME: template-ids inside anonymous structs?
1571 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1572 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1574 // If this is known to be an instance access, go ahead and build an
1575 // implicit 'this' expression now.
1576 // 'this' expression now.
1577 QualType ThisTy = getAndCaptureCurrentThisType();
1578 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1580 Expr *baseExpr = 0; // null signifies implicit access
1581 if (IsKnownInstance) {
1582 SourceLocation Loc = R.getNameLoc();
1583 if (SS.getRange().isValid())
1584 Loc = SS.getRange().getBegin();
1585 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1588 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1589 /*OpLoc*/ SourceLocation(),
1592 /*FirstQualifierInScope*/ 0,