blob: 4e9d250d4a40dfb5c9d9ee6a16d473826d63e4a0 [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"
Faisal Valia17d19f2013-11-07 05:17:06 +000014#include "clang/AST/ASTLambda.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000015#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000024
25using namespace clang;
26using namespace sema;
27
Richard Smithd80b2d52012-11-22 00:24:47 +000028typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
29static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
30 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
31 return !Bases.count(Base->getCanonicalDecl());
32}
33
Douglas Gregor5476205b2011-06-23 00:49:38 +000034/// Determines if the given class is provably not derived from all of
35/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000036static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
37 const BaseSet &Bases) {
38 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
39 return BaseIsNotInSet(Record, BasesPtr) &&
40 Record->forallBases(BaseIsNotInSet, BasesPtr);
Douglas Gregor5476205b2011-06-23 00:49:38 +000041}
42
43enum IMAKind {
44 /// The reference is definitely not an instance member access.
45 IMA_Static,
46
47 /// The reference may be an implicit instance member access.
48 IMA_Mixed,
49
Eli Friedman7bda7f72012-01-18 03:53:45 +000050 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000051 /// so, because the context is not an instance method.
52 IMA_Mixed_StaticContext,
53
54 /// The reference may be to an instance member, but it is invalid if
55 /// so, because the context is from an unrelated class.
56 IMA_Mixed_Unrelated,
57
58 /// The reference is definitely an implicit instance member access.
59 IMA_Instance,
60
61 /// The reference may be to an unresolved using declaration.
62 IMA_Unresolved,
63
John McCallf413f5e2013-05-03 00:10:13 +000064 /// The reference is a contextually-permitted abstract member reference.
65 IMA_Abstract,
66
Douglas Gregor5476205b2011-06-23 00:49:38 +000067 /// The reference may be to an unresolved using declaration and the
68 /// context is not an instance method.
69 IMA_Unresolved_StaticContext,
70
Eli Friedman456f0182012-01-20 01:26:23 +000071 // The reference refers to a field which is not a member of the containing
72 // class, which is allowed because we're in C++11 mode and the context is
73 // unevaluated.
74 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000075
Douglas Gregor5476205b2011-06-23 00:49:38 +000076 /// All possible referrents are instance members and the current
77 /// context is not an instance method.
78 IMA_Error_StaticContext,
79
80 /// All possible referrents are instance members of an unrelated
81 /// class.
82 IMA_Error_Unrelated
83};
84
85/// The given lookup names class member(s) and is not being used for
86/// an address-of-member expression. Classify the type of access
87/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000088/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000089/// conservatively answer "yes", in which case some errors will simply
90/// not be caught until template-instantiation.
91static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
92 Scope *CurScope,
93 const LookupResult &R) {
94 assert(!R.empty() && (*R.begin())->isCXXClassMember());
95
96 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
97
Douglas Gregor3024f072012-04-16 07:05:22 +000098 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
99 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000100
101 if (R.isUnresolvableResult())
102 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
103
104 // Collect all the declaring classes of instance members we find.
105 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000106 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000107 BaseSet Classes;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000108 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
109 NamedDecl *D = *I;
110
111 if (D->isCXXInstanceMember()) {
John McCall5e77d762013-04-16 07:28:30 +0000112 if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
113 || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman7bda7f72012-01-18 03:53:45 +0000114 isField = true;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000115
116 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
117 Classes.insert(R->getCanonicalDecl());
118 }
119 else
120 hasNonInstance = true;
121 }
122
123 // If we didn't find any instance members, it can't be an implicit
124 // member reference.
125 if (Classes.empty())
126 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000127
128 // C++11 [expr.prim.general]p12:
129 // An id-expression that denotes a non-static data member or non-static
130 // member function of a class can only be used:
131 // (...)
132 // - if that id-expression denotes a non-static data member and it
133 // appears in an unevaluated operand.
134 //
135 // This rule is specific to C++11. However, we also permit this form
136 // in unevaluated inline assembly operands, like the operand to a SIZE.
137 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
138 assert(!AbstractInstanceResult);
139 switch (SemaRef.ExprEvalContexts.back().Context) {
140 case Sema::Unevaluated:
141 if (isField && SemaRef.getLangOpts().CPlusPlus11)
142 AbstractInstanceResult = IMA_Field_Uneval_Context;
143 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000144
John McCallf413f5e2013-05-03 00:10:13 +0000145 case Sema::UnevaluatedAbstract:
146 AbstractInstanceResult = IMA_Abstract;
147 break;
148
149 case Sema::ConstantEvaluated:
150 case Sema::PotentiallyEvaluated:
151 case Sema::PotentiallyEvaluatedIfUsed:
152 break;
Richard Smitheae99682012-02-25 10:04:07 +0000153 }
154
Douglas Gregor5476205b2011-06-23 00:49:38 +0000155 // If the current context is not an instance method, it can't be
156 // an implicit member reference.
157 if (isStaticContext) {
158 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000159 return IMA_Mixed_StaticContext;
160
John McCallf413f5e2013-05-03 00:10:13 +0000161 return AbstractInstanceResult ? AbstractInstanceResult
162 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000163 }
164
165 CXXRecordDecl *contextClass;
166 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
167 contextClass = MD->getParent()->getCanonicalDecl();
168 else
169 contextClass = cast<CXXRecordDecl>(DC);
170
171 // [class.mfct.non-static]p3:
172 // ...is used in the body of a non-static member function of class X,
173 // if name lookup (3.4.1) resolves the name in the id-expression to a
174 // non-static non-type member of some class C [...]
175 // ...if C is not X or a base class of X, the class member access expression
176 // is ill-formed.
177 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000178 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000179 R.getNamingClass()->getCanonicalDecl()) {
180 // If the naming class is not the current context, this was a qualified
181 // member name lookup, and it's sufficient to check that we have the naming
182 // class as a base class.
183 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000184 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000185 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000186
187 // If we can prove that the current context is unrelated to all the
188 // declaring classes, it can't be an implicit member reference (in
189 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000190 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000191 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000192 AbstractInstanceResult ? AbstractInstanceResult :
193 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000194
195 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
196}
197
198/// Diagnose a reference to a field with no object available.
Richard Smithfa0a1f52012-04-05 01:13:04 +0000199static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000200 const CXXScopeSpec &SS,
Richard Smithfa0a1f52012-04-05 01:13:04 +0000201 NamedDecl *Rep,
Eli Friedman456f0182012-01-20 01:26:23 +0000202 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000203 SourceLocation Loc = nameInfo.getLoc();
204 SourceRange Range(Loc);
205 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000206
Richard Smithfa0a1f52012-04-05 01:13:04 +0000207 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
208 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
209 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
210 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
211
212 bool InStaticMethod = Method && Method->isStatic();
213 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
214
215 if (IsField && InStaticMethod)
216 // "invalid use of member 'x' in static member function"
217 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
218 << Range << nameInfo.getName();
219 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
220 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
221 // Unqualified lookup in a non-static member function found a member of an
222 // enclosing class.
223 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
224 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
225 else if (IsField)
Eli Friedman456f0182012-01-20 01:26:23 +0000226 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000227 << nameInfo.getName() << Range;
228 else
229 SemaRef.Diag(Loc, diag::err_member_call_without_object)
230 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000231}
232
233/// Builds an expression which might be an implicit member expression.
234ExprResult
235Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000236 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000237 LookupResult &R,
238 const TemplateArgumentListInfo *TemplateArgs) {
239 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
240 case IMA_Instance:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000241 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000242
243 case IMA_Mixed:
244 case IMA_Mixed_Unrelated:
245 case IMA_Unresolved:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000246 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000247
Richard Smith2a986112012-02-25 10:20:59 +0000248 case IMA_Field_Uneval_Context:
249 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
250 << R.getLookupNameInfo().getName();
251 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000252 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000253 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000254 case IMA_Mixed_StaticContext:
255 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000256 if (TemplateArgs || TemplateKWLoc.isValid())
257 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000258 return BuildDeclarationNameExpr(SS, R, false);
259
260 case IMA_Error_StaticContext:
261 case IMA_Error_Unrelated:
Richard Smithfa0a1f52012-04-05 01:13:04 +0000262 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000263 R.getLookupNameInfo());
264 return ExprError();
265 }
266
267 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000268}
269
270/// Check an ext-vector component access expression.
271///
272/// VK should be set in advance to the value kind of the base
273/// expression.
274static QualType
275CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
276 SourceLocation OpLoc, const IdentifierInfo *CompName,
277 SourceLocation CompLoc) {
278 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
279 // see FIXME there.
280 //
281 // FIXME: This logic can be greatly simplified by splitting it along
282 // halving/not halving and reworking the component checking.
283 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
284
285 // The vector accessor can't exceed the number of elements.
286 const char *compStr = CompName->getNameStart();
287
288 // This flag determines whether or not the component is one of the four
289 // special names that indicate a subset of exactly half the elements are
290 // to be selected.
291 bool HalvingSwizzle = false;
292
293 // This flag determines whether or not CompName has an 's' char prefix,
294 // indicating that it is a string of hex values to be used as vector indices.
295 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
296
297 bool HasRepeated = false;
298 bool HasIndex[16] = {};
299
300 int Idx;
301
302 // Check that we've found one of the special components, or that the component
303 // names must come from the same set.
304 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
305 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
306 HalvingSwizzle = true;
307 } else if (!HexSwizzle &&
308 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
309 do {
310 if (HasIndex[Idx]) HasRepeated = true;
311 HasIndex[Idx] = true;
312 compStr++;
313 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
314 } else {
315 if (HexSwizzle) compStr++;
316 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
317 if (HasIndex[Idx]) HasRepeated = true;
318 HasIndex[Idx] = true;
319 compStr++;
320 }
321 }
322
323 if (!HalvingSwizzle && *compStr) {
324 // We didn't get to the end of the string. This means the component names
325 // didn't come from the same set *or* we encountered an illegal name.
326 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000327 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000328 return QualType();
329 }
330
331 // Ensure no component accessor exceeds the width of the vector type it
332 // operates on.
333 if (!HalvingSwizzle) {
334 compStr = CompName->getNameStart();
335
336 if (HexSwizzle)
337 compStr++;
338
339 while (*compStr) {
340 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
341 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
342 << baseType << SourceRange(CompLoc);
343 return QualType();
344 }
345 }
346 }
347
348 // The component accessor looks fine - now we need to compute the actual type.
349 // The vector type is implied by the component accessor. For example,
350 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
351 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
352 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
353 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
354 : CompName->getLength();
355 if (HexSwizzle)
356 CompSize--;
357
358 if (CompSize == 1)
359 return vecType->getElementType();
360
361 if (HasRepeated) VK = VK_RValue;
362
363 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
364 // Now look up the TypeDefDecl from the vector type. Without this,
365 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000366 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000367 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000368 E = S.ExtVectorDecls.end();
369 I != E; ++I) {
370 if ((*I)->getUnderlyingType() == VT)
371 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000372 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000373
Douglas Gregor5476205b2011-06-23 00:49:38 +0000374 return VT; // should never get here (a typedef type should always be found).
375}
376
377static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
378 IdentifierInfo *Member,
379 const Selector &Sel,
380 ASTContext &Context) {
381 if (Member)
382 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
383 return PD;
384 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
385 return OMD;
386
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000387 for (const auto *I : PDecl->protocols()) {
388 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000389 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
Craig Toppere14c0f82014-03-12 04:55:44 +0000548 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000549 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.
Aaron Ballman574705e2014-03-13 15:41:46 +0000561 for (const auto &BS : RD->bases()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000562 if (const RecordType *BSTy = dyn_cast_or_null<RecordType>(
Aaron Ballman574705e2014-03-13 15:41:46 +0000563 BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000564 if (BSTy->getDecl()->containsDecl(ND))
565 return true;
566 }
567 }
568 }
569
570 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000571 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000572
573 private:
574 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000575};
576
577}
578
Douglas Gregor5476205b2011-06-23 00:49:38 +0000579static bool
Douglas Gregor3024f072012-04-16 07:05:22 +0000580LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000581 SourceRange BaseRange, const RecordType *RTy,
582 SourceLocation OpLoc, CXXScopeSpec &SS,
583 bool HasTemplateArgs) {
584 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000585 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
586 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000587 diag::err_typecheck_incomplete_tag,
588 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000589 return true;
590
591 if (HasTemplateArgs) {
592 // LookupTemplateName doesn't expect these both to exist simultaneously.
593 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
594
595 bool MOUS;
596 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
597 return false;
598 }
599
600 DeclContext *DC = RDecl;
601 if (SS.isSet()) {
602 // If the member name was a qualified-id, look into the
603 // nested-name-specifier.
604 DC = SemaRef.computeDeclContext(SS, false);
605
606 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
607 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
608 << SS.getRange() << DC;
609 return true;
610 }
611
612 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
613
614 if (!isa<TypeDecl>(DC)) {
615 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
616 << DC << SS.getRange();
617 return true;
618 }
619 }
620
621 // The record definition is complete, now look up the member.
622 SemaRef.LookupQualifiedName(R, DC);
623
624 if (!R.empty())
625 return false;
626
627 // We didn't find anything with the given name, so try to correct
628 // for typos.
629 DeclarationName Name = R.getLookupName();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000630 RecordMemberExprValidatorCCC Validator(RTy);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000631 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
632 R.getLookupKind(), NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +0000633 &SS, Validator, DC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000634 R.clear();
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000635 if (Corrected.isResolved() && !Corrected.isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000636 R.setLookupName(Corrected.getCorrection());
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000637 for (TypoCorrection::decl_iterator DI = Corrected.begin(),
638 DIEnd = Corrected.end();
639 DI != DIEnd; ++DI) {
640 R.addDecl(*DI);
641 }
642 R.resolveKind();
643
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000644 // If we're typo-correcting to an overloaded name, we don't yet have enough
645 // information to do overload resolution, so we don't know which previous
646 // declaration to point to.
Richard Smithf9b15102013-08-17 00:46:16 +0000647 if (Corrected.isOverloaded())
648 Corrected.setCorrectionDecl(0);
649 bool DroppedSpecifier =
650 Corrected.WillReplaceSpecifier() &&
651 Name.getAsString() == Corrected.getAsString(SemaRef.getLangOpts());
652 SemaRef.diagnoseTypo(Corrected,
653 SemaRef.PDiag(diag::err_no_member_suggest)
654 << Name << DC << DroppedSpecifier << SS.getRange());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000655 }
656
657 return false;
658}
659
660ExprResult
661Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
662 SourceLocation OpLoc, bool IsArrow,
663 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000664 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000665 NamedDecl *FirstQualifierInScope,
666 const DeclarationNameInfo &NameInfo,
667 const TemplateArgumentListInfo *TemplateArgs) {
668 if (BaseType->isDependentType() ||
669 (SS.isSet() && isDependentScopeSpecifier(SS)))
670 return ActOnDependentMemberExpr(Base, BaseType,
671 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000672 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000673 NameInfo, TemplateArgs);
674
675 LookupResult R(*this, NameInfo, LookupMemberName);
676
677 // Implicit member accesses.
678 if (!Base) {
679 QualType RecordTy = BaseType;
680 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
681 if (LookupMemberExprInRecord(*this, R, SourceRange(),
682 RecordTy->getAs<RecordType>(),
683 OpLoc, SS, TemplateArgs != 0))
684 return ExprError();
685
686 // Explicit member accesses.
687 } else {
688 ExprResult BaseResult = Owned(Base);
689 ExprResult Result =
690 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
691 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
692
693 if (BaseResult.isInvalid())
694 return ExprError();
695 Base = BaseResult.take();
696
697 if (Result.isInvalid()) {
698 Owned(Base);
699 return ExprError();
700 }
701
702 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000703 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000704
705 // LookupMemberExpr can modify Base, and thus change BaseType
706 BaseType = Base->getType();
707 }
708
709 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000710 OpLoc, IsArrow, SS, TemplateKWLoc,
711 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000712}
713
714static ExprResult
715BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
716 const CXXScopeSpec &SS, FieldDecl *Field,
717 DeclAccessPair FoundDecl,
718 const DeclarationNameInfo &MemberNameInfo);
719
720ExprResult
721Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
722 SourceLocation loc,
723 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000724 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000725 Expr *baseObjectExpr,
726 SourceLocation opLoc) {
727 // First, build the expression that refers to the base object.
728
729 bool baseObjectIsPointer = false;
730 Qualifiers baseQuals;
731
732 // Case 1: the base of the indirect field is not a field.
733 VarDecl *baseVariable = indirectField->getVarDecl();
734 CXXScopeSpec EmptySS;
735 if (baseVariable) {
736 assert(baseVariable->getType()->isRecordType());
737
738 // In principle we could have a member access expression that
739 // accesses an anonymous struct/union that's a static member of
740 // the base object's class. However, under the current standard,
741 // static data members cannot be anonymous structs or unions.
742 // Supporting this is as easy as building a MemberExpr here.
743 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
744
745 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
746
747 ExprResult result
748 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
749 if (result.isInvalid()) return ExprError();
750
751 baseObjectExpr = result.take();
752 baseObjectIsPointer = false;
753 baseQuals = baseObjectExpr->getType().getQualifiers();
754
755 // Case 2: the base of the indirect field is a field and the user
756 // wrote a member expression.
757 } else if (baseObjectExpr) {
758 // The caller provided the base object expression. Determine
759 // whether its a pointer and whether it adds any qualifiers to the
760 // anonymous struct/union fields we're looking into.
761 QualType objectType = baseObjectExpr->getType();
762
763 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
764 baseObjectIsPointer = true;
765 objectType = ptr->getPointeeType();
766 } else {
767 baseObjectIsPointer = false;
768 }
769 baseQuals = objectType.getQualifiers();
770
771 // Case 3: the base of the indirect field is a field and we should
772 // build an implicit member access.
773 } else {
774 // We've found a member of an anonymous struct/union that is
775 // inside a non-anonymous struct/union, so in a well-formed
776 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000777 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000778 if (ThisTy.isNull()) {
779 Diag(loc, diag::err_invalid_member_use_in_static_method)
780 << indirectField->getDeclName();
781 return ExprError();
782 }
783
784 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000785 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000786 baseObjectExpr
787 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
788 baseObjectIsPointer = true;
789 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
790 }
791
792 // Build the implicit member references to the field of the
793 // anonymous struct/union.
794 Expr *result = baseObjectExpr;
795 IndirectFieldDecl::chain_iterator
796 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
797
798 // Build the first member access in the chain with full information.
799 if (!baseVariable) {
800 FieldDecl *field = cast<FieldDecl>(*FI);
801
Douglas Gregor5476205b2011-06-23 00:49:38 +0000802 // Make a nameInfo that properly uses the anonymous name.
803 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
804
805 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
806 EmptySS, field, foundDecl,
807 memberNameInfo).take();
Eli Friedmancccd0642013-07-16 00:01:31 +0000808 if (!result)
809 return ExprError();
810
Douglas Gregor5476205b2011-06-23 00:49:38 +0000811 baseObjectIsPointer = false;
812
813 // FIXME: check qualified member access
814 }
815
816 // In all cases, we should now skip the first declaration in the chain.
817 ++FI;
818
819 while (FI != FEnd) {
820 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000821
Douglas Gregor5476205b2011-06-23 00:49:38 +0000822 // FIXME: these are somewhat meaningless
823 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000824 DeclAccessPair fakeFoundDecl =
825 DeclAccessPair::make(field, field->getAccess());
826
Douglas Gregor5476205b2011-06-23 00:49:38 +0000827 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Eli Friedmancccd0642013-07-16 00:01:31 +0000828 (FI == FEnd? SS : EmptySS), field,
829 fakeFoundDecl, memberNameInfo).take();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000830 }
831
832 return Owned(result);
833}
834
John McCall5e77d762013-04-16 07:28:30 +0000835static ExprResult
836BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
837 const CXXScopeSpec &SS,
838 MSPropertyDecl *PD,
839 const DeclarationNameInfo &NameInfo) {
840 // Property names are always simple identifiers and therefore never
841 // require any interesting additional storage.
842 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
843 S.Context.PseudoObjectTy, VK_LValue,
844 SS.getWithLocInContext(S.Context),
845 NameInfo.getLoc());
846}
847
Douglas Gregor5476205b2011-06-23 00:49:38 +0000848/// \brief Build a MemberExpr AST node.
Eli Friedmanfa0df832012-02-02 03:46:19 +0000849static MemberExpr *BuildMemberExpr(Sema &SemaRef,
850 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000851 const CXXScopeSpec &SS,
852 SourceLocation TemplateKWLoc,
853 ValueDecl *Member,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000854 DeclAccessPair FoundDecl,
855 const DeclarationNameInfo &MemberNameInfo,
856 QualType Ty,
857 ExprValueKind VK, ExprObjectKind OK,
858 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith08b12f12011-10-27 22:11:44 +0000859 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedmanfa0df832012-02-02 03:46:19 +0000860 MemberExpr *E =
861 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
862 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
863 TemplateArgs, Ty, VK, OK);
864 SemaRef.MarkMemberReferenced(E);
865 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000866}
867
868ExprResult
869Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
870 SourceLocation OpLoc, bool IsArrow,
871 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000872 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000873 NamedDecl *FirstQualifierInScope,
874 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000875 const TemplateArgumentListInfo *TemplateArgs,
876 bool SuppressQualifierCheck,
877 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000878 QualType BaseType = BaseExprType;
879 if (IsArrow) {
880 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000881 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000882 }
883 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000884
885 LambdaScopeInfo *const CurLSI = getCurLambda();
886 // If this is an implicit member reference and the overloaded
887 // name refers to both static and non-static member functions
888 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
889 // check if we should/can capture 'this'...
890 // Keep this example in mind:
891 // struct X {
892 // void f(int) { }
893 // static void f(double) { }
894 //
895 // int g() {
896 // auto L = [=](auto a) {
897 // return [](int i) {
898 // return [=](auto b) {
899 // f(b);
900 // //f(decltype(a){});
901 // };
902 // };
903 // };
904 // auto M = L(0.0);
905 // auto N = M(3);
906 // N(5.32); // OK, must not error.
907 // return 0;
908 // }
909 // };
910 //
911 if (!BaseExpr && CurLSI) {
912 SourceLocation Loc = R.getNameLoc();
913 if (SS.getRange().isValid())
914 Loc = SS.getRange().getBegin();
915 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
916 // If the enclosing function is not dependent, then this lambda is
917 // capture ready, so if we can capture this, do so.
918 if (!EnclosingFunctionCtx->isDependentContext()) {
919 // If the current lambda and all enclosing lambdas can capture 'this' -
920 // then go ahead and capture 'this' (since our unresolved overload set
921 // contains both static and non-static member functions).
922 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
923 CheckCXXThisCapture(Loc);
924 } else if (CurContext->isDependentContext()) {
925 // ... since this is an implicit member reference, that might potentially
926 // involve a 'this' capture, mark 'this' for potential capture in
927 // enclosing lambdas.
928 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
929 CurLSI->addPotentialThisCapture(Loc);
930 }
931 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000932 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
933 DeclarationName MemberName = MemberNameInfo.getName();
934 SourceLocation MemberLoc = MemberNameInfo.getLoc();
935
936 if (R.isAmbiguous())
937 return ExprError();
938
939 if (R.empty()) {
940 // Rederive where we looked up.
941 DeclContext *DC = (SS.isSet()
942 ? computeDeclContext(SS, false)
943 : BaseType->getAs<RecordType>()->getDecl());
944
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000945 if (ExtraArgs) {
946 ExprResult RetryExpr;
947 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000948 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000949 ParsedType ObjectType;
950 bool MayBePseudoDestructor = false;
951 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
952 OpLoc, tok::arrow, ObjectType,
953 MayBePseudoDestructor);
954 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
955 CXXScopeSpec TempSS(SS);
956 RetryExpr = ActOnMemberAccessExpr(
957 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
958 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
959 ExtraArgs->HasTrailingLParen);
960 }
961 if (Trap.hasErrorOccurred())
962 RetryExpr = ExprError();
963 }
964 if (RetryExpr.isUsable()) {
965 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
966 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
967 return RetryExpr;
968 }
969 }
970
Douglas Gregor5476205b2011-06-23 00:49:38 +0000971 Diag(R.getNameLoc(), diag::err_no_member)
972 << MemberName << DC
973 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
974 return ExprError();
975 }
976
977 // Diagnose lookups that find only declarations from a non-base
978 // type. This is possible for either qualified lookups (which may
979 // have been qualified with an unrelated type) or implicit member
980 // expressions (which were found with unqualified lookup and thus
981 // may have come from an enclosing scope). Note that it's okay for
982 // lookup to find declarations from a non-base type as long as those
983 // aren't the ones picked by overload resolution.
984 if ((SS.isSet() || !BaseExpr ||
985 (isa<CXXThisExpr>(BaseExpr) &&
986 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
987 !SuppressQualifierCheck &&
988 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
989 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +0000990
Douglas Gregor5476205b2011-06-23 00:49:38 +0000991 // Construct an unresolved result if we in fact got an unresolved
992 // result.
993 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
994 // Suppress any lookup-related diagnostics; we'll do these when we
995 // pick a member.
996 R.suppressDiagnostics();
997
998 UnresolvedMemberExpr *MemExpr
999 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1000 BaseExpr, BaseExprType,
1001 IsArrow, OpLoc,
1002 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001003 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001004 TemplateArgs, R.begin(), R.end());
1005
1006 return Owned(MemExpr);
1007 }
1008
1009 assert(R.isSingleResult());
1010 DeclAccessPair FoundDecl = R.begin().getPair();
1011 NamedDecl *MemberDecl = R.getFoundDecl();
1012
1013 // FIXME: diagnose the presence of template arguments now.
1014
1015 // If the decl being referenced had an error, return an error for this
1016 // sub-expr without emitting another error, in order to avoid cascading
1017 // error cases.
1018 if (MemberDecl->isInvalidDecl())
1019 return ExprError();
1020
1021 // Handle the implicit-member-access case.
1022 if (!BaseExpr) {
1023 // If this is not an instance member, convert to a non-member access.
1024 if (!MemberDecl->isCXXInstanceMember())
1025 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1026
1027 SourceLocation Loc = R.getNameLoc();
1028 if (SS.getRange().isValid())
1029 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001030 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001031 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1032 }
1033
1034 bool ShouldCheckUse = true;
1035 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1036 // Don't diagnose the use of a virtual member function unless it's
1037 // explicitly qualified.
1038 if (MD->isVirtual() && !SS.isSet())
1039 ShouldCheckUse = false;
1040 }
1041
1042 // Check the use of this member.
1043 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
1044 Owned(BaseExpr);
1045 return ExprError();
1046 }
1047
Douglas Gregor5476205b2011-06-23 00:49:38 +00001048 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1049 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
1050 SS, FD, FoundDecl, MemberNameInfo);
1051
John McCall5e77d762013-04-16 07:28:30 +00001052 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1053 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1054 MemberNameInfo);
1055
Douglas Gregor5476205b2011-06-23 00:49:38 +00001056 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1057 // We may have found a field within an anonymous union or struct
1058 // (C++ [class.union]).
1059 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001060 FoundDecl, BaseExpr,
1061 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001062
1063 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00001064 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1065 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001066 Var->getType().getNonReferenceType(),
1067 VK_LValue, OK_Ordinary));
1068 }
1069
1070 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1071 ExprValueKind valueKind;
1072 QualType type;
1073 if (MemberFn->isInstance()) {
1074 valueKind = VK_RValue;
1075 type = Context.BoundMemberTy;
1076 } else {
1077 valueKind = VK_LValue;
1078 type = MemberFn->getType();
1079 }
1080
Eli Friedmanfa0df832012-02-02 03:46:19 +00001081 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1082 TemplateKWLoc, MemberFn, FoundDecl,
1083 MemberNameInfo, type, valueKind,
1084 OK_Ordinary));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001085 }
1086 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1087
1088 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedmanfa0df832012-02-02 03:46:19 +00001089 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
1090 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001091 Enum->getType(), VK_RValue, OK_Ordinary));
1092 }
1093
1094 Owned(BaseExpr);
1095
1096 // We found something that we didn't expect. Complain.
1097 if (isa<TypeDecl>(MemberDecl))
1098 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1099 << MemberName << BaseType << int(IsArrow);
1100 else
1101 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1102 << MemberName << BaseType << int(IsArrow);
1103
1104 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1105 << MemberName;
1106 R.suppressDiagnostics();
1107 return ExprError();
1108}
1109
1110/// Given that normal member access failed on the given expression,
1111/// and given that the expression's type involves builtin-id or
1112/// builtin-Class, decide whether substituting in the redefinition
1113/// types would be profitable. The redefinition type is whatever
1114/// this translation unit tried to typedef to id/Class; we store
1115/// it to the side and then re-use it in places like this.
1116static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1117 const ObjCObjectPointerType *opty
1118 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1119 if (!opty) return false;
1120
1121 const ObjCObjectType *ty = opty->getObjectType();
1122
1123 QualType redef;
1124 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001125 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001126 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001127 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001128 } else {
1129 return false;
1130 }
1131
1132 // Do the substitution as long as the redefinition type isn't just a
1133 // possibly-qualified pointer to builtin-id or builtin-Class again.
1134 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001135 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001136 return false;
1137
1138 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1139 return true;
1140}
1141
John McCall50a2c2c2011-10-11 23:14:30 +00001142static bool isRecordType(QualType T) {
1143 return T->isRecordType();
1144}
1145static bool isPointerToRecordType(QualType T) {
1146 if (const PointerType *PT = T->getAs<PointerType>())
1147 return PT->getPointeeType()->isRecordType();
1148 return false;
1149}
1150
Richard Smithcab9a7d2011-10-26 19:06:56 +00001151/// Perform conversions on the LHS of a member access expression.
1152ExprResult
1153Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001154 if (IsArrow && !Base->getType()->isFunctionType())
1155 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001156
Eli Friedman9a766c42012-01-13 02:20:01 +00001157 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001158}
1159
Douglas Gregor5476205b2011-06-23 00:49:38 +00001160/// Look up the given member of the given non-type-dependent
1161/// expression. This can return in one of two ways:
1162/// * If it returns a sentinel null-but-valid result, the caller will
1163/// assume that lookup was performed and the results written into
1164/// the provided structure. It will take over from there.
1165/// * Otherwise, the returned expression will be produced in place of
1166/// an ordinary member expression.
1167///
1168/// The ObjCImpDecl bit is a gross hack that will need to be properly
1169/// fixed for ObjC++.
1170ExprResult
1171Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1172 bool &IsArrow, SourceLocation OpLoc,
1173 CXXScopeSpec &SS,
1174 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1175 assert(BaseExpr.get() && "no base expression");
1176
1177 // Perform default conversions.
Richard Smithcab9a7d2011-10-26 19:06:56 +00001178 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001179 if (BaseExpr.isInvalid())
1180 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001181
Douglas Gregor5476205b2011-06-23 00:49:38 +00001182 QualType BaseType = BaseExpr.get()->getType();
1183 assert(!BaseType->isDependentType());
1184
1185 DeclarationName MemberName = R.getLookupName();
1186 SourceLocation MemberLoc = R.getNameLoc();
1187
1188 // For later type-checking purposes, turn arrow accesses into dot
1189 // accesses. The only access type we support that doesn't follow
1190 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1191 // and those never use arrows, so this is unaffected.
1192 if (IsArrow) {
1193 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1194 BaseType = Ptr->getPointeeType();
1195 else if (const ObjCObjectPointerType *Ptr
1196 = BaseType->getAs<ObjCObjectPointerType>())
1197 BaseType = Ptr->getPointeeType();
1198 else if (BaseType->isRecordType()) {
1199 // Recover from arrow accesses to records, e.g.:
1200 // struct MyRecord foo;
1201 // foo->bar
1202 // This is actually well-formed in C++ if MyRecord has an
1203 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001204 // by now--or a diagnostic message already issued if a problem
1205 // was encountered while looking for the overloaded operator->.
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001206 if (!getLangOpts().CPlusPlus) {
1207 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1208 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1209 << FixItHint::CreateReplacement(OpLoc, ".");
1210 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001211 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001212 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001213 goto fail;
1214 } else {
1215 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1216 << BaseType << BaseExpr.get()->getSourceRange();
1217 return ExprError();
1218 }
1219 }
1220
1221 // Handle field access to simple records.
1222 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1223 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1224 RTy, OpLoc, SS, HasTemplateArgs))
1225 return ExprError();
1226
1227 // Returning valid-but-null is how we indicate to the caller that
1228 // the lookup result was filled in.
1229 return Owned((Expr*) 0);
1230 }
1231
1232 // Handle ivar access to Objective-C objects.
1233 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001234 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregor12340e52011-10-09 23:22:49 +00001235 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1236 << 1 << SS.getScopeRep()
1237 << FixItHint::CreateRemoval(SS.getRange());
1238 SS.clear();
1239 }
1240
Douglas Gregor5476205b2011-06-23 00:49:38 +00001241 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1242
1243 // There are three cases for the base type:
1244 // - builtin id (qualified or unqualified)
1245 // - builtin Class (qualified or unqualified)
1246 // - an interface
1247 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1248 if (!IDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001249 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001250 (OTy->isObjCId() || OTy->isObjCClass()))
1251 goto fail;
1252 // There's an implicit 'isa' ivar on all objects.
1253 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001254 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001255 if (OTy->isObjCId() && Member->isStr("isa"))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001256 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
Fariborz Jahanian06bb7f72013-03-28 19:50:55 +00001257 OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001258 Context.getObjCClassType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001259 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1260 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1261 ObjCImpDecl, HasTemplateArgs);
1262 goto fail;
1263 }
Fariborz Jahanian25cb4ac2012-06-21 21:35:15 +00001264
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001265 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1266 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001267 return ExprError();
1268
Ted Kremenek679b4782012-03-17 00:53:39 +00001269 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001270 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1271
1272 if (!IV) {
1273 // Attempt to correct for typos in ivar names.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001274 DeclFilterCCC<ObjCIvarDecl> Validator;
1275 Validator.IsObjCIvarLookup = IsArrow;
1276 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1277 LookupMemberName, NULL, NULL,
Kaelyn Uhrain4e8942c2012-01-31 23:49:25 +00001278 Validator, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001279 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smithf9b15102013-08-17 00:46:16 +00001280 diagnoseTypo(Corrected,
1281 PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1282 << IDecl->getDeclName() << MemberName);
1283
Ted Kremenek679b4782012-03-17 00:53:39 +00001284 // Figure out the class that declares the ivar.
1285 assert(!ClassDeclared);
1286 Decl *D = cast<Decl>(IV->getDeclContext());
1287 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1288 D = CAT->getClassInterface();
1289 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001290 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001291 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1292 Diag(MemberLoc,
1293 diag::err_property_found_suggest)
1294 << Member << BaseExpr.get()->getType()
1295 << FixItHint::CreateReplacement(OpLoc, ".");
1296 return ExprError();
1297 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001298
1299 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1300 << IDecl->getDeclName() << MemberName
1301 << BaseExpr.get()->getSourceRange();
1302 return ExprError();
1303 }
1304 }
Ted Kremenek679b4782012-03-17 00:53:39 +00001305
1306 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001307
1308 // If the decl being referenced had an error, return an error for this
1309 // sub-expr without emitting another error, in order to avoid cascading
1310 // error cases.
1311 if (IV->isInvalidDecl())
1312 return ExprError();
1313
1314 // Check whether we can reference this field.
1315 if (DiagnoseUseOfDecl(IV, MemberLoc))
1316 return ExprError();
1317 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1318 IV->getAccessControl() != ObjCIvarDecl::Package) {
1319 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1320 if (ObjCMethodDecl *MD = getCurMethodDecl())
1321 ClassOfMethodDecl = MD->getClassInterface();
1322 else if (ObjCImpDecl && getCurFunctionDecl()) {
1323 // Case of a c-function declared inside an objc implementation.
1324 // FIXME: For a c-style function nested inside an objc implementation
1325 // class, there is no implementation context available, so we pass
1326 // down the context as argument to this routine. Ideally, this context
1327 // need be passed down in the AST node and somehow calculated from the
1328 // AST for a function decl.
1329 if (ObjCImplementationDecl *IMPD =
1330 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1331 ClassOfMethodDecl = IMPD->getClassInterface();
1332 else if (ObjCCategoryImplDecl* CatImplClass =
1333 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1334 ClassOfMethodDecl = CatImplClass->getClassInterface();
1335 }
David Blaikiebbafb8a2012-03-11 07:00:24 +00001336 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001337 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1338 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1339 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1340 Diag(MemberLoc, diag::error_private_ivar_access)
1341 << IV->getDeclName();
1342 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1343 // @protected
1344 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001345 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001346 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001347 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001348 bool warn = true;
David Blaikiebbafb8a2012-03-11 07:00:24 +00001349 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001350 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1351 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1352 if (UO->getOpcode() == UO_Deref)
1353 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1354
1355 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001356 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001357 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001358 warn = false;
1359 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001360 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001361 if (warn) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001362 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1363 ObjCMethodFamily MF = MD->getMethodFamily();
1364 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001365 MF != OMF_finalize &&
1366 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001367 }
1368 if (warn)
1369 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1370 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001371
1372 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Fariborz Jahanianf12ff4df2013-04-02 18:57:54 +00001373 MemberLoc, OpLoc,
Jordan Rose657b5f42012-09-28 22:21:35 +00001374 BaseExpr.take(),
1375 IsArrow);
1376
1377 if (getLangOpts().ObjCAutoRefCount) {
1378 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1379 DiagnosticsEngine::Level Level =
1380 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1381 MemberLoc);
1382 if (Level != DiagnosticsEngine::Ignored)
Fariborz Jahanian6f829e32013-05-21 21:20:26 +00001383 recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001384 }
1385 }
1386
1387 return Owned(Result);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001388 }
1389
1390 // Objective-C property access.
1391 const ObjCObjectPointerType *OPT;
1392 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001393 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregor12340e52011-10-09 23:22:49 +00001394 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1395 << 0 << SS.getScopeRep()
1396 << FixItHint::CreateRemoval(SS.getRange());
1397 SS.clear();
1398 }
1399
Douglas Gregor5476205b2011-06-23 00:49:38 +00001400 // This actually uses the base as an r-value.
1401 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1402 if (BaseExpr.isInvalid())
1403 return ExprError();
1404
1405 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1406
1407 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1408
1409 const ObjCObjectType *OT = OPT->getObjectType();
1410
1411 // id, with and without qualifiers.
1412 if (OT->isObjCId()) {
1413 // Check protocols on qualified interfaces.
1414 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1415 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1416 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1417 // Check the use of this declaration
1418 if (DiagnoseUseOfDecl(PD, MemberLoc))
1419 return ExprError();
1420
John McCall526ab472011-10-25 17:37:35 +00001421 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1422 Context.PseudoObjectTy,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001423 VK_LValue,
1424 OK_ObjCProperty,
1425 MemberLoc,
1426 BaseExpr.take()));
1427 }
1428
1429 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1430 // Check the use of this method.
1431 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1432 return ExprError();
1433 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001434 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1435 PP.getSelectorTable(),
1436 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001437 ObjCMethodDecl *SMD = 0;
1438 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1439 SetterSel, Context))
1440 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001441
John McCall526ab472011-10-25 17:37:35 +00001442 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1443 Context.PseudoObjectTy,
1444 VK_LValue, OK_ObjCProperty,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001445 MemberLoc, BaseExpr.take()));
1446 }
1447 }
1448 // Use of id.member can only be for a property reference. Do not
1449 // use the 'id' redefinition in this case.
1450 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1451 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1452 ObjCImpDecl, HasTemplateArgs);
1453
1454 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1455 << MemberName << BaseType);
1456 }
1457
1458 // 'Class', unqualified only.
1459 if (OT->isObjCClass()) {
1460 // Only works in a method declaration (??!).
1461 ObjCMethodDecl *MD = getCurMethodDecl();
1462 if (!MD) {
1463 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1464 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1465 ObjCImpDecl, HasTemplateArgs);
1466
1467 goto fail;
1468 }
1469
1470 // Also must look for a getter name which uses property syntax.
1471 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1472 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1473 ObjCMethodDecl *Getter;
1474 if ((Getter = IFace->lookupClassMethod(Sel))) {
1475 // Check the use of this method.
1476 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1477 return ExprError();
1478 } else
1479 Getter = IFace->lookupPrivateMethod(Sel, false);
1480 // If we found a getter then this may be a valid dot-reference, we
1481 // will look for the matching setter, in case it is needed.
1482 Selector SetterSel =
Adrian Prantla4ce9062013-06-07 22:29:12 +00001483 SelectorTable::constructSetterSelector(PP.getIdentifierTable(),
1484 PP.getSelectorTable(),
1485 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001486 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1487 if (!Setter) {
1488 // If this reference is in an @implementation, also check for 'private'
1489 // methods.
1490 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1491 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001492
1493 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1494 return ExprError();
1495
1496 if (Getter || Setter) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001497 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall526ab472011-10-25 17:37:35 +00001498 Context.PseudoObjectTy,
1499 VK_LValue, OK_ObjCProperty,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001500 MemberLoc, BaseExpr.take()));
1501 }
1502
1503 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1504 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1505 ObjCImpDecl, HasTemplateArgs);
1506
1507 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1508 << MemberName << BaseType);
1509 }
1510
1511 // Normal property access.
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001512 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1513 MemberName, MemberLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001514 SourceLocation(), QualType(), false);
1515 }
1516
1517 // Handle 'field access' to vectors, such as 'V.xx'.
1518 if (BaseType->isExtVectorType()) {
1519 // FIXME: this expr should store IsArrow.
1520 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1521 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1522 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1523 Member, MemberLoc);
1524 if (ret.isNull())
1525 return ExprError();
1526
1527 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1528 *Member, MemberLoc));
1529 }
1530
1531 // Adjust builtin-sel to the appropriate redefinition type if that's
1532 // not just a pointer to builtin-sel again.
1533 if (IsArrow &&
1534 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor97673472011-08-11 20:58:55 +00001535 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1536 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1537 Context.getObjCSelRedefinitionType(),
Douglas Gregor5476205b2011-06-23 00:49:38 +00001538 CK_BitCast);
1539 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1540 ObjCImpDecl, HasTemplateArgs);
1541 }
1542
1543 // Failure cases.
1544 fail:
1545
1546 // Recover from dot accesses to pointers, e.g.:
1547 // type *foo;
1548 // foo.bar
1549 // This is actually well-formed in two cases:
1550 // - 'type' is an Objective C type
1551 // - 'bar' is a pseudo-destructor name which happens to refer to
1552 // the appropriate pointer type
1553 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1554 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1555 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1556 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1557 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1558 << FixItHint::CreateReplacement(OpLoc, "->");
1559
1560 // Recurse as an -> access.
1561 IsArrow = true;
1562 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1563 ObjCImpDecl, HasTemplateArgs);
1564 }
1565 }
1566
1567 // If the user is trying to apply -> or . to a function name, it's probably
1568 // because they forgot parentheses to call that function.
John McCall50a2c2c2011-10-11 23:14:30 +00001569 if (tryToRecoverWithCall(BaseExpr,
1570 PDiag(diag::err_member_reference_needs_call),
1571 /*complain*/ false,
Eli Friedman9a766c42012-01-13 02:20:01 +00001572 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001573 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001574 return ExprError();
John McCall50a2c2c2011-10-11 23:14:30 +00001575 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1576 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1577 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001578 }
1579
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +00001580 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001581 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001582
1583 return ExprError();
1584}
1585
1586/// The main callback when the parser finds something like
1587/// expression . [nested-name-specifier] identifier
1588/// expression -> [nested-name-specifier] identifier
1589/// where 'identifier' encompasses a fairly broad spectrum of
1590/// possibilities, including destructor and operator references.
1591///
1592/// \param OpKind either tok::arrow or tok::period
1593/// \param HasTrailingLParen whether the next token is '(', which
1594/// is used to diagnose mis-uses of special members that can
1595/// only be called
James Dennett2a4d13c2012-06-15 07:13:21 +00001596/// \param ObjCImpDecl the current Objective-C \@implementation
1597/// decl; this is an ugly hack around the fact that Objective-C
1598/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001599ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1600 SourceLocation OpLoc,
1601 tok::TokenKind OpKind,
1602 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001603 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001604 UnqualifiedId &Id,
1605 Decl *ObjCImpDecl,
1606 bool HasTrailingLParen) {
1607 if (SS.isSet() && SS.isInvalid())
1608 return ExprError();
1609
1610 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001611 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001612 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1613 Diag(Id.getSourceRange().getBegin(),
1614 diag::ext_ms_explicit_constructor_call);
1615
1616 TemplateArgumentListInfo TemplateArgsBuffer;
1617
1618 // Decompose the name into its component parts.
1619 DeclarationNameInfo NameInfo;
1620 const TemplateArgumentListInfo *TemplateArgs;
1621 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1622 NameInfo, TemplateArgs);
1623
1624 DeclarationName Name = NameInfo.getName();
1625 bool IsArrow = (OpKind == tok::arrow);
1626
1627 NamedDecl *FirstQualifierInScope
Aaron Ballman4a979672014-01-03 13:56:08 +00001628 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001629
1630 // This is a postfix expression, so get rid of ParenListExprs.
1631 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1632 if (Result.isInvalid()) return ExprError();
1633 Base = Result.take();
1634
1635 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1636 isDependentScopeSpecifier(SS)) {
1637 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1638 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001639 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001640 NameInfo, TemplateArgs);
1641 } else {
1642 LookupResult R(*this, NameInfo, LookupMemberName);
1643 ExprResult BaseResult = Owned(Base);
1644 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1645 SS, ObjCImpDecl, TemplateArgs != 0);
1646 if (BaseResult.isInvalid())
1647 return ExprError();
1648 Base = BaseResult.take();
1649
1650 if (Result.isInvalid()) {
1651 Owned(Base);
1652 return ExprError();
1653 }
1654
1655 if (Result.get()) {
1656 // The only way a reference to a destructor can be used is to
1657 // immediately call it, which falls into this case. If the
1658 // next token is not a '(', produce a diagnostic and build the
1659 // call now.
1660 if (!HasTrailingLParen &&
1661 Id.getKind() == UnqualifiedId::IK_DestructorName)
1662 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1663
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001664 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001665 }
1666
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001667 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor5476205b2011-06-23 00:49:38 +00001668 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001669 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001670 FirstQualifierInScope, R, TemplateArgs,
1671 false, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001672 }
1673
Benjamin Kramer62b95d82012-08-23 21:35:17 +00001674 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001675}
1676
1677static ExprResult
1678BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1679 const CXXScopeSpec &SS, FieldDecl *Field,
1680 DeclAccessPair FoundDecl,
1681 const DeclarationNameInfo &MemberNameInfo) {
1682 // x.a is an l-value if 'a' has a reference type. Otherwise:
1683 // x.a is an l-value/x-value/pr-value if the base is (and note
1684 // that *x is always an l-value), except that if the base isn't
1685 // an ordinary object then we must have an rvalue.
1686 ExprValueKind VK = VK_LValue;
1687 ExprObjectKind OK = OK_Ordinary;
1688 if (!IsArrow) {
1689 if (BaseExpr->getObjectKind() == OK_Ordinary)
1690 VK = BaseExpr->getValueKind();
1691 else
1692 VK = VK_RValue;
1693 }
1694 if (VK != VK_RValue && Field->isBitField())
1695 OK = OK_BitField;
1696
1697 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1698 QualType MemberType = Field->getType();
1699 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1700 MemberType = Ref->getPointeeType();
1701 VK = VK_LValue;
1702 } else {
1703 QualType BaseType = BaseExpr->getType();
1704 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001705
Douglas Gregor5476205b2011-06-23 00:49:38 +00001706 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001707
Douglas Gregor5476205b2011-06-23 00:49:38 +00001708 // GC attributes are never picked up by members.
1709 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001710
Douglas Gregor5476205b2011-06-23 00:49:38 +00001711 // CVR attributes from the base are picked up by members,
1712 // except that 'mutable' members don't pick up 'const'.
1713 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001714
Douglas Gregor5476205b2011-06-23 00:49:38 +00001715 Qualifiers MemberQuals
1716 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001717
Douglas Gregor5476205b2011-06-23 00:49:38 +00001718 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001719
1720
Douglas Gregor5476205b2011-06-23 00:49:38 +00001721 Qualifiers Combined = BaseQuals + MemberQuals;
1722 if (Combined != MemberQuals)
1723 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1724 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001725
Daniel Jasper0baec5492012-06-06 08:32:04 +00001726 S.UnusedPrivateFields.remove(Field);
1727
Douglas Gregor5476205b2011-06-23 00:49:38 +00001728 ExprResult Base =
1729 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1730 FoundDecl, Field);
1731 if (Base.isInvalid())
1732 return ExprError();
Eli Friedmanfa0df832012-02-02 03:46:19 +00001733 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001734 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor5476205b2011-06-23 00:49:38 +00001735 Field, FoundDecl, MemberNameInfo,
1736 MemberType, VK, OK));
1737}
1738
1739/// Builds an implicit member access expression. The current context
1740/// is known to be an instance method, and the given unqualified lookup
1741/// set is known to contain only instance members, at least one of which
1742/// is from an appropriate type.
1743ExprResult
1744Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001745 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001746 LookupResult &R,
1747 const TemplateArgumentListInfo *TemplateArgs,
1748 bool IsKnownInstance) {
1749 assert(!R.empty() && !R.isAmbiguous());
1750
1751 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001752
Douglas Gregor5476205b2011-06-23 00:49:38 +00001753 // If this is known to be an instance access, go ahead and build an
1754 // implicit 'this' expression now.
1755 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001756 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001757 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1758
1759 Expr *baseExpr = 0; // null signifies implicit access
1760 if (IsKnownInstance) {
1761 SourceLocation Loc = R.getNameLoc();
1762 if (SS.getRange().isValid())
1763 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001764 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001765 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1766 }
1767
1768 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1769 /*OpLoc*/ SourceLocation(),
1770 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001771 SS, TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001772 /*FirstQualifierInScope*/ 0,
1773 R, TemplateArgs);
1774}