blob: 7151fc55041464d1ef42e9e9b1e4620ff33f3748 [file] [log] [blame]
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis member access expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/SemaInternal.h"
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000014#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000023
24using namespace clang;
25using namespace sema;
26
Richard Smithf62c6902012-11-22 00:24:47 +000027typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
28static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
29 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
30 return !Bases.count(Base->getCanonicalDecl());
31}
32
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000033/// Determines if the given class is provably not derived from all of
34/// the prospective base classes.
Richard Smithf62c6902012-11-22 00:24:47 +000035static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
36 const BaseSet &Bases) {
37 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
38 return BaseIsNotInSet(Record, BasesPtr) &&
39 Record->forallBases(BaseIsNotInSet, BasesPtr);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000040}
41
42enum IMAKind {
43 /// The reference is definitely not an instance member access.
44 IMA_Static,
45
46 /// The reference may be an implicit instance member access.
47 IMA_Mixed,
48
Eli Friedman9bc291d2012-01-18 03:53:45 +000049 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000050 /// so, because the context is not an instance method.
51 IMA_Mixed_StaticContext,
52
53 /// The reference may be to an instance member, but it is invalid if
54 /// so, because the context is from an unrelated class.
55 IMA_Mixed_Unrelated,
56
57 /// The reference is definitely an implicit instance member access.
58 IMA_Instance,
59
60 /// The reference may be to an unresolved using declaration.
61 IMA_Unresolved,
62
John McCallaeeacf72013-05-03 00:10:13 +000063 /// The reference is a contextually-permitted abstract member reference.
64 IMA_Abstract,
65
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000066 /// The reference may be to an unresolved using declaration and the
67 /// context is not an instance method.
68 IMA_Unresolved_StaticContext,
69
Eli Friedmanef331b72012-01-20 01:26:23 +000070 // The reference refers to a field which is not a member of the containing
71 // class, which is allowed because we're in C++11 mode and the context is
72 // unevaluated.
73 IMA_Field_Uneval_Context,
Eli Friedman9bc291d2012-01-18 03:53:45 +000074
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000075 /// All possible referrents are instance members and the current
76 /// context is not an instance method.
77 IMA_Error_StaticContext,
78
79 /// All possible referrents are instance members of an unrelated
80 /// class.
81 IMA_Error_Unrelated
82};
83
84/// The given lookup names class member(s) and is not being used for
85/// an address-of-member expression. Classify the type of access
86/// according to whether it's possible that this reference names an
Eli Friedman9bc291d2012-01-18 03:53:45 +000087/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000088/// conservatively answer "yes", in which case some errors will simply
89/// not be caught until template-instantiation.
90static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
91 Scope *CurScope,
92 const LookupResult &R) {
93 assert(!R.empty() && (*R.begin())->isCXXClassMember());
94
95 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
96
Douglas Gregorcefc3af2012-04-16 07:05:22 +000097 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
98 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000099
100 if (R.isUnresolvableResult())
101 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
102
103 // Collect all the declaring classes of instance members we find.
104 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000105 bool isField = false;
Richard Smithf62c6902012-11-22 00:24:47 +0000106 BaseSet Classes;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000107 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
108 NamedDecl *D = *I;
109
110 if (D->isCXXInstanceMember()) {
John McCall76da55d2013-04-16 07:28:30 +0000111 if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
112 || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000113 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000114
115 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
116 Classes.insert(R->getCanonicalDecl());
117 }
118 else
119 hasNonInstance = true;
120 }
121
122 // If we didn't find any instance members, it can't be an implicit
123 // member reference.
124 if (Classes.empty())
125 return IMA_Static;
John McCallaeeacf72013-05-03 00:10:13 +0000126
127 // C++11 [expr.prim.general]p12:
128 // An id-expression that denotes a non-static data member or non-static
129 // member function of a class can only be used:
130 // (...)
131 // - if that id-expression denotes a non-static data member and it
132 // appears in an unevaluated operand.
133 //
134 // This rule is specific to C++11. However, we also permit this form
135 // in unevaluated inline assembly operands, like the operand to a SIZE.
136 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
137 assert(!AbstractInstanceResult);
138 switch (SemaRef.ExprEvalContexts.back().Context) {
139 case Sema::Unevaluated:
140 if (isField && SemaRef.getLangOpts().CPlusPlus11)
141 AbstractInstanceResult = IMA_Field_Uneval_Context;
142 break;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000143
John McCallaeeacf72013-05-03 00:10:13 +0000144 case Sema::UnevaluatedAbstract:
145 AbstractInstanceResult = IMA_Abstract;
146 break;
147
148 case Sema::ConstantEvaluated:
149 case Sema::PotentiallyEvaluated:
150 case Sema::PotentiallyEvaluatedIfUsed:
151 break;
Richard Smith2c8aee42012-02-25 10:04:07 +0000152 }
153
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000154 // If the current context is not an instance method, it can't be
155 // an implicit member reference.
156 if (isStaticContext) {
157 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000158 return IMA_Mixed_StaticContext;
159
John McCallaeeacf72013-05-03 00:10:13 +0000160 return AbstractInstanceResult ? AbstractInstanceResult
161 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000162 }
163
164 CXXRecordDecl *contextClass;
165 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
166 contextClass = MD->getParent()->getCanonicalDecl();
167 else
168 contextClass = cast<CXXRecordDecl>(DC);
169
170 // [class.mfct.non-static]p3:
171 // ...is used in the body of a non-static member function of class X,
172 // if name lookup (3.4.1) resolves the name in the id-expression to a
173 // non-static non-type member of some class C [...]
174 // ...if C is not X or a base class of X, the class member access expression
175 // is ill-formed.
176 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000177 contextClass->getCanonicalDecl() !=
Richard Smithf62c6902012-11-22 00:24:47 +0000178 R.getNamingClass()->getCanonicalDecl()) {
179 // If the naming class is not the current context, this was a qualified
180 // member name lookup, and it's sufficient to check that we have the naming
181 // class as a base class.
182 Classes.clear();
Richard Smith746619a2012-11-22 00:40:54 +0000183 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithf62c6902012-11-22 00:24:47 +0000184 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000185
186 // If we can prove that the current context is unrelated to all the
187 // declaring classes, it can't be an implicit member reference (in
188 // which case it's an error if any of those members are selected).
Richard Smithf62c6902012-11-22 00:24:47 +0000189 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smithd390de92012-02-25 10:20:59 +0000190 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallaeeacf72013-05-03 00:10:13 +0000191 AbstractInstanceResult ? AbstractInstanceResult :
192 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000193
194 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
195}
196
197/// Diagnose a reference to a field with no object available.
Richard Smitha85cf392012-04-05 01:13:04 +0000198static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000199 const CXXScopeSpec &SS,
Richard Smitha85cf392012-04-05 01:13:04 +0000200 NamedDecl *Rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000201 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000202 SourceLocation Loc = nameInfo.getLoc();
203 SourceRange Range(Loc);
204 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman9bc291d2012-01-18 03:53:45 +0000205
Richard Smitha85cf392012-04-05 01:13:04 +0000206 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
207 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
208 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
209 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
210
211 bool InStaticMethod = Method && Method->isStatic();
212 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
213
214 if (IsField && InStaticMethod)
215 // "invalid use of member 'x' in static member function"
216 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
217 << Range << nameInfo.getName();
218 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
219 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
220 // Unqualified lookup in a non-static member function found a member of an
221 // enclosing class.
222 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
223 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
224 else if (IsField)
Eli Friedmanef331b72012-01-20 01:26:23 +0000225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smitha85cf392012-04-05 01:13:04 +0000226 << nameInfo.getName() << Range;
227 else
228 SemaRef.Diag(Loc, diag::err_member_call_without_object)
229 << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000230}
231
232/// Builds an expression which might be an implicit member expression.
233ExprResult
234Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000235 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000236 LookupResult &R,
237 const TemplateArgumentListInfo *TemplateArgs) {
238 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
239 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000240 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000241
242 case IMA_Mixed:
243 case IMA_Mixed_Unrelated:
244 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000245 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000246
Richard Smithd390de92012-02-25 10:20:59 +0000247 case IMA_Field_Uneval_Context:
248 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
249 << R.getLookupNameInfo().getName();
250 // Fall through.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000251 case IMA_Static:
John McCallaeeacf72013-05-03 00:10:13 +0000252 case IMA_Abstract:
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000253 case IMA_Mixed_StaticContext:
254 case IMA_Unresolved_StaticContext:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000255 if (TemplateArgs || TemplateKWLoc.isValid())
256 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000257 return BuildDeclarationNameExpr(SS, R, false);
258
259 case IMA_Error_StaticContext:
260 case IMA_Error_Unrelated:
Richard Smitha85cf392012-04-05 01:13:04 +0000261 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000262 R.getLookupNameInfo());
263 return ExprError();
264 }
265
266 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000267}
268
269/// Check an ext-vector component access expression.
270///
271/// VK should be set in advance to the value kind of the base
272/// expression.
273static QualType
274CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
275 SourceLocation OpLoc, const IdentifierInfo *CompName,
276 SourceLocation CompLoc) {
277 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
278 // see FIXME there.
279 //
280 // FIXME: This logic can be greatly simplified by splitting it along
281 // halving/not halving and reworking the component checking.
282 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
283
284 // The vector accessor can't exceed the number of elements.
285 const char *compStr = CompName->getNameStart();
286
287 // This flag determines whether or not the component is one of the four
288 // special names that indicate a subset of exactly half the elements are
289 // to be selected.
290 bool HalvingSwizzle = false;
291
292 // This flag determines whether or not CompName has an 's' char prefix,
293 // indicating that it is a string of hex values to be used as vector indices.
294 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
295
296 bool HasRepeated = false;
297 bool HasIndex[16] = {};
298
299 int Idx;
300
301 // Check that we've found one of the special components, or that the component
302 // names must come from the same set.
303 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
304 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
305 HalvingSwizzle = true;
306 } else if (!HexSwizzle &&
307 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
308 do {
309 if (HasIndex[Idx]) HasRepeated = true;
310 HasIndex[Idx] = true;
311 compStr++;
312 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
313 } else {
314 if (HexSwizzle) compStr++;
315 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
316 if (HasIndex[Idx]) HasRepeated = true;
317 HasIndex[Idx] = true;
318 compStr++;
319 }
320 }
321
322 if (!HalvingSwizzle && *compStr) {
323 // We didn't get to the end of the string. This means the component names
324 // didn't come from the same set *or* we encountered an illegal name.
325 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000326 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000327 return QualType();
328 }
329
330 // Ensure no component accessor exceeds the width of the vector type it
331 // operates on.
332 if (!HalvingSwizzle) {
333 compStr = CompName->getNameStart();
334
335 if (HexSwizzle)
336 compStr++;
337
338 while (*compStr) {
339 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
340 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
341 << baseType << SourceRange(CompLoc);
342 return QualType();
343 }
344 }
345 }
346
347 // The component accessor looks fine - now we need to compute the actual type.
348 // The vector type is implied by the component accessor. For example,
349 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
350 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
351 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
352 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
353 : CompName->getLength();
354 if (HexSwizzle)
355 CompSize--;
356
357 if (CompSize == 1)
358 return vecType->getElementType();
359
360 if (HasRepeated) VK = VK_RValue;
361
362 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
363 // Now look up the TypeDefDecl from the vector type. Without this,
364 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000365 for (Sema::ExtVectorDeclsType::iterator
Axel Naumann0ec56b72012-10-18 19:05:02 +0000366 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregord58a0a52011-07-28 00:39:29 +0000367 E = S.ExtVectorDecls.end();
368 I != E; ++I) {
369 if ((*I)->getUnderlyingType() == VT)
370 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000371 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000372
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000373 return VT; // should never get here (a typedef type should always be found).
374}
375
376static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
377 IdentifierInfo *Member,
378 const Selector &Sel,
379 ASTContext &Context) {
380 if (Member)
381 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
382 return PD;
383 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
384 return OMD;
385
386 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
387 E = PDecl->protocol_end(); I != E; ++I) {
388 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
389 Context))
390 return D;
391 }
392 return 0;
393}
394
395static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
396 IdentifierInfo *Member,
397 const Selector &Sel,
398 ASTContext &Context) {
399 // Check protocols on qualified interfaces.
400 Decl *GDecl = 0;
401 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
402 E = QIdTy->qual_end(); I != E; ++I) {
403 if (Member)
404 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
405 GDecl = PD;
406 break;
407 }
408 // Also must look for a getter or setter name which uses property syntax.
409 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
410 GDecl = OMD;
411 break;
412 }
413 }
414 if (!GDecl) {
415 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
416 E = QIdTy->qual_end(); I != E; ++I) {
417 // Search in the protocol-qualifier list of current protocol.
418 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
419 Context);
420 if (GDecl)
421 return GDecl;
422 }
423 }
424 return GDecl;
425}
426
427ExprResult
428Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
429 bool IsArrow, SourceLocation OpLoc,
430 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000431 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000432 NamedDecl *FirstQualifierInScope,
433 const DeclarationNameInfo &NameInfo,
434 const TemplateArgumentListInfo *TemplateArgs) {
435 // Even in dependent contexts, try to diagnose base expressions with
436 // obviously wrong types, e.g.:
437 //
438 // T* t;
439 // t.f;
440 //
441 // In Obj-C++, however, the above expression is valid, since it could be
442 // accessing the 'f' property if T is an Obj-C interface. The extra check
443 // allows this, while still reporting an error if T is a struct pointer.
444 if (!IsArrow) {
445 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikie4e4d0842012-03-11 07:00:24 +0000446 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000447 PT->getPointeeType()->isRecordType())) {
448 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +0000449 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +0000450 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000451 return ExprError();
452 }
453 }
454
455 assert(BaseType->isDependentType() ||
456 NameInfo.getName().isDependentName() ||
457 isDependentScopeSpecifier(SS));
458
459 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
460 // must have pointer type, and the accessed type is the pointee.
461 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
462 IsArrow, OpLoc,
463 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000464 TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000465 FirstQualifierInScope,
466 NameInfo, TemplateArgs));
467}
468
469/// We know that the given qualified member reference points only to
470/// declarations which do not belong to the static type of the base
471/// expression. Diagnose the problem.
472static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
473 Expr *BaseExpr,
474 QualType BaseType,
475 const CXXScopeSpec &SS,
476 NamedDecl *rep,
477 const DeclarationNameInfo &nameInfo) {
478 // If this is an implicit member access, use a different set of
479 // diagnostics.
480 if (!BaseExpr)
Richard Smitha85cf392012-04-05 01:13:04 +0000481 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000482
483 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
484 << SS.getRange() << rep << BaseType;
485}
486
487// Check whether the declarations we found through a nested-name
488// specifier in a member expression are actually members of the base
489// type. The restriction here is:
490//
491// C++ [expr.ref]p2:
492// ... In these cases, the id-expression shall name a
493// member of the class or of one of its base classes.
494//
495// So it's perfectly legitimate for the nested-name specifier to name
496// an unrelated class, and for us to find an overload set including
497// decls from classes which are not superclasses, as long as the decl
498// we actually pick through overload resolution is from a superclass.
499bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
500 QualType BaseType,
501 const CXXScopeSpec &SS,
502 const LookupResult &R) {
Richard Smithf62c6902012-11-22 00:24:47 +0000503 CXXRecordDecl *BaseRecord =
504 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
505 if (!BaseRecord) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000506 // We can't check this yet because the base type is still
507 // dependent.
508 assert(BaseType->isDependentType());
509 return false;
510 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000511
512 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
513 // If this is an implicit member reference and we find a
514 // non-instance member, it's not an error.
515 if (!BaseExpr && !(*I)->isCXXInstanceMember())
516 return false;
517
518 // Note that we use the DC of the decl, not the underlying decl.
519 DeclContext *DC = (*I)->getDeclContext();
520 while (DC->isTransparentContext())
521 DC = DC->getParent();
522
523 if (!DC->isRecord())
524 continue;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000525
Richard Smithf62c6902012-11-22 00:24:47 +0000526 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
527 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
528 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000529 return false;
530 }
531
532 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
533 R.getRepresentativeDecl(),
534 R.getLookupNameInfo());
535 return true;
536}
537
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000538namespace {
539
540// Callback to only accept typo corrections that are either a ValueDecl or a
541// FunctionTemplateDecl.
542class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
543 public:
544 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
545 NamedDecl *ND = candidate.getCorrectionDecl();
546 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
547 }
548};
549
550}
551
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000552static bool
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000553LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000554 SourceRange BaseRange, const RecordType *RTy,
555 SourceLocation OpLoc, CXXScopeSpec &SS,
556 bool HasTemplateArgs) {
557 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000558 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
559 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregord10099e2012-05-04 16:32:21 +0000560 diag::err_typecheck_incomplete_tag,
561 BaseRange))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000562 return true;
563
564 if (HasTemplateArgs) {
565 // LookupTemplateName doesn't expect these both to exist simultaneously.
566 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
567
568 bool MOUS;
569 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
570 return false;
571 }
572
573 DeclContext *DC = RDecl;
574 if (SS.isSet()) {
575 // If the member name was a qualified-id, look into the
576 // nested-name-specifier.
577 DC = SemaRef.computeDeclContext(SS, false);
578
579 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
580 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
581 << SS.getRange() << DC;
582 return true;
583 }
584
585 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
586
587 if (!isa<TypeDecl>(DC)) {
588 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
589 << DC << SS.getRange();
590 return true;
591 }
592 }
593
594 // The record definition is complete, now look up the member.
595 SemaRef.LookupQualifiedName(R, DC);
596
597 if (!R.empty())
598 return false;
599
600 // We didn't find anything with the given name, so try to correct
601 // for typos.
602 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000603 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000604 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
605 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000606 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000607 R.clear();
Nick Lewyckyd9de51f2013-05-07 22:14:37 +0000608 if (Corrected.isResolved() && !Corrected.isKeyword()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000609 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000610 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000611 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000612 Corrected.getQuoted(SemaRef.getLangOpts()));
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000613 bool droppedSpecifier =
614 Corrected.WillReplaceSpecifier() && Name.getAsString() == CorrectedStr;
Nick Lewyckyd9de51f2013-05-07 22:14:37 +0000615
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000616 R.setLookupName(Corrected.getCorrection());
Nick Lewyckyd9de51f2013-05-07 22:14:37 +0000617 for (TypoCorrection::decl_iterator DI = Corrected.begin(),
618 DIEnd = Corrected.end();
619 DI != DIEnd; ++DI) {
620 R.addDecl(*DI);
621 }
622 R.resolveKind();
623
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000624 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Kaelyn Uhrainb2567dd2013-07-02 23:47:44 +0000625 << Name << DC << droppedSpecifier << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +0000626 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
627 CorrectedStr);
Nick Lewyckyd9de51f2013-05-07 22:14:37 +0000628
629 // If we're typo-correcting to an overloaded name, we don't yet have enough
630 // information to do overload resolution, so we don't know which previous
631 // declaration to point to.
632 if (!Corrected.isOverloaded()) {
633 NamedDecl *ND = Corrected.getCorrectionDecl();
634 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
635 << ND->getDeclName();
636 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000637 }
638
639 return false;
640}
641
642ExprResult
643Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
644 SourceLocation OpLoc, bool IsArrow,
645 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000646 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000647 NamedDecl *FirstQualifierInScope,
648 const DeclarationNameInfo &NameInfo,
649 const TemplateArgumentListInfo *TemplateArgs) {
650 if (BaseType->isDependentType() ||
651 (SS.isSet() && isDependentScopeSpecifier(SS)))
652 return ActOnDependentMemberExpr(Base, BaseType,
653 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000654 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000655 NameInfo, TemplateArgs);
656
657 LookupResult R(*this, NameInfo, LookupMemberName);
658
659 // Implicit member accesses.
660 if (!Base) {
661 QualType RecordTy = BaseType;
662 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
663 if (LookupMemberExprInRecord(*this, R, SourceRange(),
664 RecordTy->getAs<RecordType>(),
665 OpLoc, SS, TemplateArgs != 0))
666 return ExprError();
667
668 // Explicit member accesses.
669 } else {
670 ExprResult BaseResult = Owned(Base);
671 ExprResult Result =
672 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
673 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
674
675 if (BaseResult.isInvalid())
676 return ExprError();
677 Base = BaseResult.take();
678
679 if (Result.isInvalid()) {
680 Owned(Base);
681 return ExprError();
682 }
683
684 if (Result.get())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000685 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000686
687 // LookupMemberExpr can modify Base, and thus change BaseType
688 BaseType = Base->getType();
689 }
690
691 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000692 OpLoc, IsArrow, SS, TemplateKWLoc,
693 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000694}
695
696static ExprResult
697BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
698 const CXXScopeSpec &SS, FieldDecl *Field,
699 DeclAccessPair FoundDecl,
700 const DeclarationNameInfo &MemberNameInfo);
701
702ExprResult
703Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
704 SourceLocation loc,
705 IndirectFieldDecl *indirectField,
706 Expr *baseObjectExpr,
707 SourceLocation opLoc) {
708 // First, build the expression that refers to the base object.
709
710 bool baseObjectIsPointer = false;
711 Qualifiers baseQuals;
712
713 // Case 1: the base of the indirect field is not a field.
714 VarDecl *baseVariable = indirectField->getVarDecl();
715 CXXScopeSpec EmptySS;
716 if (baseVariable) {
717 assert(baseVariable->getType()->isRecordType());
718
719 // In principle we could have a member access expression that
720 // accesses an anonymous struct/union that's a static member of
721 // the base object's class. However, under the current standard,
722 // static data members cannot be anonymous structs or unions.
723 // Supporting this is as easy as building a MemberExpr here.
724 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
725
726 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
727
728 ExprResult result
729 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
730 if (result.isInvalid()) return ExprError();
731
732 baseObjectExpr = result.take();
733 baseObjectIsPointer = false;
734 baseQuals = baseObjectExpr->getType().getQualifiers();
735
736 // Case 2: the base of the indirect field is a field and the user
737 // wrote a member expression.
738 } else if (baseObjectExpr) {
739 // The caller provided the base object expression. Determine
740 // whether its a pointer and whether it adds any qualifiers to the
741 // anonymous struct/union fields we're looking into.
742 QualType objectType = baseObjectExpr->getType();
743
744 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
745 baseObjectIsPointer = true;
746 objectType = ptr->getPointeeType();
747 } else {
748 baseObjectIsPointer = false;
749 }
750 baseQuals = objectType.getQualifiers();
751
752 // Case 3: the base of the indirect field is a field and we should
753 // build an implicit member access.
754 } else {
755 // We've found a member of an anonymous struct/union that is
756 // inside a non-anonymous struct/union, so in a well-formed
757 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000758 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000759 if (ThisTy.isNull()) {
760 Diag(loc, diag::err_invalid_member_use_in_static_method)
761 << indirectField->getDeclName();
762 return ExprError();
763 }
764
765 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000766 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000767 baseObjectExpr
768 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
769 baseObjectIsPointer = true;
770 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
771 }
772
773 // Build the implicit member references to the field of the
774 // anonymous struct/union.
775 Expr *result = baseObjectExpr;
776 IndirectFieldDecl::chain_iterator
777 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
778
779 // Build the first member access in the chain with full information.
780 if (!baseVariable) {
781 FieldDecl *field = cast<FieldDecl>(*FI);
782
783 // FIXME: use the real found-decl info!
784 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
785
786 // Make a nameInfo that properly uses the anonymous name.
787 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
788
789 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
790 EmptySS, field, foundDecl,
791 memberNameInfo).take();
792 baseObjectIsPointer = false;
793
794 // FIXME: check qualified member access
795 }
796
797 // In all cases, we should now skip the first declaration in the chain.
798 ++FI;
799
800 while (FI != FEnd) {
801 FieldDecl *field = cast<FieldDecl>(*FI++);
802
803 // FIXME: these are somewhat meaningless
804 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
805 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
806
807 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
808 (FI == FEnd? SS : EmptySS), field,
809 foundDecl, memberNameInfo).take();
810 }
811
812 return Owned(result);
813}
814
John McCall76da55d2013-04-16 07:28:30 +0000815static ExprResult
816BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
817 const CXXScopeSpec &SS,
818 MSPropertyDecl *PD,
819 const DeclarationNameInfo &NameInfo) {
820 // Property names are always simple identifiers and therefore never
821 // require any interesting additional storage.
822 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
823 S.Context.PseudoObjectTy, VK_LValue,
824 SS.getWithLocInContext(S.Context),
825 NameInfo.getLoc());
826}
827
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000828/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000829static MemberExpr *BuildMemberExpr(Sema &SemaRef,
830 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000831 const CXXScopeSpec &SS,
832 SourceLocation TemplateKWLoc,
833 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000834 DeclAccessPair FoundDecl,
835 const DeclarationNameInfo &MemberNameInfo,
836 QualType Ty,
837 ExprValueKind VK, ExprObjectKind OK,
838 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000839 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000840 MemberExpr *E =
841 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
842 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
843 TemplateArgs, Ty, VK, OK);
844 SemaRef.MarkMemberReferenced(E);
845 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000846}
847
848ExprResult
849Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
850 SourceLocation OpLoc, bool IsArrow,
851 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000852 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000853 NamedDecl *FirstQualifierInScope,
854 LookupResult &R,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000855 const TemplateArgumentListInfo *TemplateArgs,
856 bool SuppressQualifierCheck,
857 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000858 QualType BaseType = BaseExprType;
859 if (IsArrow) {
860 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000861 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000862 }
863 R.setBaseObjectType(BaseType);
864
865 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
866 DeclarationName MemberName = MemberNameInfo.getName();
867 SourceLocation MemberLoc = MemberNameInfo.getLoc();
868
869 if (R.isAmbiguous())
870 return ExprError();
871
872 if (R.empty()) {
873 // Rederive where we looked up.
874 DeclContext *DC = (SS.isSet()
875 ? computeDeclContext(SS, false)
876 : BaseType->getAs<RecordType>()->getDecl());
877
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000878 if (ExtraArgs) {
879 ExprResult RetryExpr;
880 if (!IsArrow && BaseExpr) {
Kaelyn Uhrain111263c2012-05-01 01:17:53 +0000881 SFINAETrap Trap(*this, true);
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000882 ParsedType ObjectType;
883 bool MayBePseudoDestructor = false;
884 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
885 OpLoc, tok::arrow, ObjectType,
886 MayBePseudoDestructor);
887 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
888 CXXScopeSpec TempSS(SS);
889 RetryExpr = ActOnMemberAccessExpr(
890 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
891 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
892 ExtraArgs->HasTrailingLParen);
893 }
894 if (Trap.hasErrorOccurred())
895 RetryExpr = ExprError();
896 }
897 if (RetryExpr.isUsable()) {
898 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
899 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
900 return RetryExpr;
901 }
902 }
903
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000904 Diag(R.getNameLoc(), diag::err_no_member)
905 << MemberName << DC
906 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
907 return ExprError();
908 }
909
910 // Diagnose lookups that find only declarations from a non-base
911 // type. This is possible for either qualified lookups (which may
912 // have been qualified with an unrelated type) or implicit member
913 // expressions (which were found with unqualified lookup and thus
914 // may have come from an enclosing scope). Note that it's okay for
915 // lookup to find declarations from a non-base type as long as those
916 // aren't the ones picked by overload resolution.
917 if ((SS.isSet() || !BaseExpr ||
918 (isa<CXXThisExpr>(BaseExpr) &&
919 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
920 !SuppressQualifierCheck &&
921 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
922 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000923
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000924 // Construct an unresolved result if we in fact got an unresolved
925 // result.
926 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
927 // Suppress any lookup-related diagnostics; we'll do these when we
928 // pick a member.
929 R.suppressDiagnostics();
930
931 UnresolvedMemberExpr *MemExpr
932 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
933 BaseExpr, BaseExprType,
934 IsArrow, OpLoc,
935 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000936 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000937 TemplateArgs, R.begin(), R.end());
938
939 return Owned(MemExpr);
940 }
941
942 assert(R.isSingleResult());
943 DeclAccessPair FoundDecl = R.begin().getPair();
944 NamedDecl *MemberDecl = R.getFoundDecl();
945
946 // FIXME: diagnose the presence of template arguments now.
947
948 // If the decl being referenced had an error, return an error for this
949 // sub-expr without emitting another error, in order to avoid cascading
950 // error cases.
951 if (MemberDecl->isInvalidDecl())
952 return ExprError();
953
954 // Handle the implicit-member-access case.
955 if (!BaseExpr) {
956 // If this is not an instance member, convert to a non-member access.
957 if (!MemberDecl->isCXXInstanceMember())
958 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
959
960 SourceLocation Loc = R.getNameLoc();
961 if (SS.getRange().isValid())
962 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000963 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000964 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
965 }
966
967 bool ShouldCheckUse = true;
968 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
969 // Don't diagnose the use of a virtual member function unless it's
970 // explicitly qualified.
971 if (MD->isVirtual() && !SS.isSet())
972 ShouldCheckUse = false;
973 }
974
975 // Check the use of this member.
976 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
977 Owned(BaseExpr);
978 return ExprError();
979 }
980
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000981 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
982 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
983 SS, FD, FoundDecl, MemberNameInfo);
984
John McCall76da55d2013-04-16 07:28:30 +0000985 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
986 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
987 MemberNameInfo);
988
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000989 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
990 // We may have found a field within an anonymous union or struct
991 // (C++ [class.union]).
992 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
993 BaseExpr, OpLoc);
994
995 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000996 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
997 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000998 Var->getType().getNonReferenceType(),
999 VK_LValue, OK_Ordinary));
1000 }
1001
1002 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1003 ExprValueKind valueKind;
1004 QualType type;
1005 if (MemberFn->isInstance()) {
1006 valueKind = VK_RValue;
1007 type = Context.BoundMemberTy;
1008 } else {
1009 valueKind = VK_LValue;
1010 type = MemberFn->getType();
1011 }
1012
Eli Friedman5f2987c2012-02-02 03:46:19 +00001013 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1014 TemplateKWLoc, MemberFn, FoundDecl,
1015 MemberNameInfo, type, valueKind,
1016 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001017 }
1018 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1019
1020 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +00001021 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1022 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001023 Enum->getType(), VK_RValue, OK_Ordinary));
1024 }
1025
1026 Owned(BaseExpr);
1027
1028 // We found something that we didn't expect. Complain.
1029 if (isa<TypeDecl>(MemberDecl))
1030 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1031 << MemberName << BaseType << int(IsArrow);
1032 else
1033 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1034 << MemberName << BaseType << int(IsArrow);
1035
1036 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1037 << MemberName;
1038 R.suppressDiagnostics();
1039 return ExprError();
1040}
1041
1042/// Given that normal member access failed on the given expression,
1043/// and given that the expression's type involves builtin-id or
1044/// builtin-Class, decide whether substituting in the redefinition
1045/// types would be profitable. The redefinition type is whatever
1046/// this translation unit tried to typedef to id/Class; we store
1047/// it to the side and then re-use it in places like this.
1048static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1049 const ObjCObjectPointerType *opty
1050 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1051 if (!opty) return false;
1052
1053 const ObjCObjectType *ty = opty->getObjectType();
1054
1055 QualType redef;
1056 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001057 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001058 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001059 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001060 } else {
1061 return false;
1062 }
1063
1064 // Do the substitution as long as the redefinition type isn't just a
1065 // possibly-qualified pointer to builtin-id or builtin-Class again.
1066 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieu47fcbba2012-10-12 17:48:40 +00001067 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001068 return false;
1069
1070 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1071 return true;
1072}
1073
John McCall6dbba4f2011-10-11 23:14:30 +00001074static bool isRecordType(QualType T) {
1075 return T->isRecordType();
1076}
1077static bool isPointerToRecordType(QualType T) {
1078 if (const PointerType *PT = T->getAs<PointerType>())
1079 return PT->getPointeeType()->isRecordType();
1080 return false;
1081}
1082
Richard Smith9138b4e2011-10-26 19:06:56 +00001083/// Perform conversions on the LHS of a member access expression.
1084ExprResult
1085Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001086 if (IsArrow && !Base->getType()->isFunctionType())
1087 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001088
Eli Friedman059d5782012-01-13 02:20:01 +00001089 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001090}
1091
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001092/// Look up the given member of the given non-type-dependent
1093/// expression. This can return in one of two ways:
1094/// * If it returns a sentinel null-but-valid result, the caller will
1095/// assume that lookup was performed and the results written into
1096/// the provided structure. It will take over from there.
1097/// * Otherwise, the returned expression will be produced in place of
1098/// an ordinary member expression.
1099///
1100/// The ObjCImpDecl bit is a gross hack that will need to be properly
1101/// fixed for ObjC++.
1102ExprResult
1103Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1104 bool &IsArrow, SourceLocation OpLoc,
1105 CXXScopeSpec &SS,
1106 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1107 assert(BaseExpr.get() && "no base expression");
1108
1109 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001110 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001111 if (BaseExpr.isInvalid())
1112 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001113
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001114 QualType BaseType = BaseExpr.get()->getType();
1115 assert(!BaseType->isDependentType());
1116
1117 DeclarationName MemberName = R.getLookupName();
1118 SourceLocation MemberLoc = R.getNameLoc();
1119
1120 // For later type-checking purposes, turn arrow accesses into dot
1121 // accesses. The only access type we support that doesn't follow
1122 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1123 // and those never use arrows, so this is unaffected.
1124 if (IsArrow) {
1125 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1126 BaseType = Ptr->getPointeeType();
1127 else if (const ObjCObjectPointerType *Ptr
1128 = BaseType->getAs<ObjCObjectPointerType>())
1129 BaseType = Ptr->getPointeeType();
1130 else if (BaseType->isRecordType()) {
1131 // Recover from arrow accesses to records, e.g.:
1132 // struct MyRecord foo;
1133 // foo->bar
1134 // This is actually well-formed in C++ if MyRecord has an
1135 // overloaded operator->, but that should have been dealt with
1136 // by now.
1137 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1138 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1139 << FixItHint::CreateReplacement(OpLoc, ".");
1140 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001141 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001142 goto fail;
1143 } else {
1144 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1145 << BaseType << BaseExpr.get()->getSourceRange();
1146 return ExprError();
1147 }
1148 }
1149
1150 // Handle field access to simple records.
1151 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1152 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1153 RTy, OpLoc, SS, HasTemplateArgs))
1154 return ExprError();
1155
1156 // Returning valid-but-null is how we indicate to the caller that
1157 // the lookup result was filled in.
1158 return Owned((Expr*) 0);
1159 }
1160
1161 // Handle ivar access to Objective-C objects.
1162 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001163 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001164 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1165 << 1 << SS.getScopeRep()
1166 << FixItHint::CreateRemoval(SS.getRange());
1167 SS.clear();
1168 }
1169
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001170 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1171
1172 // There are three cases for the base type:
1173 // - builtin id (qualified or unqualified)
1174 // - builtin Class (qualified or unqualified)
1175 // - an interface
1176 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1177 if (!IDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001178 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001179 (OTy->isObjCId() || OTy->isObjCClass()))
1180 goto fail;
1181 // There's an implicit 'isa' ivar on all objects.
1182 // But we only actually find it this way on objects of type 'id',
Eric Christopher2502ec82012-08-16 23:50:37 +00001183 // apparently.
Fariborz Jahanian7e352742013-03-27 21:19:25 +00001184 if (OTy->isObjCId() && Member->isStr("isa"))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001185 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
Fariborz Jahanianec8deba2013-03-28 19:50:55 +00001186 OpLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001187 Context.getObjCClassType()));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001188 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1189 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1190 ObjCImpDecl, HasTemplateArgs);
1191 goto fail;
1192 }
Fariborz Jahanian09100592012-06-21 21:35:15 +00001193
Douglas Gregord10099e2012-05-04 16:32:21 +00001194 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1195 BaseExpr.get()))
Douglas Gregord07cc362012-01-02 17:18:37 +00001196 return ExprError();
1197
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001198 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001199 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1200
1201 if (!IV) {
1202 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001203 DeclFilterCCC<ObjCIvarDecl> Validator;
1204 Validator.IsObjCIvarLookup = IsArrow;
1205 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1206 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001207 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001208 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001209 Diag(R.getNameLoc(),
1210 diag::err_typecheck_member_reference_ivar_suggest)
1211 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1212 << FixItHint::CreateReplacement(R.getNameLoc(),
1213 IV->getNameAsString());
1214 Diag(IV->getLocation(), diag::note_previous_decl)
1215 << IV->getDeclName();
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001216
1217 // Figure out the class that declares the ivar.
1218 assert(!ClassDeclared);
1219 Decl *D = cast<Decl>(IV->getDeclContext());
1220 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1221 D = CAT->getClassInterface();
1222 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001223 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001224 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1225 Diag(MemberLoc,
1226 diag::err_property_found_suggest)
1227 << Member << BaseExpr.get()->getType()
1228 << FixItHint::CreateReplacement(OpLoc, ".");
1229 return ExprError();
1230 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001231
1232 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1233 << IDecl->getDeclName() << MemberName
1234 << BaseExpr.get()->getSourceRange();
1235 return ExprError();
1236 }
1237 }
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001238
1239 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001240
1241 // If the decl being referenced had an error, return an error for this
1242 // sub-expr without emitting another error, in order to avoid cascading
1243 // error cases.
1244 if (IV->isInvalidDecl())
1245 return ExprError();
1246
1247 // Check whether we can reference this field.
1248 if (DiagnoseUseOfDecl(IV, MemberLoc))
1249 return ExprError();
1250 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1251 IV->getAccessControl() != ObjCIvarDecl::Package) {
1252 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1253 if (ObjCMethodDecl *MD = getCurMethodDecl())
1254 ClassOfMethodDecl = MD->getClassInterface();
1255 else if (ObjCImpDecl && getCurFunctionDecl()) {
1256 // Case of a c-function declared inside an objc implementation.
1257 // FIXME: For a c-style function nested inside an objc implementation
1258 // class, there is no implementation context available, so we pass
1259 // down the context as argument to this routine. Ideally, this context
1260 // need be passed down in the AST node and somehow calculated from the
1261 // AST for a function decl.
1262 if (ObjCImplementationDecl *IMPD =
1263 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1264 ClassOfMethodDecl = IMPD->getClassInterface();
1265 else if (ObjCCategoryImplDecl* CatImplClass =
1266 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1267 ClassOfMethodDecl = CatImplClass->getClassInterface();
1268 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001269 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001270 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1271 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1272 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1273 Diag(MemberLoc, diag::error_private_ivar_access)
1274 << IV->getDeclName();
1275 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1276 // @protected
1277 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001278 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001279 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001280 }
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001281 bool warn = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00001282 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001283 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1284 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1285 if (UO->getOpcode() == UO_Deref)
1286 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1287
1288 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001289 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001290 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001291 warn = false;
1292 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001293 }
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001294 if (warn) {
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001295 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1296 ObjCMethodFamily MF = MD->getMethodFamily();
1297 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahanian26202292013-02-14 19:07:19 +00001298 MF != OMF_finalize &&
1299 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001300 }
1301 if (warn)
1302 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1303 }
Jordan Rose7a270482012-09-28 22:21:35 +00001304
1305 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00001306 MemberLoc, OpLoc,
Jordan Rose7a270482012-09-28 22:21:35 +00001307 BaseExpr.take(),
1308 IsArrow);
1309
1310 if (getLangOpts().ObjCAutoRefCount) {
1311 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1312 DiagnosticsEngine::Level Level =
1313 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1314 MemberLoc);
1315 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian569b4ad2013-05-21 21:20:26 +00001316 recordUseOfEvaluatedWeak(Result);
Jordan Rose7a270482012-09-28 22:21:35 +00001317 }
1318 }
1319
1320 return Owned(Result);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001321 }
1322
1323 // Objective-C property access.
1324 const ObjCObjectPointerType *OPT;
1325 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001326 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001327 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1328 << 0 << SS.getScopeRep()
1329 << FixItHint::CreateRemoval(SS.getRange());
1330 SS.clear();
1331 }
1332
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001333 // This actually uses the base as an r-value.
1334 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1335 if (BaseExpr.isInvalid())
1336 return ExprError();
1337
1338 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1339
1340 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1341
1342 const ObjCObjectType *OT = OPT->getObjectType();
1343
1344 // id, with and without qualifiers.
1345 if (OT->isObjCId()) {
1346 // Check protocols on qualified interfaces.
1347 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1348 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1349 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1350 // Check the use of this declaration
1351 if (DiagnoseUseOfDecl(PD, MemberLoc))
1352 return ExprError();
1353
John McCall3c3b7f92011-10-25 17:37:35 +00001354 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1355 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001356 VK_LValue,
1357 OK_ObjCProperty,
1358 MemberLoc,
1359 BaseExpr.take()));
1360 }
1361
1362 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1363 // Check the use of this method.
1364 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1365 return ExprError();
1366 Selector SetterSel =
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001367 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1368 PP.getSelectorTable(),
1369 Member);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001370 ObjCMethodDecl *SMD = 0;
1371 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1372 SetterSel, Context))
1373 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001374
John McCall3c3b7f92011-10-25 17:37:35 +00001375 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1376 Context.PseudoObjectTy,
1377 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001378 MemberLoc, BaseExpr.take()));
1379 }
1380 }
1381 // Use of id.member can only be for a property reference. Do not
1382 // use the 'id' redefinition in this case.
1383 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1384 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1385 ObjCImpDecl, HasTemplateArgs);
1386
1387 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1388 << MemberName << BaseType);
1389 }
1390
1391 // 'Class', unqualified only.
1392 if (OT->isObjCClass()) {
1393 // Only works in a method declaration (??!).
1394 ObjCMethodDecl *MD = getCurMethodDecl();
1395 if (!MD) {
1396 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1397 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1398 ObjCImpDecl, HasTemplateArgs);
1399
1400 goto fail;
1401 }
1402
1403 // Also must look for a getter name which uses property syntax.
1404 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1405 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1406 ObjCMethodDecl *Getter;
1407 if ((Getter = IFace->lookupClassMethod(Sel))) {
1408 // Check the use of this method.
1409 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1410 return ExprError();
1411 } else
1412 Getter = IFace->lookupPrivateMethod(Sel, false);
1413 // If we found a getter then this may be a valid dot-reference, we
1414 // will look for the matching setter, in case it is needed.
1415 Selector SetterSel =
Adrian Prantl80e8ea92013-06-07 22:29:12 +00001416 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1417 PP.getSelectorTable(),
1418 Member);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001419 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1420 if (!Setter) {
1421 // If this reference is in an @implementation, also check for 'private'
1422 // methods.
1423 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1424 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001425
1426 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1427 return ExprError();
1428
1429 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001430 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001431 Context.PseudoObjectTy,
1432 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001433 MemberLoc, BaseExpr.take()));
1434 }
1435
1436 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1437 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1438 ObjCImpDecl, HasTemplateArgs);
1439
1440 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1441 << MemberName << BaseType);
1442 }
1443
1444 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001445 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1446 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001447 SourceLocation(), QualType(), false);
1448 }
1449
1450 // Handle 'field access' to vectors, such as 'V.xx'.
1451 if (BaseType->isExtVectorType()) {
1452 // FIXME: this expr should store IsArrow.
1453 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1454 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1455 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1456 Member, MemberLoc);
1457 if (ret.isNull())
1458 return ExprError();
1459
1460 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1461 *Member, MemberLoc));
1462 }
1463
1464 // Adjust builtin-sel to the appropriate redefinition type if that's
1465 // not just a pointer to builtin-sel again.
1466 if (IsArrow &&
1467 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001468 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1469 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1470 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001471 CK_BitCast);
1472 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1473 ObjCImpDecl, HasTemplateArgs);
1474 }
1475
1476 // Failure cases.
1477 fail:
1478
1479 // Recover from dot accesses to pointers, e.g.:
1480 // type *foo;
1481 // foo.bar
1482 // This is actually well-formed in two cases:
1483 // - 'type' is an Objective C type
1484 // - 'bar' is a pseudo-destructor name which happens to refer to
1485 // the appropriate pointer type
1486 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1487 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1488 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1489 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1490 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1491 << FixItHint::CreateReplacement(OpLoc, "->");
1492
1493 // Recurse as an -> access.
1494 IsArrow = true;
1495 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1496 ObjCImpDecl, HasTemplateArgs);
1497 }
1498 }
1499
1500 // If the user is trying to apply -> or . to a function name, it's probably
1501 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001502 if (tryToRecoverWithCall(BaseExpr,
1503 PDiag(diag::err_member_reference_needs_call),
1504 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001505 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001506 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001507 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001508 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1509 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1510 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001511 }
1512
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +00001513 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +00001514 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001515
1516 return ExprError();
1517}
1518
1519/// The main callback when the parser finds something like
1520/// expression . [nested-name-specifier] identifier
1521/// expression -> [nested-name-specifier] identifier
1522/// where 'identifier' encompasses a fairly broad spectrum of
1523/// possibilities, including destructor and operator references.
1524///
1525/// \param OpKind either tok::arrow or tok::period
1526/// \param HasTrailingLParen whether the next token is '(', which
1527/// is used to diagnose mis-uses of special members that can
1528/// only be called
James Dennett699c9042012-06-15 07:13:21 +00001529/// \param ObjCImpDecl the current Objective-C \@implementation
1530/// decl; this is an ugly hack around the fact that Objective-C
1531/// \@implementations aren't properly put in the context chain
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001532ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1533 SourceLocation OpLoc,
1534 tok::TokenKind OpKind,
1535 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001536 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001537 UnqualifiedId &Id,
1538 Decl *ObjCImpDecl,
1539 bool HasTrailingLParen) {
1540 if (SS.isSet() && SS.isInvalid())
1541 return ExprError();
1542
1543 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001544 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001545 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1546 Diag(Id.getSourceRange().getBegin(),
1547 diag::ext_ms_explicit_constructor_call);
1548
1549 TemplateArgumentListInfo TemplateArgsBuffer;
1550
1551 // Decompose the name into its component parts.
1552 DeclarationNameInfo NameInfo;
1553 const TemplateArgumentListInfo *TemplateArgs;
1554 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1555 NameInfo, TemplateArgs);
1556
1557 DeclarationName Name = NameInfo.getName();
1558 bool IsArrow = (OpKind == tok::arrow);
1559
1560 NamedDecl *FirstQualifierInScope
1561 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1562 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1563
1564 // This is a postfix expression, so get rid of ParenListExprs.
1565 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1566 if (Result.isInvalid()) return ExprError();
1567 Base = Result.take();
1568
1569 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1570 isDependentScopeSpecifier(SS)) {
1571 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1572 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001573 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001574 NameInfo, TemplateArgs);
1575 } else {
1576 LookupResult R(*this, NameInfo, LookupMemberName);
1577 ExprResult BaseResult = Owned(Base);
1578 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1579 SS, ObjCImpDecl, TemplateArgs != 0);
1580 if (BaseResult.isInvalid())
1581 return ExprError();
1582 Base = BaseResult.take();
1583
1584 if (Result.isInvalid()) {
1585 Owned(Base);
1586 return ExprError();
1587 }
1588
1589 if (Result.get()) {
1590 // The only way a reference to a destructor can be used is to
1591 // immediately call it, which falls into this case. If the
1592 // next token is not a '(', produce a diagnostic and build the
1593 // call now.
1594 if (!HasTrailingLParen &&
1595 Id.getKind() == UnqualifiedId::IK_DestructorName)
1596 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1597
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001598 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001599 }
1600
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001601 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001602 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001603 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001604 FirstQualifierInScope, R, TemplateArgs,
1605 false, &ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001606 }
1607
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001608 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001609}
1610
1611static ExprResult
1612BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1613 const CXXScopeSpec &SS, FieldDecl *Field,
1614 DeclAccessPair FoundDecl,
1615 const DeclarationNameInfo &MemberNameInfo) {
1616 // x.a is an l-value if 'a' has a reference type. Otherwise:
1617 // x.a is an l-value/x-value/pr-value if the base is (and note
1618 // that *x is always an l-value), except that if the base isn't
1619 // an ordinary object then we must have an rvalue.
1620 ExprValueKind VK = VK_LValue;
1621 ExprObjectKind OK = OK_Ordinary;
1622 if (!IsArrow) {
1623 if (BaseExpr->getObjectKind() == OK_Ordinary)
1624 VK = BaseExpr->getValueKind();
1625 else
1626 VK = VK_RValue;
1627 }
1628 if (VK != VK_RValue && Field->isBitField())
1629 OK = OK_BitField;
1630
1631 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1632 QualType MemberType = Field->getType();
1633 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1634 MemberType = Ref->getPointeeType();
1635 VK = VK_LValue;
1636 } else {
1637 QualType BaseType = BaseExpr->getType();
1638 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001639
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001640 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001641
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001642 // GC attributes are never picked up by members.
1643 BaseQuals.removeObjCGCAttr();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001644
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001645 // CVR attributes from the base are picked up by members,
1646 // except that 'mutable' members don't pick up 'const'.
1647 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001648
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001649 Qualifiers MemberQuals
1650 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001651
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001652 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001653
1654
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001655 Qualifiers Combined = BaseQuals + MemberQuals;
1656 if (Combined != MemberQuals)
1657 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1658 }
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001659
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001660 S.UnusedPrivateFields.remove(Field);
1661
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001662 ExprResult Base =
1663 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1664 FoundDecl, Field);
1665 if (Base.isInvalid())
1666 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001667 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001668 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001669 Field, FoundDecl, MemberNameInfo,
1670 MemberType, VK, OK));
1671}
1672
1673/// Builds an implicit member access expression. The current context
1674/// is known to be an instance method, and the given unqualified lookup
1675/// set is known to contain only instance members, at least one of which
1676/// is from an appropriate type.
1677ExprResult
1678Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001679 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001680 LookupResult &R,
1681 const TemplateArgumentListInfo *TemplateArgs,
1682 bool IsKnownInstance) {
1683 assert(!R.empty() && !R.isAmbiguous());
1684
1685 SourceLocation loc = R.getNameLoc();
1686
1687 // We may have found a field within an anonymous union or struct
1688 // (C++ [class.union]).
1689 // FIXME: template-ids inside anonymous structs?
1690 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1691 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1692
1693 // If this is known to be an instance access, go ahead and build an
1694 // implicit 'this' expression now.
1695 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001696 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001697 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1698
1699 Expr *baseExpr = 0; // null signifies implicit access
1700 if (IsKnownInstance) {
1701 SourceLocation Loc = R.getNameLoc();
1702 if (SS.getRange().isValid())
1703 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001704 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001705 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1706 }
1707
1708 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1709 /*OpLoc*/ SourceLocation(),
1710 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001711 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001712 /*FirstQualifierInScope*/ 0,
1713 R, TemplateArgs);
1714}