blob: 5d1332336098a9b994a4a2048b5d686dbe3c468f [file] [log] [blame]
Douglas Gregor5476205b2011-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 Gregor5476205b2011-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 Carruth3a022472012-12-04 09:13:33 +000020#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000023
24using namespace clang;
25using namespace sema;
26
Richard Smithd80b2d52012-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 Gregor5476205b2011-06-23 00:49:38 +000033/// Determines if the given class is provably not derived from all of
34/// the prospective base classes.
Richard Smithd80b2d52012-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 Gregor5476205b2011-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 Friedman7bda7f72012-01-18 03:53:45 +000049 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-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 McCallf413f5e2013-05-03 00:10:13 +000063 /// The reference is a contextually-permitted abstract member reference.
64 IMA_Abstract,
65
Douglas Gregor5476205b2011-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 Friedman456f0182012-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 Friedman7bda7f72012-01-18 03:53:45 +000074
Douglas Gregor5476205b2011-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 Friedman7bda7f72012-01-18 03:53:45 +000087/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-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 Gregor3024f072012-04-16 07:05:22 +000097 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
98 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-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 Friedman7bda7f72012-01-18 03:53:45 +0000105 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000106 BaseSet Classes;
Douglas Gregor5476205b2011-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 McCall5e77d762013-04-16 07:28:30 +0000111 if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
112 || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman7bda7f72012-01-18 03:53:45 +0000113 isField = true;
Douglas Gregor5476205b2011-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 McCallf413f5e2013-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 Gregor5476205b2011-06-23 00:49:38 +0000143
John McCallf413f5e2013-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 Smitheae99682012-02-25 10:04:07 +0000152 }
153
Douglas Gregor5476205b2011-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 Smitheae99682012-02-25 10:04:07 +0000158 return IMA_Mixed_StaticContext;
159
John McCallf413f5e2013-05-03 00:10:13 +0000160 return AbstractInstanceResult ? AbstractInstanceResult
161 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-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 Hutchins5b330db2012-02-25 00:11:55 +0000177 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-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 Smithb2c5f962012-11-22 00:40:54 +0000183 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000184 }
Douglas Gregor5476205b2011-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 Smithd80b2d52012-11-22 00:24:47 +0000189 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000190 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000191 AbstractInstanceResult ? AbstractInstanceResult :
192 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-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 Smithfa0a1f52012-04-05 01:13:04 +0000198static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000199 const CXXScopeSpec &SS,
Richard Smithfa0a1f52012-04-05 01:13:04 +0000200 NamedDecl *Rep,
Eli Friedman456f0182012-01-20 01:26:23 +0000201 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000202 SourceLocation Loc = nameInfo.getLoc();
203 SourceRange Range(Loc);
204 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000205
Richard Smithfa0a1f52012-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 Friedman456f0182012-01-20 01:26:23 +0000225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000226 << nameInfo.getName() << Range;
227 else
228 SemaRef.Diag(Loc, diag::err_member_call_without_object)
229 << Range;
Douglas Gregor5476205b2011-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 Bagnara7945c982012-01-27 09:46:47 +0000235 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000236 LookupResult &R,
237 const TemplateArgumentListInfo *TemplateArgs) {
238 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
239 case IMA_Instance:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000240 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000241
242 case IMA_Mixed:
243 case IMA_Mixed_Unrelated:
244 case IMA_Unresolved:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000245 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000246
Richard Smith2a986112012-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 Gregor5476205b2011-06-23 00:49:38 +0000251 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000252 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000253 case IMA_Mixed_StaticContext:
254 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000255 if (TemplateArgs || TemplateKWLoc.isValid())
256 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000257 return BuildDeclarationNameExpr(SS, R, false);
258
259 case IMA_Error_StaticContext:
260 case IMA_Error_Unrelated:
Richard Smithfa0a1f52012-04-05 01:13:04 +0000261 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000262 R.getLookupNameInfo());
263 return ExprError();
264 }
265
266 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-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 Lattner0e62c1c2011-07-23 10:55:15 +0000326 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-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 Gregorb7098a32011-07-28 00:39:29 +0000365 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000366 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-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 Gregor5476205b2011-06-23 00:49:38 +0000371 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000372
Douglas Gregor5476205b2011-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 Bagnara7945c982012-01-27 09:46:47 +0000431 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-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 Blaikiebbafb8a2012-03-11 07:00:24 +0000446 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000447 PT->getPointeeType()->isRecordType())) {
448 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000449 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000450 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-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 Bagnara7945c982012-01-27 09:46:47 +0000464 TemplateKWLoc,
Douglas Gregor5476205b2011-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 Smithfa0a1f52012-04-05 01:13:04 +0000481 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-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 Smithd80b2d52012-11-22 00:24:47 +0000503 CXXRecordDecl *BaseRecord =
504 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
505 if (!BaseRecord) {
Douglas Gregor5476205b2011-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 Gregor5476205b2011-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 Gregor5476205b2011-06-23 00:49:38 +0000525
Richard Smithd80b2d52012-11-22 00:24:47 +0000526 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
527 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
528 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-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 Uhrain3658e6a2012-01-13 21:28:55 +0000538namespace {
539
540// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000541// FunctionTemplateDecl and are declared in the current record or, for a C++
542// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000543class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
544 public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000545 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
546 : Record(RTy->getDecl()) {}
547
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000548 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
549 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000550 // Don't accept candidates that cannot be member functions, constants,
551 // variables, or templates.
552 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
553 return false;
554
555 // Accept candidates that occur in the current record.
556 if (Record->containsDecl(ND))
557 return true;
558
559 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
560 // Accept candidates that occur in any of the current class' base classes.
561 for (CXXRecordDecl::base_class_const_iterator BS = RD->bases_begin(),
562 BSEnd = RD->bases_end();
563 BS != BSEnd; ++BS) {
564 if (const RecordType *BSTy = dyn_cast_or_null<RecordType>(
565 BS->getType().getTypePtrOrNull())) {
566 if (BSTy->getDecl()->containsDecl(ND))
567 return true;
568 }
569 }
570 }
571
572 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000573 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000574
575 private:
576 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000577};
578
579}
580
Douglas Gregor5476205b2011-06-23 00:49:38 +0000581static bool
Douglas Gregor3024f072012-04-16 07:05:22 +0000582LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000583 SourceRange BaseRange, const RecordType *RTy,
584 SourceLocation OpLoc, CXXScopeSpec &SS,
585 bool HasTemplateArgs) {
586 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000587 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
588 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000589 diag::err_typecheck_incomplete_tag,
590 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000591 return true;
592
593 if (HasTemplateArgs) {
594 // LookupTemplateName doesn't expect these both to exist simultaneously.
595 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
596
597 bool MOUS;
598 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
599 return false;
600 }
601
602 DeclContext *DC = RDecl;
603 if (SS.isSet()) {
604 // If the member name was a qualified-id, look into the
605 // nested-name-specifier.
606 DC = SemaRef.computeDeclContext(SS, false);
607
608 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
609 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
610 << SS.getRange() << DC;
611 return true;
612 }
613
614 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
615
616 if (!isa<TypeDecl>(DC)) {
617 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
618 << DC << SS.getRange();
619 return true;
620 }
621 }
622
623 // The record definition is complete, now look up the member.
624 SemaRef.LookupQualifiedName(R, DC);
625
626 if (!R.empty())
627 return false;
628
629 // We didn't find anything with the given name, so try to correct
630 // for typos.
631 DeclarationName Name = R.getLookupName();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000632 RecordMemberExprValidatorCCC Validator(RTy);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000633 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
634 R.getLookupKind(), NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000635 &SS, Validator, DC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000636 R.clear();
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000637 if (Corrected.isResolved() && !Corrected.isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000638 R.setLookupName(Corrected.getCorrection());
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000639 for (TypoCorrection::decl_iterator DI = Corrected.begin(),
640 DIEnd = Corrected.end();
641 DI != DIEnd; ++DI) {
642 R.addDecl(*DI);
643 }
644 R.resolveKind();
645
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000646 // If we're typo-correcting to an overloaded name, we don't yet have enough
647 // information to do overload resolution, so we don't know which previous
648 // declaration to point to.
Richard Smithf9b15102013-08-17 00:46:16 +0000649 if (Corrected.isOverloaded())
650 Corrected.setCorrectionDecl(0);
651 bool DroppedSpecifier =
652 Corrected.WillReplaceSpecifier() &&
653 Name.getAsString() == Corrected.getAsString(SemaRef.getLangOpts());
654 SemaRef.diagnoseTypo(Corrected,
655 SemaRef.PDiag(diag::err_no_member_suggest)
656 << Name << DC << DroppedSpecifier << SS.getRange());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000657 }
658
659 return false;
660}
661
662ExprResult
663Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
664 SourceLocation OpLoc, bool IsArrow,
665 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000666 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000667 NamedDecl *FirstQualifierInScope,
668 const DeclarationNameInfo &NameInfo,
669 const TemplateArgumentListInfo *TemplateArgs) {
670 if (BaseType->isDependentType() ||
671 (SS.isSet() && isDependentScopeSpecifier(SS)))
672 return ActOnDependentMemberExpr(Base, BaseType,
673 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000674 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000675 NameInfo, TemplateArgs);
676
677 LookupResult R(*this, NameInfo, LookupMemberName);
678
679 // Implicit member accesses.
680 if (!Base) {
681 QualType RecordTy = BaseType;
682 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
683 if (LookupMemberExprInRecord(*this, R, SourceRange(),
684 RecordTy->getAs<RecordType>(),
685 OpLoc, SS, TemplateArgs != 0))
686 return ExprError();
687
688 // Explicit member accesses.
689 } else {
690 ExprResult BaseResult = Owned(Base);
691 ExprResult Result =
692 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
693 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
694
695 if (BaseResult.isInvalid())
696 return ExprError();
697 Base = BaseResult.take();
698
699 if (Result.isInvalid()) {
700 Owned(Base);
701 return ExprError();
702 }
703
704 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000705 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000706
707 // LookupMemberExpr can modify Base, and thus change BaseType
708 BaseType = Base->getType();
709 }
710
711 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000712 OpLoc, IsArrow, SS, TemplateKWLoc,
713 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000714}
715
716static ExprResult
717BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
718 const CXXScopeSpec &SS, FieldDecl *Field,
719 DeclAccessPair FoundDecl,
720 const DeclarationNameInfo &MemberNameInfo);
721
722ExprResult
723Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
724 SourceLocation loc,
725 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000726 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000727 Expr *baseObjectExpr,
728 SourceLocation opLoc) {
729 // First, build the expression that refers to the base object.
730
731 bool baseObjectIsPointer = false;
732 Qualifiers baseQuals;
733
734 // Case 1: the base of the indirect field is not a field.
735 VarDecl *baseVariable = indirectField->getVarDecl();
736 CXXScopeSpec EmptySS;
737 if (baseVariable) {
738 assert(baseVariable->getType()->isRecordType());
739
740 // In principle we could have a member access expression that
741 // accesses an anonymous struct/union that's a static member of
742 // the base object's class. However, under the current standard,
743 // static data members cannot be anonymous structs or unions.
744 // Supporting this is as easy as building a MemberExpr here.
745 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
746
747 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
748
749 ExprResult result
750 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
751 if (result.isInvalid()) return ExprError();
752
753 baseObjectExpr = result.take();
754 baseObjectIsPointer = false;
755 baseQuals = baseObjectExpr->getType().getQualifiers();
756
757 // Case 2: the base of the indirect field is a field and the user
758 // wrote a member expression.
759 } else if (baseObjectExpr) {
760 // The caller provided the base object expression. Determine
761 // whether its a pointer and whether it adds any qualifiers to the
762 // anonymous struct/union fields we're looking into.
763 QualType objectType = baseObjectExpr->getType();
764
765 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
766 baseObjectIsPointer = true;
767 objectType = ptr->getPointeeType();
768 } else {
769 baseObjectIsPointer = false;
770 }
771 baseQuals = objectType.getQualifiers();
772
773 // Case 3: the base of the indirect field is a field and we should
774 // build an implicit member access.
775 } else {
776 // We've found a member of an anonymous struct/union that is
777 // inside a non-anonymous struct/union, so in a well-formed
778 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000779 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000780 if (ThisTy.isNull()) {
781 Diag(loc, diag::err_invalid_member_use_in_static_method)
782 << indirectField->getDeclName();
783 return ExprError();
784 }
785
786 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000787 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000788 baseObjectExpr
789 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
790 baseObjectIsPointer = true;
791 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
792 }
793
794 // Build the implicit member references to the field of the
795 // anonymous struct/union.
796 Expr *result = baseObjectExpr;
797 IndirectFieldDecl::chain_iterator
798 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
799
800 // Build the first member access in the chain with full information.
801 if (!baseVariable) {
802 FieldDecl *field = cast<FieldDecl>(*FI);
803
Douglas Gregor5476205b2011-06-23 00:49:38 +0000804 // Make a nameInfo that properly uses the anonymous name.
805 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
806
807 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
808 EmptySS, field, foundDecl,
809 memberNameInfo).take();
Eli Friedmancccd0642013-07-16 00:01:31 +0000810 if (!result)
811 return ExprError();
812
Douglas Gregor5476205b2011-06-23 00:49:38 +0000813 baseObjectIsPointer = false;
814
815 // FIXME: check qualified member access
816 }
817
818 // In all cases, we should now skip the first declaration in the chain.
819 ++FI;
820
821 while (FI != FEnd) {
822 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000823
Douglas Gregor5476205b2011-06-23 00:49:38 +0000824 // FIXME: these are somewhat meaningless
825 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000826 DeclAccessPair fakeFoundDecl =
827 DeclAccessPair::make(field, field->getAccess());
828
Douglas Gregor5476205b2011-06-23 00:49:38 +0000829 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Eli Friedmancccd0642013-07-16 00:01:31 +0000830 (FI == FEnd? SS : EmptySS), field,
831 fakeFoundDecl, memberNameInfo).take();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000832 }
833
834 return Owned(result);
835}
836
John McCall5e77d762013-04-16 07:28:30 +0000837static ExprResult
838BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
839 const CXXScopeSpec &SS,
840 MSPropertyDecl *PD,
841 const DeclarationNameInfo &NameInfo) {
842 // Property names are always simple identifiers and therefore never
843 // require any interesting additional storage.
844 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
845 S.Context.PseudoObjectTy, VK_LValue,
846 SS.getWithLocInContext(S.Context),
847 NameInfo.getLoc());
848}
849
Douglas Gregor5476205b2011-06-23 00:49:38 +0000850/// \brief Build a MemberExpr AST node.
Eli Friedmanfa0df832012-02-02 03:46:19 +0000851static MemberExpr *BuildMemberExpr(Sema &SemaRef,
852 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000853 const CXXScopeSpec &SS,
854 SourceLocation TemplateKWLoc,
855 ValueDecl *Member,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000856 DeclAccessPair FoundDecl,
857 const DeclarationNameInfo &MemberNameInfo,
858 QualType Ty,
859 ExprValueKind VK, ExprObjectKind OK,
860 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith08b12f12011-10-27 22:11:44 +0000861 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedmanfa0df832012-02-02 03:46:19 +0000862 MemberExpr *E =
863 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
864 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
865 TemplateArgs, Ty, VK, OK);
866 SemaRef.MarkMemberReferenced(E);
867 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000868}
869
870ExprResult
871Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
872 SourceLocation OpLoc, bool IsArrow,
873 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000874 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000875 NamedDecl *FirstQualifierInScope,
876 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000877 const TemplateArgumentListInfo *TemplateArgs,
878 bool SuppressQualifierCheck,
879 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000880 QualType BaseType = BaseExprType;
881 if (IsArrow) {
882 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000883 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000884 }
885 R.setBaseObjectType(BaseType);
886
887 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
888 DeclarationName MemberName = MemberNameInfo.getName();
889 SourceLocation MemberLoc = MemberNameInfo.getLoc();
890
891 if (R.isAmbiguous())
892 return ExprError();
893
894 if (R.empty()) {
895 // Rederive where we looked up.
896 DeclContext *DC = (SS.isSet()
897 ? computeDeclContext(SS, false)
898 : BaseType->getAs<RecordType>()->getDecl());
899
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000900 if (ExtraArgs) {
901 ExprResult RetryExpr;
902 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000903 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000904 ParsedType ObjectType;
905 bool MayBePseudoDestructor = false;
906 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
907 OpLoc, tok::arrow, ObjectType,
908 MayBePseudoDestructor);
909 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
910 CXXScopeSpec TempSS(SS);
911 RetryExpr = ActOnMemberAccessExpr(
912 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
913 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
914 ExtraArgs->HasTrailingLParen);
915 }
916 if (Trap.hasErrorOccurred())
917 RetryExpr = ExprError();
918 }
919 if (RetryExpr.isUsable()) {
920 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
921 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
922 return RetryExpr;
923 }
924 }
925
Douglas Gregor5476205b2011-06-23 00:49:38 +0000926 Diag(R.getNameLoc(), diag::err_no_member)
927 << MemberName << DC
928 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
929 return ExprError();
930 }
931
932 // Diagnose lookups that find only declarations from a non-base
933 // type. This is possible for either qualified lookups (which may
934 // have been qualified with an unrelated type) or implicit member
935 // expressions (which were found with unqualified lookup and thus
936 // may have come from an enclosing scope). Note that it's okay for
937 // lookup to find declarations from a non-base type as long as those
938 // aren't the ones picked by overload resolution.
939 if ((SS.isSet() || !BaseExpr ||
940 (isa<CXXThisExpr>(BaseExpr) &&
941 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
942 !SuppressQualifierCheck &&
943 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
944 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +0000945
Douglas Gregor5476205b2011-06-23 00:49:38 +0000946 // Construct an unresolved result if we in fact got an unresolved
947 // result.
948 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
949 // Suppress any lookup-related diagnostics; we'll do these when we
950 // pick a member.
951 R.suppressDiagnostics();
952
953 UnresolvedMemberExpr *MemExpr
954 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
955 BaseExpr, BaseExprType,
956 IsArrow, OpLoc,
957 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +0000958 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000959 TemplateArgs, R.begin(), R.end());
960
961 return Owned(MemExpr);
962 }
963
964 assert(R.isSingleResult());
965 DeclAccessPair FoundDecl = R.begin().getPair();
966 NamedDecl *MemberDecl = R.getFoundDecl();
967
968 // FIXME: diagnose the presence of template arguments now.
969
970 // If the decl being referenced had an error, return an error for this
971 // sub-expr without emitting another error, in order to avoid cascading
972 // error cases.
973 if (MemberDecl->isInvalidDecl())
974 return ExprError();
975
976 // Handle the implicit-member-access case.
977 if (!BaseExpr) {
978 // If this is not an instance member, convert to a non-member access.
979 if (!MemberDecl->isCXXInstanceMember())
980 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
981
982 SourceLocation Loc = R.getNameLoc();
983 if (SS.getRange().isValid())
984 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +0000985 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000986 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
987 }
988
989 bool ShouldCheckUse = true;
990 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
991 // Don't diagnose the use of a virtual member function unless it's
992 // explicitly qualified.
993 if (MD->isVirtual() && !SS.isSet())
994 ShouldCheckUse = false;
995 }
996
997 // Check the use of this member.
998 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
999 Owned(BaseExpr);
1000 return ExprError();
1001 }
1002
Douglas Gregor5476205b2011-06-23 00:49:38 +00001003 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1004 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
1005 SS, FD, FoundDecl, MemberNameInfo);
1006
John McCall5e77d762013-04-16 07:28:30 +00001007 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1008 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1009 MemberNameInfo);
1010
Douglas Gregor5476205b2011-06-23 00:49:38 +00001011 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1012 // We may have found a field within an anonymous union or struct
1013 // (C++ [class.union]).
1014 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001015 FoundDecl, BaseExpr,
1016 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001017
1018 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00001019 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1020 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001021 Var->getType().getNonReferenceType(),
1022 VK_LValue, OK_Ordinary));
1023 }
1024
1025 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1026 ExprValueKind valueKind;
1027 QualType type;
1028 if (MemberFn->isInstance()) {
1029 valueKind = VK_RValue;
1030 type = Context.BoundMemberTy;
1031 } else {
1032 valueKind = VK_LValue;
1033 type = MemberFn->getType();
1034 }
1035
Eli Friedmanfa0df832012-02-02 03:46:19 +00001036 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1037 TemplateKWLoc, MemberFn, FoundDecl,
1038 MemberNameInfo, type, valueKind,
1039 OK_Ordinary));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001040 }
1041 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1042
1043 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00001044 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1045 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001046 Enum->getType(), VK_RValue, OK_Ordinary));
1047 }
1048
1049 Owned(BaseExpr);
1050
1051 // We found something that we didn't expect. Complain.
1052 if (isa<TypeDecl>(MemberDecl))
1053 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1054 << MemberName << BaseType << int(IsArrow);
1055 else
1056 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1057 << MemberName << BaseType << int(IsArrow);
1058
1059 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1060 << MemberName;
1061 R.suppressDiagnostics();
1062 return ExprError();
1063}
1064
1065/// Given that normal member access failed on the given expression,
1066/// and given that the expression's type involves builtin-id or
1067/// builtin-Class, decide whether substituting in the redefinition
1068/// types would be profitable. The redefinition type is whatever
1069/// this translation unit tried to typedef to id/Class; we store
1070/// it to the side and then re-use it in places like this.
1071static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1072 const ObjCObjectPointerType *opty
1073 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1074 if (!opty) return false;
1075
1076 const ObjCObjectType *ty = opty->getObjectType();
1077
1078 QualType redef;
1079 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001080 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001081 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001082 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001083 } else {
1084 return false;
1085 }
1086
1087 // Do the substitution as long as the redefinition type isn't just a
1088 // possibly-qualified pointer to builtin-id or builtin-Class again.
1089 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001090 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001091 return false;
1092
1093 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1094 return true;
1095}
1096
John McCall50a2c2c2011-10-11 23:14:30 +00001097static bool isRecordType(QualType T) {
1098 return T->isRecordType();
1099}
1100static bool isPointerToRecordType(QualType T) {
1101 if (const PointerType *PT = T->getAs<PointerType>())
1102 return PT->getPointeeType()->isRecordType();
1103 return false;
1104}
1105
Richard Smithcab9a7d2011-10-26 19:06:56 +00001106/// Perform conversions on the LHS of a member access expression.
1107ExprResult
1108Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001109 if (IsArrow && !Base->getType()->isFunctionType())
1110 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001111
Eli Friedman9a766c42012-01-13 02:20:01 +00001112 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001113}
1114
Douglas Gregor5476205b2011-06-23 00:49:38 +00001115/// Look up the given member of the given non-type-dependent
1116/// expression. This can return in one of two ways:
1117/// * If it returns a sentinel null-but-valid result, the caller will
1118/// assume that lookup was performed and the results written into
1119/// the provided structure. It will take over from there.
1120/// * Otherwise, the returned expression will be produced in place of
1121/// an ordinary member expression.
1122///
1123/// The ObjCImpDecl bit is a gross hack that will need to be properly
1124/// fixed for ObjC++.
1125ExprResult
1126Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1127 bool &IsArrow, SourceLocation OpLoc,
1128 CXXScopeSpec &SS,
1129 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1130 assert(BaseExpr.get() && "no base expression");
1131
1132 // Perform default conversions.
Richard Smithcab9a7d2011-10-26 19:06:56 +00001133 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001134 if (BaseExpr.isInvalid())
1135 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001136
Douglas Gregor5476205b2011-06-23 00:49:38 +00001137 QualType BaseType = BaseExpr.get()->getType();
1138 assert(!BaseType->isDependentType());
1139
1140 DeclarationName MemberName = R.getLookupName();
1141 SourceLocation MemberLoc = R.getNameLoc();
1142
1143 // For later type-checking purposes, turn arrow accesses into dot
1144 // accesses. The only access type we support that doesn't follow
1145 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1146 // and those never use arrows, so this is unaffected.
1147 if (IsArrow) {
1148 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1149 BaseType = Ptr->getPointeeType();
1150 else if (const ObjCObjectPointerType *Ptr
1151 = BaseType->getAs<ObjCObjectPointerType>())
1152 BaseType = Ptr->getPointeeType();
1153 else if (BaseType->isRecordType()) {
1154 // Recover from arrow accesses to records, e.g.:
1155 // struct MyRecord foo;
1156 // foo->bar
1157 // This is actually well-formed in C++ if MyRecord has an
1158 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001159 // by now--or a diagnostic message already issued if a problem
1160 // was encountered while looking for the overloaded operator->.
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001161 if (!getLangOpts().CPlusPlus) {
1162 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1163 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1164 << FixItHint::CreateReplacement(OpLoc, ".");
1165 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001166 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001167 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001168 goto fail;
1169 } else {
1170 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1171 << BaseType << BaseExpr.get()->getSourceRange();
1172 return ExprError();
1173 }
1174 }
1175
1176 // Handle field access to simple records.
1177 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1178 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1179 RTy, OpLoc, SS, HasTemplateArgs))
1180 return ExprError();
1181
1182 // Returning valid-but-null is how we indicate to the caller that
1183 // the lookup result was filled in.
1184 return Owned((Expr*) 0);
1185 }
1186
1187 // Handle ivar access to Objective-C objects.
1188 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001189 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregor12340e52011-10-09 23:22:49 +00001190 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1191 << 1 << SS.getScopeRep()
1192 << FixItHint::CreateRemoval(SS.getRange());
1193 SS.clear();
1194 }
1195
Douglas Gregor5476205b2011-06-23 00:49:38 +00001196 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1197
1198 // There are three cases for the base type:
1199 // - builtin id (qualified or unqualified)
1200 // - builtin Class (qualified or unqualified)
1201 // - an interface
1202 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1203 if (!IDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001204 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001205 (OTy->isObjCId() || OTy->isObjCClass()))
1206 goto fail;
1207 // There's an implicit 'isa' ivar on all objects.
1208 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001209 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001210 if (OTy->isObjCId() && Member->isStr("isa"))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001211 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +00001212 OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001213 Context.getObjCClassType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001214 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1215 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1216 ObjCImpDecl, HasTemplateArgs);
1217 goto fail;
1218 }
Fariborz Jahanian25cb4ac2012-06-21 21:35:15 +00001219
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001220 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1221 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001222 return ExprError();
1223
Ted Kremenek679b4782012-03-17 00:53:39 +00001224 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001225 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1226
1227 if (!IV) {
1228 // Attempt to correct for typos in ivar names.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001229 DeclFilterCCC<ObjCIvarDecl> Validator;
1230 Validator.IsObjCIvarLookup = IsArrow;
1231 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1232 LookupMemberName, NULL, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001233 Validator, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001234 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smithf9b15102013-08-17 00:46:16 +00001235 diagnoseTypo(Corrected,
1236 PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1237 << IDecl->getDeclName() << MemberName);
1238
Ted Kremenek679b4782012-03-17 00:53:39 +00001239 // Figure out the class that declares the ivar.
1240 assert(!ClassDeclared);
1241 Decl *D = cast<Decl>(IV->getDeclContext());
1242 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1243 D = CAT->getClassInterface();
1244 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001245 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001246 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1247 Diag(MemberLoc,
1248 diag::err_property_found_suggest)
1249 << Member << BaseExpr.get()->getType()
1250 << FixItHint::CreateReplacement(OpLoc, ".");
1251 return ExprError();
1252 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001253
1254 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1255 << IDecl->getDeclName() << MemberName
1256 << BaseExpr.get()->getSourceRange();
1257 return ExprError();
1258 }
1259 }
Ted Kremenek679b4782012-03-17 00:53:39 +00001260
1261 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001262
1263 // If the decl being referenced had an error, return an error for this
1264 // sub-expr without emitting another error, in order to avoid cascading
1265 // error cases.
1266 if (IV->isInvalidDecl())
1267 return ExprError();
1268
1269 // Check whether we can reference this field.
1270 if (DiagnoseUseOfDecl(IV, MemberLoc))
1271 return ExprError();
1272 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1273 IV->getAccessControl() != ObjCIvarDecl::Package) {
1274 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1275 if (ObjCMethodDecl *MD = getCurMethodDecl())
1276 ClassOfMethodDecl = MD->getClassInterface();
1277 else if (ObjCImpDecl && getCurFunctionDecl()) {
1278 // Case of a c-function declared inside an objc implementation.
1279 // FIXME: For a c-style function nested inside an objc implementation
1280 // class, there is no implementation context available, so we pass
1281 // down the context as argument to this routine. Ideally, this context
1282 // need be passed down in the AST node and somehow calculated from the
1283 // AST for a function decl.
1284 if (ObjCImplementationDecl *IMPD =
1285 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1286 ClassOfMethodDecl = IMPD->getClassInterface();
1287 else if (ObjCCategoryImplDecl* CatImplClass =
1288 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1289 ClassOfMethodDecl = CatImplClass->getClassInterface();
1290 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001291 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001292 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1293 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1294 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1295 Diag(MemberLoc, diag::error_private_ivar_access)
1296 << IV->getDeclName();
1297 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1298 // @protected
1299 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001300 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001301 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001302 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001303 bool warn = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001304 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001305 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1306 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1307 if (UO->getOpcode() == UO_Deref)
1308 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1309
1310 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001311 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001312 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001313 warn = false;
1314 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001315 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001316 if (warn) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001317 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1318 ObjCMethodFamily MF = MD->getMethodFamily();
1319 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001320 MF != OMF_finalize &&
1321 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001322 }
1323 if (warn)
1324 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1325 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001326
1327 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001328 MemberLoc, OpLoc,
Jordan Rose657b5f42012-09-28 22:21:35 +00001329 BaseExpr.take(),
1330 IsArrow);
1331
1332 if (getLangOpts().ObjCAutoRefCount) {
1333 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1334 DiagnosticsEngine::Level Level =
1335 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1336 MemberLoc);
1337 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00001338 recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001339 }
1340 }
1341
1342 return Owned(Result);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001343 }
1344
1345 // Objective-C property access.
1346 const ObjCObjectPointerType *OPT;
1347 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001348 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregor12340e52011-10-09 23:22:49 +00001349 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1350 << 0 << SS.getScopeRep()
1351 << FixItHint::CreateRemoval(SS.getRange());
1352 SS.clear();
1353 }
1354
Douglas Gregor5476205b2011-06-23 00:49:38 +00001355 // This actually uses the base as an r-value.
1356 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1357 if (BaseExpr.isInvalid())
1358 return ExprError();
1359
1360 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1361
1362 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1363
1364 const ObjCObjectType *OT = OPT->getObjectType();
1365
1366 // id, with and without qualifiers.
1367 if (OT->isObjCId()) {
1368 // Check protocols on qualified interfaces.
1369 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1370 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1371 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1372 // Check the use of this declaration
1373 if (DiagnoseUseOfDecl(PD, MemberLoc))
1374 return ExprError();
1375
John McCall526ab472011-10-25 17:37:35 +00001376 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1377 Context.PseudoObjectTy,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001378 VK_LValue,
1379 OK_ObjCProperty,
1380 MemberLoc,
1381 BaseExpr.take()));
1382 }
1383
1384 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1385 // Check the use of this method.
1386 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1387 return ExprError();
1388 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001389 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1390 PP.getSelectorTable(),
1391 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001392 ObjCMethodDecl *SMD = 0;
1393 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1394 SetterSel, Context))
1395 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001396
John McCall526ab472011-10-25 17:37:35 +00001397 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1398 Context.PseudoObjectTy,
1399 VK_LValue, OK_ObjCProperty,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001400 MemberLoc, BaseExpr.take()));
1401 }
1402 }
1403 // Use of id.member can only be for a property reference. Do not
1404 // use the 'id' redefinition in this case.
1405 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1406 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1407 ObjCImpDecl, HasTemplateArgs);
1408
1409 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1410 << MemberName << BaseType);
1411 }
1412
1413 // 'Class', unqualified only.
1414 if (OT->isObjCClass()) {
1415 // Only works in a method declaration (??!).
1416 ObjCMethodDecl *MD = getCurMethodDecl();
1417 if (!MD) {
1418 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1419 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1420 ObjCImpDecl, HasTemplateArgs);
1421
1422 goto fail;
1423 }
1424
1425 // Also must look for a getter name which uses property syntax.
1426 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1427 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1428 ObjCMethodDecl *Getter;
1429 if ((Getter = IFace->lookupClassMethod(Sel))) {
1430 // Check the use of this method.
1431 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1432 return ExprError();
1433 } else
1434 Getter = IFace->lookupPrivateMethod(Sel, false);
1435 // If we found a getter then this may be a valid dot-reference, we
1436 // will look for the matching setter, in case it is needed.
1437 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001438 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1439 PP.getSelectorTable(),
1440 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001441 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1442 if (!Setter) {
1443 // If this reference is in an @implementation, also check for 'private'
1444 // methods.
1445 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1446 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001447
1448 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1449 return ExprError();
1450
1451 if (Getter || Setter) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001452 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001453 Context.PseudoObjectTy,
1454 VK_LValue, OK_ObjCProperty,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001455 MemberLoc, BaseExpr.take()));
1456 }
1457
1458 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1459 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1460 ObjCImpDecl, HasTemplateArgs);
1461
1462 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1463 << MemberName << BaseType);
1464 }
1465
1466 // Normal property access.
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001467 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1468 MemberName, MemberLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001469 SourceLocation(), QualType(), false);
1470 }
1471
1472 // Handle 'field access' to vectors, such as 'V.xx'.
1473 if (BaseType->isExtVectorType()) {
1474 // FIXME: this expr should store IsArrow.
1475 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1476 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1477 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1478 Member, MemberLoc);
1479 if (ret.isNull())
1480 return ExprError();
1481
1482 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1483 *Member, MemberLoc));
1484 }
1485
1486 // Adjust builtin-sel to the appropriate redefinition type if that's
1487 // not just a pointer to builtin-sel again.
1488 if (IsArrow &&
1489 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor97673472011-08-11 20:58:55 +00001490 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1491 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1492 Context.getObjCSelRedefinitionType(),
Douglas Gregor5476205b2011-06-23 00:49:38 +00001493 CK_BitCast);
1494 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1495 ObjCImpDecl, HasTemplateArgs);
1496 }
1497
1498 // Failure cases.
1499 fail:
1500
1501 // Recover from dot accesses to pointers, e.g.:
1502 // type *foo;
1503 // foo.bar
1504 // This is actually well-formed in two cases:
1505 // - 'type' is an Objective C type
1506 // - 'bar' is a pseudo-destructor name which happens to refer to
1507 // the appropriate pointer type
1508 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1509 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1510 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1511 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1512 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1513 << FixItHint::CreateReplacement(OpLoc, "->");
1514
1515 // Recurse as an -> access.
1516 IsArrow = true;
1517 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1518 ObjCImpDecl, HasTemplateArgs);
1519 }
1520 }
1521
1522 // If the user is trying to apply -> or . to a function name, it's probably
1523 // because they forgot parentheses to call that function.
John McCall50a2c2c2011-10-11 23:14:30 +00001524 if (tryToRecoverWithCall(BaseExpr,
1525 PDiag(diag::err_member_reference_needs_call),
1526 /*complain*/ false,
Eli Friedman9a766c42012-01-13 02:20:01 +00001527 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001528 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001529 return ExprError();
John McCall50a2c2c2011-10-11 23:14:30 +00001530 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1531 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1532 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001533 }
1534
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +00001535 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001536 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001537
1538 return ExprError();
1539}
1540
1541/// The main callback when the parser finds something like
1542/// expression . [nested-name-specifier] identifier
1543/// expression -> [nested-name-specifier] identifier
1544/// where 'identifier' encompasses a fairly broad spectrum of
1545/// possibilities, including destructor and operator references.
1546///
1547/// \param OpKind either tok::arrow or tok::period
1548/// \param HasTrailingLParen whether the next token is '(', which
1549/// is used to diagnose mis-uses of special members that can
1550/// only be called
James Dennett2a4d13c2012-06-15 07:13:21 +00001551/// \param ObjCImpDecl the current Objective-C \@implementation
1552/// decl; this is an ugly hack around the fact that Objective-C
1553/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001554ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1555 SourceLocation OpLoc,
1556 tok::TokenKind OpKind,
1557 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001558 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001559 UnqualifiedId &Id,
1560 Decl *ObjCImpDecl,
1561 bool HasTrailingLParen) {
1562 if (SS.isSet() && SS.isInvalid())
1563 return ExprError();
1564
1565 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001566 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001567 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1568 Diag(Id.getSourceRange().getBegin(),
1569 diag::ext_ms_explicit_constructor_call);
1570
1571 TemplateArgumentListInfo TemplateArgsBuffer;
1572
1573 // Decompose the name into its component parts.
1574 DeclarationNameInfo NameInfo;
1575 const TemplateArgumentListInfo *TemplateArgs;
1576 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1577 NameInfo, TemplateArgs);
1578
1579 DeclarationName Name = NameInfo.getName();
1580 bool IsArrow = (OpKind == tok::arrow);
1581
1582 NamedDecl *FirstQualifierInScope
1583 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1584 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1585
1586 // This is a postfix expression, so get rid of ParenListExprs.
1587 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1588 if (Result.isInvalid()) return ExprError();
1589 Base = Result.take();
1590
1591 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1592 isDependentScopeSpecifier(SS)) {
1593 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1594 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001595 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001596 NameInfo, TemplateArgs);
1597 } else {
1598 LookupResult R(*this, NameInfo, LookupMemberName);
1599 ExprResult BaseResult = Owned(Base);
1600 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1601 SS, ObjCImpDecl, TemplateArgs != 0);
1602 if (BaseResult.isInvalid())
1603 return ExprError();
1604 Base = BaseResult.take();
1605
1606 if (Result.isInvalid()) {
1607 Owned(Base);
1608 return ExprError();
1609 }
1610
1611 if (Result.get()) {
1612 // The only way a reference to a destructor can be used is to
1613 // immediately call it, which falls into this case. If the
1614 // next token is not a '(', produce a diagnostic and build the
1615 // call now.
1616 if (!HasTrailingLParen &&
1617 Id.getKind() == UnqualifiedId::IK_DestructorName)
1618 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1619
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001620 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001621 }
1622
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001623 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor5476205b2011-06-23 00:49:38 +00001624 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001625 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001626 FirstQualifierInScope, R, TemplateArgs,
1627 false, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001628 }
1629
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001630 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001631}
1632
1633static ExprResult
1634BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1635 const CXXScopeSpec &SS, FieldDecl *Field,
1636 DeclAccessPair FoundDecl,
1637 const DeclarationNameInfo &MemberNameInfo) {
1638 // x.a is an l-value if 'a' has a reference type. Otherwise:
1639 // x.a is an l-value/x-value/pr-value if the base is (and note
1640 // that *x is always an l-value), except that if the base isn't
1641 // an ordinary object then we must have an rvalue.
1642 ExprValueKind VK = VK_LValue;
1643 ExprObjectKind OK = OK_Ordinary;
1644 if (!IsArrow) {
1645 if (BaseExpr->getObjectKind() == OK_Ordinary)
1646 VK = BaseExpr->getValueKind();
1647 else
1648 VK = VK_RValue;
1649 }
1650 if (VK != VK_RValue && Field->isBitField())
1651 OK = OK_BitField;
1652
1653 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1654 QualType MemberType = Field->getType();
1655 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1656 MemberType = Ref->getPointeeType();
1657 VK = VK_LValue;
1658 } else {
1659 QualType BaseType = BaseExpr->getType();
1660 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001661
Douglas Gregor5476205b2011-06-23 00:49:38 +00001662 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001663
Douglas Gregor5476205b2011-06-23 00:49:38 +00001664 // GC attributes are never picked up by members.
1665 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001666
Douglas Gregor5476205b2011-06-23 00:49:38 +00001667 // CVR attributes from the base are picked up by members,
1668 // except that 'mutable' members don't pick up 'const'.
1669 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001670
Douglas Gregor5476205b2011-06-23 00:49:38 +00001671 Qualifiers MemberQuals
1672 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001673
Douglas Gregor5476205b2011-06-23 00:49:38 +00001674 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001675
1676
Douglas Gregor5476205b2011-06-23 00:49:38 +00001677 Qualifiers Combined = BaseQuals + MemberQuals;
1678 if (Combined != MemberQuals)
1679 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1680 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001681
Daniel Jasper0baec5492012-06-06 08:32:04 +00001682 S.UnusedPrivateFields.remove(Field);
1683
Douglas Gregor5476205b2011-06-23 00:49:38 +00001684 ExprResult Base =
1685 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1686 FoundDecl, Field);
1687 if (Base.isInvalid())
1688 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001689 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001690 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor5476205b2011-06-23 00:49:38 +00001691 Field, FoundDecl, MemberNameInfo,
1692 MemberType, VK, OK));
1693}
1694
1695/// Builds an implicit member access expression. The current context
1696/// is known to be an instance method, and the given unqualified lookup
1697/// set is known to contain only instance members, at least one of which
1698/// is from an appropriate type.
1699ExprResult
1700Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001701 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001702 LookupResult &R,
1703 const TemplateArgumentListInfo *TemplateArgs,
1704 bool IsKnownInstance) {
1705 assert(!R.empty() && !R.isAmbiguous());
1706
1707 SourceLocation loc = R.getNameLoc();
1708
1709 // We may have found a field within an anonymous union or struct
1710 // (C++ [class.union]).
1711 // FIXME: template-ids inside anonymous structs?
1712 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
Eli Friedmancccd0642013-07-16 00:01:31 +00001713 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD,
1714 R.begin().getPair());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001715
1716 // If this is known to be an instance access, go ahead and build an
1717 // implicit 'this' expression now.
1718 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001719 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001720 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1721
1722 Expr *baseExpr = 0; // null signifies implicit access
1723 if (IsKnownInstance) {
1724 SourceLocation Loc = R.getNameLoc();
1725 if (SS.getRange().isValid())
1726 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001727 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001728 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1729 }
1730
1731 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1732 /*OpLoc*/ SourceLocation(),
1733 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001734 SS, TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001735 /*FirstQualifierInScope*/ 0,
1736 R, TemplateArgs);
1737}