blob: b3efa70b43a132bf1d29f46bd879a4679a711eb8 [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//===----------------------------------------------------------------------===//
Kaelyn Takatafe408a72014-10-27 18:07:46 +000013#include "clang/Sema/Overload.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"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "clang/Sema/SemaInternal.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000025
26using namespace clang;
27using namespace sema;
28
Richard Smithd80b2d52012-11-22 00:24:47 +000029typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
30static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
31 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
32 return !Bases.count(Base->getCanonicalDecl());
33}
34
Douglas Gregor5476205b2011-06-23 00:49:38 +000035/// Determines if the given class is provably not derived from all of
36/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000037static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
38 const BaseSet &Bases) {
39 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
40 return BaseIsNotInSet(Record, BasesPtr) &&
41 Record->forallBases(BaseIsNotInSet, BasesPtr);
Douglas Gregor5476205b2011-06-23 00:49:38 +000042}
43
44enum IMAKind {
45 /// The reference is definitely not an instance member access.
46 IMA_Static,
47
48 /// The reference may be an implicit instance member access.
49 IMA_Mixed,
50
Eli Friedman7bda7f72012-01-18 03:53:45 +000051 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000052 /// so, because the context is not an instance method.
53 IMA_Mixed_StaticContext,
54
55 /// The reference may be to an instance member, but it is invalid if
56 /// so, because the context is from an unrelated class.
57 IMA_Mixed_Unrelated,
58
59 /// The reference is definitely an implicit instance member access.
60 IMA_Instance,
61
62 /// The reference may be to an unresolved using declaration.
63 IMA_Unresolved,
64
John McCallf413f5e2013-05-03 00:10:13 +000065 /// The reference is a contextually-permitted abstract member reference.
66 IMA_Abstract,
67
Douglas Gregor5476205b2011-06-23 00:49:38 +000068 /// The reference may be to an unresolved using declaration and the
69 /// context is not an instance method.
70 IMA_Unresolved_StaticContext,
71
Eli Friedman456f0182012-01-20 01:26:23 +000072 // The reference refers to a field which is not a member of the containing
73 // class, which is allowed because we're in C++11 mode and the context is
74 // unevaluated.
75 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000076
Douglas Gregor5476205b2011-06-23 00:49:38 +000077 /// All possible referrents are instance members and the current
78 /// context is not an instance method.
79 IMA_Error_StaticContext,
80
81 /// All possible referrents are instance members of an unrelated
82 /// class.
83 IMA_Error_Unrelated
84};
85
86/// The given lookup names class member(s) and is not being used for
87/// an address-of-member expression. Classify the type of access
88/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000089/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000090/// conservatively answer "yes", in which case some errors will simply
91/// not be caught until template-instantiation.
92static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +000093 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
Reid Klecknerae628962014-12-18 00:42:51 +0000207 // Look through using shadow decls and aliases.
208 Rep = Rep->getUnderlyingDecl();
209
Richard Smithfa0a1f52012-04-05 01:13:04 +0000210 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
211 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000212 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000213 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
214
215 bool InStaticMethod = Method && Method->isStatic();
216 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
217
218 if (IsField && InStaticMethod)
219 // "invalid use of member 'x' in static member function"
220 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
221 << Range << nameInfo.getName();
222 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
223 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
224 // Unqualified lookup in a non-static member function found a member of an
225 // enclosing class.
226 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
227 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
228 else if (IsField)
Eli Friedman456f0182012-01-20 01:26:23 +0000229 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000230 << nameInfo.getName() << Range;
231 else
232 SemaRef.Diag(Loc, diag::err_member_call_without_object)
233 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000234}
235
236/// Builds an expression which might be an implicit member expression.
237ExprResult
238Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000239 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000240 LookupResult &R,
241 const TemplateArgumentListInfo *TemplateArgs) {
Reid Klecknerae628962014-12-18 00:42:51 +0000242 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000243 case IMA_Instance:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000244 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000245
246 case IMA_Mixed:
247 case IMA_Mixed_Unrelated:
248 case IMA_Unresolved:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000249 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000250
Richard Smith2a986112012-02-25 10:20:59 +0000251 case IMA_Field_Uneval_Context:
252 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
253 << R.getLookupNameInfo().getName();
254 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000255 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000256 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000257 case IMA_Mixed_StaticContext:
258 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000259 if (TemplateArgs || TemplateKWLoc.isValid())
260 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000261 return BuildDeclarationNameExpr(SS, R, false);
262
263 case IMA_Error_StaticContext:
264 case IMA_Error_Unrelated:
Richard Smithfa0a1f52012-04-05 01:13:04 +0000265 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000266 R.getLookupNameInfo());
267 return ExprError();
268 }
269
270 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000271}
272
273/// Check an ext-vector component access expression.
274///
275/// VK should be set in advance to the value kind of the base
276/// expression.
277static QualType
278CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
279 SourceLocation OpLoc, const IdentifierInfo *CompName,
280 SourceLocation CompLoc) {
281 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
282 // see FIXME there.
283 //
284 // FIXME: This logic can be greatly simplified by splitting it along
285 // halving/not halving and reworking the component checking.
286 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
287
288 // The vector accessor can't exceed the number of elements.
289 const char *compStr = CompName->getNameStart();
290
291 // This flag determines whether or not the component is one of the four
292 // special names that indicate a subset of exactly half the elements are
293 // to be selected.
294 bool HalvingSwizzle = false;
295
296 // This flag determines whether or not CompName has an 's' char prefix,
297 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000298 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000299
300 bool HasRepeated = false;
301 bool HasIndex[16] = {};
302
303 int Idx;
304
305 // Check that we've found one of the special components, or that the component
306 // names must come from the same set.
307 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
308 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
309 HalvingSwizzle = true;
310 } else if (!HexSwizzle &&
311 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
312 do {
313 if (HasIndex[Idx]) HasRepeated = true;
314 HasIndex[Idx] = true;
315 compStr++;
316 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
317 } else {
318 if (HexSwizzle) compStr++;
319 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
320 if (HasIndex[Idx]) HasRepeated = true;
321 HasIndex[Idx] = true;
322 compStr++;
323 }
324 }
325
326 if (!HalvingSwizzle && *compStr) {
327 // We didn't get to the end of the string. This means the component names
328 // didn't come from the same set *or* we encountered an illegal name.
329 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000330 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000331 return QualType();
332 }
333
334 // Ensure no component accessor exceeds the width of the vector type it
335 // operates on.
336 if (!HalvingSwizzle) {
337 compStr = CompName->getNameStart();
338
339 if (HexSwizzle)
340 compStr++;
341
342 while (*compStr) {
343 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
344 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
345 << baseType << SourceRange(CompLoc);
346 return QualType();
347 }
348 }
349 }
350
351 // The component accessor looks fine - now we need to compute the actual type.
352 // The vector type is implied by the component accessor. For example,
353 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
354 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
355 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
356 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
357 : CompName->getLength();
358 if (HexSwizzle)
359 CompSize--;
360
361 if (CompSize == 1)
362 return vecType->getElementType();
363
364 if (HasRepeated) VK = VK_RValue;
365
366 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
367 // Now look up the TypeDefDecl from the vector type. Without this,
368 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000369 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000370 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000371 E = S.ExtVectorDecls.end();
372 I != E; ++I) {
373 if ((*I)->getUnderlyingType() == VT)
374 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000375 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000376
Douglas Gregor5476205b2011-06-23 00:49:38 +0000377 return VT; // should never get here (a typedef type should always be found).
378}
379
380static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
381 IdentifierInfo *Member,
382 const Selector &Sel,
383 ASTContext &Context) {
384 if (Member)
385 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
386 return PD;
387 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
388 return OMD;
389
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000390 for (const auto *I : PDecl->protocols()) {
391 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000392 Context))
393 return D;
394 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000395 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000396}
397
398static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
399 IdentifierInfo *Member,
400 const Selector &Sel,
401 ASTContext &Context) {
402 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000403 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000404 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000405 if (Member)
Aaron Ballman83731462014-03-17 16:14:00 +0000406 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000407 GDecl = PD;
408 break;
409 }
410 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000411 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000412 GDecl = OMD;
413 break;
414 }
415 }
416 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000417 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000418 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000419 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000420 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.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000461 return CXXDependentScopeMemberExpr::Create(
462 Context, BaseExpr, BaseType, IsArrow, OpLoc,
463 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
464 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000465}
466
467/// We know that the given qualified member reference points only to
468/// declarations which do not belong to the static type of the base
469/// expression. Diagnose the problem.
470static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
471 Expr *BaseExpr,
472 QualType BaseType,
473 const CXXScopeSpec &SS,
474 NamedDecl *rep,
475 const DeclarationNameInfo &nameInfo) {
476 // If this is an implicit member access, use a different set of
477 // diagnostics.
478 if (!BaseExpr)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000479 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000480
481 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
482 << SS.getRange() << rep << BaseType;
483}
484
485// Check whether the declarations we found through a nested-name
486// specifier in a member expression are actually members of the base
487// type. The restriction here is:
488//
489// C++ [expr.ref]p2:
490// ... In these cases, the id-expression shall name a
491// member of the class or of one of its base classes.
492//
493// So it's perfectly legitimate for the nested-name specifier to name
494// an unrelated class, and for us to find an overload set including
495// decls from classes which are not superclasses, as long as the decl
496// we actually pick through overload resolution is from a superclass.
497bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
498 QualType BaseType,
499 const CXXScopeSpec &SS,
500 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000501 CXXRecordDecl *BaseRecord =
502 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
503 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000504 // We can't check this yet because the base type is still
505 // dependent.
506 assert(BaseType->isDependentType());
507 return false;
508 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000509
510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
511 // If this is an implicit member reference and we find a
512 // non-instance member, it's not an error.
513 if (!BaseExpr && !(*I)->isCXXInstanceMember())
514 return false;
515
516 // Note that we use the DC of the decl, not the underlying decl.
517 DeclContext *DC = (*I)->getDeclContext();
518 while (DC->isTransparentContext())
519 DC = DC->getParent();
520
521 if (!DC->isRecord())
522 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000523
Richard Smithd80b2d52012-11-22 00:24:47 +0000524 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
525 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
526 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000527 return false;
528 }
529
530 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
531 R.getRepresentativeDecl(),
532 R.getLookupNameInfo());
533 return true;
534}
535
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000536namespace {
537
538// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000539// FunctionTemplateDecl and are declared in the current record or, for a C++
540// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000541class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000542public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000543 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000544 : Record(RTy->getDecl()) {
545 // Don't add bare keywords to the consumer since they will always fail
546 // validation by virtue of not being associated with any decls.
547 WantTypeSpecifiers = false;
548 WantExpressionKeywords = false;
549 WantCXXNamedCasts = false;
550 WantFunctionLikeCasts = false;
551 WantRemainingKeywords = false;
552 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000553
Craig Toppere14c0f82014-03-12 04:55:44 +0000554 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000555 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000556 // Don't accept candidates that cannot be member functions, constants,
557 // variables, or templates.
558 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
559 return false;
560
561 // Accept candidates that occur in the current record.
562 if (Record->containsDecl(ND))
563 return true;
564
565 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
566 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000567 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000568 if (const RecordType *BSTy =
569 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000570 if (BSTy->getDecl()->containsDecl(ND))
571 return true;
572 }
573 }
574 }
575
576 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000577 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000578
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000579private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000580 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000581};
582
583}
584
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000585static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000586 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000587 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000588 SourceLocation OpLoc, bool IsArrow,
589 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000590 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000591 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000592 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000593 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
594 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000595 diag::err_typecheck_incomplete_tag,
596 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000597 return true;
598
599 if (HasTemplateArgs) {
600 // LookupTemplateName doesn't expect these both to exist simultaneously.
601 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
602
603 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000604 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000605 return false;
606 }
607
608 DeclContext *DC = RDecl;
609 if (SS.isSet()) {
610 // If the member name was a qualified-id, look into the
611 // nested-name-specifier.
612 DC = SemaRef.computeDeclContext(SS, false);
613
614 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
615 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000616 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000617 return true;
618 }
619
620 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
621
622 if (!isa<TypeDecl>(DC)) {
623 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000624 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000625 return true;
626 }
627 }
628
629 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000630 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000631
632 if (!R.empty())
633 return false;
634
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000635 DeclarationName Typo = R.getLookupName();
636 SourceLocation TypoLoc = R.getNameLoc();
637 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000638 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
639 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000640 [=, &SemaRef](const TypoCorrection &TC) {
641 if (TC) {
642 assert(!TC.isKeyword() &&
643 "Got a keyword as a correction for a member!");
644 bool DroppedSpecifier =
645 TC.WillReplaceSpecifier() &&
646 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
647 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
648 << Typo << DC << DroppedSpecifier
649 << SS.getRange());
650 } else {
651 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
652 }
653 },
654 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
655 R.clear(); // Ensure there's no decls lingering in the shared state.
656 R.suppressDiagnostics();
657 R.setLookupName(TC.getCorrection());
658 for (NamedDecl *ND : TC)
659 R.addDecl(ND);
660 R.resolveKind();
661 return SemaRef.BuildMemberReferenceExpr(
662 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
663 nullptr, R, nullptr);
664 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000665 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000666
667 return false;
668}
669
Richard Smitha0edd302014-05-31 00:18:32 +0000670static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
671 ExprResult &BaseExpr, bool &IsArrow,
672 SourceLocation OpLoc, CXXScopeSpec &SS,
673 Decl *ObjCImpDecl, bool HasTemplateArgs);
674
Douglas Gregor5476205b2011-06-23 00:49:38 +0000675ExprResult
676Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
677 SourceLocation OpLoc, bool IsArrow,
678 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000679 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000680 NamedDecl *FirstQualifierInScope,
681 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000682 const TemplateArgumentListInfo *TemplateArgs,
683 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000684 if (BaseType->isDependentType() ||
685 (SS.isSet() && isDependentScopeSpecifier(SS)))
686 return ActOnDependentMemberExpr(Base, BaseType,
687 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000688 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000689 NameInfo, TemplateArgs);
690
691 LookupResult R(*this, NameInfo, LookupMemberName);
692
693 // Implicit member accesses.
694 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000695 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000696 QualType RecordTy = BaseType;
697 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000698 if (LookupMemberExprInRecord(*this, R, nullptr,
699 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000700 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000701 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000702 if (TE)
703 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000704
705 // Explicit member accesses.
706 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000707 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000708 ExprResult Result = LookupMemberExpr(
709 *this, R, BaseResult, IsArrow, OpLoc, SS,
710 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
711 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000712
713 if (BaseResult.isInvalid())
714 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000715 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000716
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000717 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000718 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000719
720 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000721 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000722
723 // LookupMemberExpr can modify Base, and thus change BaseType
724 BaseType = Base->getType();
725 }
726
727 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000728 OpLoc, IsArrow, SS, TemplateKWLoc,
Richard Smitha0edd302014-05-31 00:18:32 +0000729 FirstQualifierInScope, R, TemplateArgs,
730 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000731}
732
733static ExprResult
734BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000735 SourceLocation OpLoc, const CXXScopeSpec &SS,
736 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000737 const DeclarationNameInfo &MemberNameInfo);
738
739ExprResult
740Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
741 SourceLocation loc,
742 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000743 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000744 Expr *baseObjectExpr,
745 SourceLocation opLoc) {
746 // First, build the expression that refers to the base object.
747
748 bool baseObjectIsPointer = false;
749 Qualifiers baseQuals;
750
751 // Case 1: the base of the indirect field is not a field.
752 VarDecl *baseVariable = indirectField->getVarDecl();
753 CXXScopeSpec EmptySS;
754 if (baseVariable) {
755 assert(baseVariable->getType()->isRecordType());
756
757 // In principle we could have a member access expression that
758 // accesses an anonymous struct/union that's a static member of
759 // the base object's class. However, under the current standard,
760 // static data members cannot be anonymous structs or unions.
761 // Supporting this is as easy as building a MemberExpr here.
762 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
763
764 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
765
766 ExprResult result
767 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
768 if (result.isInvalid()) return ExprError();
769
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000770 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000771 baseObjectIsPointer = false;
772 baseQuals = baseObjectExpr->getType().getQualifiers();
773
774 // Case 2: the base of the indirect field is a field and the user
775 // wrote a member expression.
776 } else if (baseObjectExpr) {
777 // The caller provided the base object expression. Determine
778 // whether its a pointer and whether it adds any qualifiers to the
779 // anonymous struct/union fields we're looking into.
780 QualType objectType = baseObjectExpr->getType();
781
782 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
783 baseObjectIsPointer = true;
784 objectType = ptr->getPointeeType();
785 } else {
786 baseObjectIsPointer = false;
787 }
788 baseQuals = objectType.getQualifiers();
789
790 // Case 3: the base of the indirect field is a field and we should
791 // build an implicit member access.
792 } else {
793 // We've found a member of an anonymous struct/union that is
794 // inside a non-anonymous struct/union, so in a well-formed
795 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000796 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000797 if (ThisTy.isNull()) {
798 Diag(loc, diag::err_invalid_member_use_in_static_method)
799 << indirectField->getDeclName();
800 return ExprError();
801 }
802
803 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000804 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000805 baseObjectExpr
806 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
807 baseObjectIsPointer = true;
808 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
809 }
810
811 // Build the implicit member references to the field of the
812 // anonymous struct/union.
813 Expr *result = baseObjectExpr;
814 IndirectFieldDecl::chain_iterator
815 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
816
817 // Build the first member access in the chain with full information.
818 if (!baseVariable) {
819 FieldDecl *field = cast<FieldDecl>(*FI);
820
Douglas Gregor5476205b2011-06-23 00:49:38 +0000821 // Make a nameInfo that properly uses the anonymous name.
822 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000823
Douglas Gregor5476205b2011-06-23 00:49:38 +0000824 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000825 SourceLocation(), EmptySS, field,
826 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000827 if (!result)
828 return ExprError();
829
Douglas Gregor5476205b2011-06-23 00:49:38 +0000830 // FIXME: check qualified member access
831 }
832
833 // In all cases, we should now skip the first declaration in the chain.
834 ++FI;
835
836 while (FI != FEnd) {
837 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000838
Douglas Gregor5476205b2011-06-23 00:49:38 +0000839 // FIXME: these are somewhat meaningless
840 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000841 DeclAccessPair fakeFoundDecl =
842 DeclAccessPair::make(field, field->getAccess());
843
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000844 result =
845 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
846 SourceLocation(), (FI == FEnd ? SS : EmptySS),
847 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000848 }
849
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000850 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000851}
852
John McCall5e77d762013-04-16 07:28:30 +0000853static ExprResult
854BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
855 const CXXScopeSpec &SS,
856 MSPropertyDecl *PD,
857 const DeclarationNameInfo &NameInfo) {
858 // Property names are always simple identifiers and therefore never
859 // require any interesting additional storage.
860 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
861 S.Context.PseudoObjectTy, VK_LValue,
862 SS.getWithLocInContext(S.Context),
863 NameInfo.getLoc());
864}
865
Douglas Gregor5476205b2011-06-23 00:49:38 +0000866/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000867static MemberExpr *BuildMemberExpr(
868 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
869 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
870 ValueDecl *Member, DeclAccessPair FoundDecl,
871 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
872 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000873 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000874 MemberExpr *E = MemberExpr::Create(
875 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
876 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000877 SemaRef.MarkMemberReferenced(E);
878 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000879}
880
881ExprResult
882Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
883 SourceLocation OpLoc, bool IsArrow,
884 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000885 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000886 NamedDecl *FirstQualifierInScope,
887 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000888 const TemplateArgumentListInfo *TemplateArgs,
889 bool SuppressQualifierCheck,
890 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000891 QualType BaseType = BaseExprType;
892 if (IsArrow) {
893 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000894 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000895 }
896 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000897
898 LambdaScopeInfo *const CurLSI = getCurLambda();
899 // If this is an implicit member reference and the overloaded
900 // name refers to both static and non-static member functions
901 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
902 // check if we should/can capture 'this'...
903 // Keep this example in mind:
904 // struct X {
905 // void f(int) { }
906 // static void f(double) { }
907 //
908 // int g() {
909 // auto L = [=](auto a) {
910 // return [](int i) {
911 // return [=](auto b) {
912 // f(b);
913 // //f(decltype(a){});
914 // };
915 // };
916 // };
917 // auto M = L(0.0);
918 // auto N = M(3);
919 // N(5.32); // OK, must not error.
920 // return 0;
921 // }
922 // };
923 //
924 if (!BaseExpr && CurLSI) {
925 SourceLocation Loc = R.getNameLoc();
926 if (SS.getRange().isValid())
927 Loc = SS.getRange().getBegin();
928 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
929 // If the enclosing function is not dependent, then this lambda is
930 // capture ready, so if we can capture this, do so.
931 if (!EnclosingFunctionCtx->isDependentContext()) {
932 // If the current lambda and all enclosing lambdas can capture 'this' -
933 // then go ahead and capture 'this' (since our unresolved overload set
934 // contains both static and non-static member functions).
935 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
936 CheckCXXThisCapture(Loc);
937 } else if (CurContext->isDependentContext()) {
938 // ... since this is an implicit member reference, that might potentially
939 // involve a 'this' capture, mark 'this' for potential capture in
940 // enclosing lambdas.
941 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
942 CurLSI->addPotentialThisCapture(Loc);
943 }
944 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000945 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
946 DeclarationName MemberName = MemberNameInfo.getName();
947 SourceLocation MemberLoc = MemberNameInfo.getLoc();
948
949 if (R.isAmbiguous())
950 return ExprError();
951
952 if (R.empty()) {
953 // Rederive where we looked up.
954 DeclContext *DC = (SS.isSet()
955 ? computeDeclContext(SS, false)
956 : BaseType->getAs<RecordType>()->getDecl());
957
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000958 if (ExtraArgs) {
959 ExprResult RetryExpr;
960 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000961 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000962 ParsedType ObjectType;
963 bool MayBePseudoDestructor = false;
964 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
965 OpLoc, tok::arrow, ObjectType,
966 MayBePseudoDestructor);
967 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
968 CXXScopeSpec TempSS(SS);
969 RetryExpr = ActOnMemberAccessExpr(
970 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +0000971 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000972 }
973 if (Trap.hasErrorOccurred())
974 RetryExpr = ExprError();
975 }
976 if (RetryExpr.isUsable()) {
977 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
978 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
979 return RetryExpr;
980 }
981 }
982
Douglas Gregor5476205b2011-06-23 00:49:38 +0000983 Diag(R.getNameLoc(), diag::err_no_member)
984 << MemberName << DC
985 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
986 return ExprError();
987 }
988
989 // Diagnose lookups that find only declarations from a non-base
990 // type. This is possible for either qualified lookups (which may
991 // have been qualified with an unrelated type) or implicit member
992 // expressions (which were found with unqualified lookup and thus
993 // may have come from an enclosing scope). Note that it's okay for
994 // lookup to find declarations from a non-base type as long as those
995 // aren't the ones picked by overload resolution.
996 if ((SS.isSet() || !BaseExpr ||
997 (isa<CXXThisExpr>(BaseExpr) &&
998 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
999 !SuppressQualifierCheck &&
1000 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1001 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001002
Douglas Gregor5476205b2011-06-23 00:49:38 +00001003 // Construct an unresolved result if we in fact got an unresolved
1004 // result.
1005 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1006 // Suppress any lookup-related diagnostics; we'll do these when we
1007 // pick a member.
1008 R.suppressDiagnostics();
1009
1010 UnresolvedMemberExpr *MemExpr
1011 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1012 BaseExpr, BaseExprType,
1013 IsArrow, OpLoc,
1014 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001015 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001016 TemplateArgs, R.begin(), R.end());
1017
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001018 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001019 }
1020
1021 assert(R.isSingleResult());
1022 DeclAccessPair FoundDecl = R.begin().getPair();
1023 NamedDecl *MemberDecl = R.getFoundDecl();
1024
1025 // FIXME: diagnose the presence of template arguments now.
1026
1027 // If the decl being referenced had an error, return an error for this
1028 // sub-expr without emitting another error, in order to avoid cascading
1029 // error cases.
1030 if (MemberDecl->isInvalidDecl())
1031 return ExprError();
1032
1033 // Handle the implicit-member-access case.
1034 if (!BaseExpr) {
1035 // If this is not an instance member, convert to a non-member access.
1036 if (!MemberDecl->isCXXInstanceMember())
1037 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1038
1039 SourceLocation Loc = R.getNameLoc();
1040 if (SS.getRange().isValid())
1041 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001042 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001043 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1044 }
1045
1046 bool ShouldCheckUse = true;
1047 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1048 // Don't diagnose the use of a virtual member function unless it's
1049 // explicitly qualified.
1050 if (MD->isVirtual() && !SS.isSet())
1051 ShouldCheckUse = false;
1052 }
1053
1054 // Check the use of this member.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001055 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001056 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001057
Douglas Gregor5476205b2011-06-23 00:49:38 +00001058 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001059 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1060 FoundDecl, MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001061
John McCall5e77d762013-04-16 07:28:30 +00001062 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1063 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1064 MemberNameInfo);
1065
Douglas Gregor5476205b2011-06-23 00:49:38 +00001066 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1067 // We may have found a field within an anonymous union or struct
1068 // (C++ [class.union]).
1069 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001070 FoundDecl, BaseExpr,
1071 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001072
1073 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001074 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1075 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001076 Var->getType().getNonReferenceType(), VK_LValue,
1077 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001078 }
1079
1080 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1081 ExprValueKind valueKind;
1082 QualType type;
1083 if (MemberFn->isInstance()) {
1084 valueKind = VK_RValue;
1085 type = Context.BoundMemberTy;
1086 } else {
1087 valueKind = VK_LValue;
1088 type = MemberFn->getType();
1089 }
1090
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001091 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1092 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1093 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001094 }
1095 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1096
1097 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001098 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1099 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1100 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001101 }
1102
Douglas Gregor5476205b2011-06-23 00:49:38 +00001103 // We found something that we didn't expect. Complain.
1104 if (isa<TypeDecl>(MemberDecl))
1105 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1106 << MemberName << BaseType << int(IsArrow);
1107 else
1108 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1109 << MemberName << BaseType << int(IsArrow);
1110
1111 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1112 << MemberName;
1113 R.suppressDiagnostics();
1114 return ExprError();
1115}
1116
1117/// Given that normal member access failed on the given expression,
1118/// and given that the expression's type involves builtin-id or
1119/// builtin-Class, decide whether substituting in the redefinition
1120/// types would be profitable. The redefinition type is whatever
1121/// this translation unit tried to typedef to id/Class; we store
1122/// it to the side and then re-use it in places like this.
1123static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1124 const ObjCObjectPointerType *opty
1125 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1126 if (!opty) return false;
1127
1128 const ObjCObjectType *ty = opty->getObjectType();
1129
1130 QualType redef;
1131 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001132 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001133 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001134 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001135 } else {
1136 return false;
1137 }
1138
1139 // Do the substitution as long as the redefinition type isn't just a
1140 // possibly-qualified pointer to builtin-id or builtin-Class again.
1141 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001142 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001143 return false;
1144
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001145 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001146 return true;
1147}
1148
John McCall50a2c2c2011-10-11 23:14:30 +00001149static bool isRecordType(QualType T) {
1150 return T->isRecordType();
1151}
1152static bool isPointerToRecordType(QualType T) {
1153 if (const PointerType *PT = T->getAs<PointerType>())
1154 return PT->getPointeeType()->isRecordType();
1155 return false;
1156}
1157
Richard Smithcab9a7d2011-10-26 19:06:56 +00001158/// Perform conversions on the LHS of a member access expression.
1159ExprResult
1160Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001161 if (IsArrow && !Base->getType()->isFunctionType())
1162 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001163
Eli Friedman9a766c42012-01-13 02:20:01 +00001164 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001165}
1166
Douglas Gregor5476205b2011-06-23 00:49:38 +00001167/// Look up the given member of the given non-type-dependent
1168/// expression. This can return in one of two ways:
1169/// * If it returns a sentinel null-but-valid result, the caller will
1170/// assume that lookup was performed and the results written into
1171/// the provided structure. It will take over from there.
1172/// * Otherwise, the returned expression will be produced in place of
1173/// an ordinary member expression.
1174///
1175/// The ObjCImpDecl bit is a gross hack that will need to be properly
1176/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001177static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1178 ExprResult &BaseExpr, bool &IsArrow,
1179 SourceLocation OpLoc, CXXScopeSpec &SS,
1180 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001181 assert(BaseExpr.get() && "no base expression");
1182
1183 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001184 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001185 if (BaseExpr.isInvalid())
1186 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001187
Douglas Gregor5476205b2011-06-23 00:49:38 +00001188 QualType BaseType = BaseExpr.get()->getType();
1189 assert(!BaseType->isDependentType());
1190
1191 DeclarationName MemberName = R.getLookupName();
1192 SourceLocation MemberLoc = R.getNameLoc();
1193
1194 // For later type-checking purposes, turn arrow accesses into dot
1195 // accesses. The only access type we support that doesn't follow
1196 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1197 // and those never use arrows, so this is unaffected.
1198 if (IsArrow) {
1199 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1200 BaseType = Ptr->getPointeeType();
1201 else if (const ObjCObjectPointerType *Ptr
1202 = BaseType->getAs<ObjCObjectPointerType>())
1203 BaseType = Ptr->getPointeeType();
1204 else if (BaseType->isRecordType()) {
1205 // Recover from arrow accesses to records, e.g.:
1206 // struct MyRecord foo;
1207 // foo->bar
1208 // This is actually well-formed in C++ if MyRecord has an
1209 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001210 // by now--or a diagnostic message already issued if a problem
1211 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001212 if (!S.getLangOpts().CPlusPlus) {
1213 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001214 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1215 << FixItHint::CreateReplacement(OpLoc, ".");
1216 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001217 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001218 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001219 goto fail;
1220 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001221 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001222 << BaseType << BaseExpr.get()->getSourceRange();
1223 return ExprError();
1224 }
1225 }
1226
1227 // Handle field access to simple records.
1228 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001229 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001230 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001231 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001232 return ExprError();
1233
1234 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001235 // the lookup result was filled in. If typo correction was attempted and
1236 // failed, the lookup result will have been cleared--that combined with the
1237 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1238 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001239 }
1240
1241 // Handle ivar access to Objective-C objects.
1242 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001243 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001244 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001245 << 1 << SS.getScopeRep()
1246 << FixItHint::CreateRemoval(SS.getRange());
1247 SS.clear();
1248 }
Richard Smitha0edd302014-05-31 00:18:32 +00001249
Douglas Gregor5476205b2011-06-23 00:49:38 +00001250 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1251
1252 // There are three cases for the base type:
1253 // - builtin id (qualified or unqualified)
1254 // - builtin Class (qualified or unqualified)
1255 // - an interface
1256 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1257 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001258 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001259 (OTy->isObjCId() || OTy->isObjCClass()))
1260 goto fail;
1261 // There's an implicit 'isa' ivar on all objects.
1262 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001263 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001264 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001265 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1266 OpLoc, S.Context.getObjCClassType());
1267 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1268 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001269 ObjCImpDecl, HasTemplateArgs);
1270 goto fail;
1271 }
Richard Smitha0edd302014-05-31 00:18:32 +00001272
1273 if (S.RequireCompleteType(OpLoc, BaseType,
1274 diag::err_typecheck_incomplete_tag,
1275 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001276 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001277
1278 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001279 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1280
1281 if (!IV) {
1282 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001283 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1284 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001285 if (TypoCorrection Corrected = S.CorrectTypo(
1286 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001287 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001288 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001289 S.diagnoseTypo(
1290 Corrected,
1291 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1292 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001293
Ted Kremenek679b4782012-03-17 00:53:39 +00001294 // Figure out the class that declares the ivar.
1295 assert(!ClassDeclared);
1296 Decl *D = cast<Decl>(IV->getDeclContext());
1297 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1298 D = CAT->getClassInterface();
1299 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001300 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001301 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001302 S.Diag(MemberLoc, diag::err_property_found_suggest)
1303 << Member << BaseExpr.get()->getType()
1304 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001305 return ExprError();
1306 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001307
Richard Smitha0edd302014-05-31 00:18:32 +00001308 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1309 << IDecl->getDeclName() << MemberName
1310 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001311 return ExprError();
1312 }
1313 }
Richard Smitha0edd302014-05-31 00:18:32 +00001314
Ted Kremenek679b4782012-03-17 00:53:39 +00001315 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001316
1317 // If the decl being referenced had an error, return an error for this
1318 // sub-expr without emitting another error, in order to avoid cascading
1319 // error cases.
1320 if (IV->isInvalidDecl())
1321 return ExprError();
1322
1323 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001324 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001325 return ExprError();
1326 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1327 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001328 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001329 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001330 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001331 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001332 // Case of a c-function declared inside an objc implementation.
1333 // FIXME: For a c-style function nested inside an objc implementation
1334 // class, there is no implementation context available, so we pass
1335 // down the context as argument to this routine. Ideally, this context
1336 // need be passed down in the AST node and somehow calculated from the
1337 // AST for a function decl.
1338 if (ObjCImplementationDecl *IMPD =
1339 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1340 ClassOfMethodDecl = IMPD->getClassInterface();
1341 else if (ObjCCategoryImplDecl* CatImplClass =
1342 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1343 ClassOfMethodDecl = CatImplClass->getClassInterface();
1344 }
Richard Smitha0edd302014-05-31 00:18:32 +00001345 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001346 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1347 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1348 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001349 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001350 << IV->getDeclName();
1351 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1352 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001353 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1354 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001355 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001356 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001357 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001358 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001359 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1360 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1361 if (UO->getOpcode() == UO_Deref)
1362 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1363
1364 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001365 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001366 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001367 warn = false;
1368 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001369 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001370 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001371 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001372 ObjCMethodFamily MF = MD->getMethodFamily();
1373 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001374 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001375 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001376 }
1377 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001378 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001379 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001380
Richard Smitha0edd302014-05-31 00:18:32 +00001381 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1382 IV, IV->getType(), MemberLoc, OpLoc, BaseExpr.get(), IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001383
Richard Smitha0edd302014-05-31 00:18:32 +00001384 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001385 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001386 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001387 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001388 }
1389 }
1390
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001391 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001392 }
1393
1394 // Objective-C property access.
1395 const ObjCObjectPointerType *OPT;
1396 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001397 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001398 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1399 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001400 SS.clear();
1401 }
1402
Douglas Gregor5476205b2011-06-23 00:49:38 +00001403 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001404 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001405 if (BaseExpr.isInvalid())
1406 return ExprError();
1407
Richard Smitha0edd302014-05-31 00:18:32 +00001408 assert(S.Context.hasSameUnqualifiedType(BaseType,
1409 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001410
1411 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1412
1413 const ObjCObjectType *OT = OPT->getObjectType();
1414
1415 // id, with and without qualifiers.
1416 if (OT->isObjCId()) {
1417 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001418 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1419 if (Decl *PMDecl =
1420 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001421 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1422 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001423 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001424 return ExprError();
1425
Richard Smitha0edd302014-05-31 00:18:32 +00001426 return new (S.Context)
1427 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001428 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001429 }
1430
1431 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1432 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001433 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001434 return ExprError();
1435 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001436 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1437 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001438 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001439 ObjCMethodDecl *SMD = nullptr;
1440 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001441 /*Property id*/ nullptr,
1442 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001443 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001444
1445 return new (S.Context)
1446 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001447 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001448 }
1449 }
1450 // Use of id.member can only be for a property reference. Do not
1451 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001452 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1453 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001454 ObjCImpDecl, HasTemplateArgs);
1455
Richard Smitha0edd302014-05-31 00:18:32 +00001456 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001457 << MemberName << BaseType);
1458 }
1459
1460 // 'Class', unqualified only.
1461 if (OT->isObjCClass()) {
1462 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001463 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001464 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001465 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1466 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001467 ObjCImpDecl, HasTemplateArgs);
1468
1469 goto fail;
1470 }
1471
1472 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001473 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001474 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1475 ObjCMethodDecl *Getter;
1476 if ((Getter = IFace->lookupClassMethod(Sel))) {
1477 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001478 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001479 return ExprError();
1480 } else
1481 Getter = IFace->lookupPrivateMethod(Sel, false);
1482 // If we found a getter then this may be a valid dot-reference, we
1483 // will look for the matching setter, in case it is needed.
1484 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001485 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1486 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001487 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001488 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1489 if (!Setter) {
1490 // If this reference is in an @implementation, also check for 'private'
1491 // methods.
1492 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1493 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001494
Richard Smitha0edd302014-05-31 00:18:32 +00001495 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001496 return ExprError();
1497
1498 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001499 return new (S.Context) ObjCPropertyRefExpr(
1500 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1501 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001502 }
1503
Richard Smitha0edd302014-05-31 00:18:32 +00001504 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1505 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001506 ObjCImpDecl, HasTemplateArgs);
1507
Richard Smitha0edd302014-05-31 00:18:32 +00001508 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001509 << MemberName << BaseType);
1510 }
1511
1512 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001513 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1514 MemberLoc, SourceLocation(), QualType(),
1515 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001516 }
1517
1518 // Handle 'field access' to vectors, such as 'V.xx'.
1519 if (BaseType->isExtVectorType()) {
1520 // FIXME: this expr should store IsArrow.
1521 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1522 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
Richard Smitha0edd302014-05-31 00:18:32 +00001523 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001524 Member, MemberLoc);
1525 if (ret.isNull())
1526 return ExprError();
1527
Richard Smitha0edd302014-05-31 00:18:32 +00001528 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001529 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001530 }
1531
1532 // Adjust builtin-sel to the appropriate redefinition type if that's
1533 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001534 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1535 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1536 BaseExpr = S.ImpCastExprToType(
1537 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1538 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001539 ObjCImpDecl, HasTemplateArgs);
1540 }
1541
1542 // Failure cases.
1543 fail:
1544
1545 // Recover from dot accesses to pointers, e.g.:
1546 // type *foo;
1547 // foo.bar
1548 // This is actually well-formed in two cases:
1549 // - 'type' is an Objective C type
1550 // - 'bar' is a pseudo-destructor name which happens to refer to
1551 // the appropriate pointer type
1552 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1553 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1554 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001555 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1556 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001557 << FixItHint::CreateReplacement(OpLoc, "->");
1558
1559 // Recurse as an -> access.
1560 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001561 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001562 ObjCImpDecl, HasTemplateArgs);
1563 }
1564 }
1565
1566 // If the user is trying to apply -> or . to a function name, it's probably
1567 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001568 if (S.tryToRecoverWithCall(
1569 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1570 /*complain*/ false,
1571 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001572 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001573 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001574 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1575 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001576 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001577 }
1578
Richard Smitha0edd302014-05-31 00:18:32 +00001579 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001580 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001581
1582 return ExprError();
1583}
1584
1585/// The main callback when the parser finds something like
1586/// expression . [nested-name-specifier] identifier
1587/// expression -> [nested-name-specifier] identifier
1588/// where 'identifier' encompasses a fairly broad spectrum of
1589/// possibilities, including destructor and operator references.
1590///
1591/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001592/// \param ObjCImpDecl the current Objective-C \@implementation
1593/// decl; this is an ugly hack around the fact that Objective-C
1594/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001595ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1596 SourceLocation OpLoc,
1597 tok::TokenKind OpKind,
1598 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001599 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001600 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001601 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001602 if (SS.isSet() && SS.isInvalid())
1603 return ExprError();
1604
1605 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001606 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001607 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1608 Diag(Id.getSourceRange().getBegin(),
1609 diag::ext_ms_explicit_constructor_call);
1610
1611 TemplateArgumentListInfo TemplateArgsBuffer;
1612
1613 // Decompose the name into its component parts.
1614 DeclarationNameInfo NameInfo;
1615 const TemplateArgumentListInfo *TemplateArgs;
1616 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1617 NameInfo, TemplateArgs);
1618
1619 DeclarationName Name = NameInfo.getName();
1620 bool IsArrow = (OpKind == tok::arrow);
1621
1622 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001623 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001624
1625 // This is a postfix expression, so get rid of ParenListExprs.
1626 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1627 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001628 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001629
1630 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1631 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001632 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1633 TemplateKWLoc, FirstQualifierInScope,
1634 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001635 }
1636
David Majnemerced8bdf2015-02-25 17:36:15 +00001637 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001638 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1639 TemplateKWLoc, FirstQualifierInScope,
1640 NameInfo, TemplateArgs, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001641}
1642
1643static ExprResult
1644BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001645 SourceLocation OpLoc, const CXXScopeSpec &SS,
1646 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001647 const DeclarationNameInfo &MemberNameInfo) {
1648 // x.a is an l-value if 'a' has a reference type. Otherwise:
1649 // x.a is an l-value/x-value/pr-value if the base is (and note
1650 // that *x is always an l-value), except that if the base isn't
1651 // an ordinary object then we must have an rvalue.
1652 ExprValueKind VK = VK_LValue;
1653 ExprObjectKind OK = OK_Ordinary;
1654 if (!IsArrow) {
1655 if (BaseExpr->getObjectKind() == OK_Ordinary)
1656 VK = BaseExpr->getValueKind();
1657 else
1658 VK = VK_RValue;
1659 }
1660 if (VK != VK_RValue && Field->isBitField())
1661 OK = OK_BitField;
1662
1663 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1664 QualType MemberType = Field->getType();
1665 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1666 MemberType = Ref->getPointeeType();
1667 VK = VK_LValue;
1668 } else {
1669 QualType BaseType = BaseExpr->getType();
1670 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001671
Douglas Gregor5476205b2011-06-23 00:49:38 +00001672 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001673
Douglas Gregor5476205b2011-06-23 00:49:38 +00001674 // GC attributes are never picked up by members.
1675 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001676
Douglas Gregor5476205b2011-06-23 00:49:38 +00001677 // CVR attributes from the base are picked up by members,
1678 // except that 'mutable' members don't pick up 'const'.
1679 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001680
Douglas Gregor5476205b2011-06-23 00:49:38 +00001681 Qualifiers MemberQuals
1682 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001683
Douglas Gregor5476205b2011-06-23 00:49:38 +00001684 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001685
1686
Douglas Gregor5476205b2011-06-23 00:49:38 +00001687 Qualifiers Combined = BaseQuals + MemberQuals;
1688 if (Combined != MemberQuals)
1689 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1690 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001691
Daniel Jasper0baec5492012-06-06 08:32:04 +00001692 S.UnusedPrivateFields.remove(Field);
1693
Douglas Gregor5476205b2011-06-23 00:49:38 +00001694 ExprResult Base =
1695 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1696 FoundDecl, Field);
1697 if (Base.isInvalid())
1698 return ExprError();
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001699 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001700 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1701 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001702}
1703
1704/// Builds an implicit member access expression. The current context
1705/// is known to be an instance method, and the given unqualified lookup
1706/// set is known to contain only instance members, at least one of which
1707/// is from an appropriate type.
1708ExprResult
1709Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001710 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001711 LookupResult &R,
1712 const TemplateArgumentListInfo *TemplateArgs,
1713 bool IsKnownInstance) {
1714 assert(!R.empty() && !R.isAmbiguous());
1715
1716 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001717
Douglas Gregor5476205b2011-06-23 00:49:38 +00001718 // If this is known to be an instance access, go ahead and build an
1719 // implicit 'this' expression now.
1720 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001721 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001722 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001723
1724 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001725 if (IsKnownInstance) {
1726 SourceLocation Loc = R.getNameLoc();
1727 if (SS.getRange().isValid())
1728 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001729 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001730 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1731 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001732
Douglas Gregor5476205b2011-06-23 00:49:38 +00001733 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1734 /*OpLoc*/ SourceLocation(),
1735 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001736 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001737 /*FirstQualifierInScope*/ nullptr,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001738 R, TemplateArgs);
1739}