blob: afeabf5d913a9a5cb4de89b6437b87ff7f6d0034 [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;
Richard Smithd80b2d52012-11-22 00:24:47 +000030
Douglas Gregor5476205b2011-06-23 00:49:38 +000031/// Determines if the given class is provably not derived from all of
32/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000033static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
34 const BaseSet &Bases) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +000035 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
36 return !Bases.count(Base->getCanonicalDecl());
37 };
38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
Douglas Gregor5476205b2011-06-23 00:49:38 +000039}
40
41enum IMAKind {
42 /// The reference is definitely not an instance member access.
43 IMA_Static,
44
45 /// The reference may be an implicit instance member access.
46 IMA_Mixed,
47
Eli Friedman7bda7f72012-01-18 03:53:45 +000048 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000049 /// so, because the context is not an instance method.
50 IMA_Mixed_StaticContext,
51
52 /// The reference may be to an instance member, but it is invalid if
53 /// so, because the context is from an unrelated class.
54 IMA_Mixed_Unrelated,
55
56 /// The reference is definitely an implicit instance member access.
57 IMA_Instance,
58
59 /// The reference may be to an unresolved using declaration.
60 IMA_Unresolved,
61
John McCallf413f5e2013-05-03 00:10:13 +000062 /// The reference is a contextually-permitted abstract member reference.
63 IMA_Abstract,
64
Douglas Gregor5476205b2011-06-23 00:49:38 +000065 /// The reference may be to an unresolved using declaration and the
66 /// context is not an instance method.
67 IMA_Unresolved_StaticContext,
68
Eli Friedman456f0182012-01-20 01:26:23 +000069 // The reference refers to a field which is not a member of the containing
70 // class, which is allowed because we're in C++11 mode and the context is
71 // unevaluated.
72 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000073
Douglas Gregor5476205b2011-06-23 00:49:38 +000074 /// All possible referrents are instance members and the current
75 /// context is not an instance method.
76 IMA_Error_StaticContext,
77
78 /// All possible referrents are instance members of an unrelated
79 /// class.
80 IMA_Error_Unrelated
81};
82
83/// The given lookup names class member(s) and is not being used for
84/// an address-of-member expression. Classify the type of access
85/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000086/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000087/// conservatively answer "yes", in which case some errors will simply
88/// not be caught until template-instantiation.
89static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +000090 const LookupResult &R) {
91 assert(!R.empty() && (*R.begin())->isCXXClassMember());
92
93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
94
Douglas Gregor3024f072012-04-16 07:05:22 +000095 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +000097
98 if (R.isUnresolvableResult())
99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
100
101 // Collect all the declaring classes of instance members we find.
102 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000103 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000104 BaseSet Classes;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000105 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
106 NamedDecl *D = *I;
107
108 if (D->isCXXInstanceMember()) {
Benjamin Kramera008d3a2015-04-10 11:37:55 +0000109 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
110 isa<IndirectFieldDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000111
112 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
113 Classes.insert(R->getCanonicalDecl());
114 }
115 else
116 hasNonInstance = true;
117 }
118
119 // If we didn't find any instance members, it can't be an implicit
120 // member reference.
121 if (Classes.empty())
122 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000123
124 // C++11 [expr.prim.general]p12:
125 // An id-expression that denotes a non-static data member or non-static
126 // member function of a class can only be used:
127 // (...)
128 // - if that id-expression denotes a non-static data member and it
129 // appears in an unevaluated operand.
130 //
131 // This rule is specific to C++11. However, we also permit this form
132 // in unevaluated inline assembly operands, like the operand to a SIZE.
133 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
134 assert(!AbstractInstanceResult);
135 switch (SemaRef.ExprEvalContexts.back().Context) {
136 case Sema::Unevaluated:
137 if (isField && SemaRef.getLangOpts().CPlusPlus11)
138 AbstractInstanceResult = IMA_Field_Uneval_Context;
139 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000140
John McCallf413f5e2013-05-03 00:10:13 +0000141 case Sema::UnevaluatedAbstract:
142 AbstractInstanceResult = IMA_Abstract;
143 break;
144
145 case Sema::ConstantEvaluated:
146 case Sema::PotentiallyEvaluated:
147 case Sema::PotentiallyEvaluatedIfUsed:
148 break;
Richard Smitheae99682012-02-25 10:04:07 +0000149 }
150
Douglas Gregor5476205b2011-06-23 00:49:38 +0000151 // If the current context is not an instance method, it can't be
152 // an implicit member reference.
153 if (isStaticContext) {
154 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000155 return IMA_Mixed_StaticContext;
156
John McCallf413f5e2013-05-03 00:10:13 +0000157 return AbstractInstanceResult ? AbstractInstanceResult
158 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000159 }
160
161 CXXRecordDecl *contextClass;
162 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
163 contextClass = MD->getParent()->getCanonicalDecl();
164 else
165 contextClass = cast<CXXRecordDecl>(DC);
166
167 // [class.mfct.non-static]p3:
168 // ...is used in the body of a non-static member function of class X,
169 // if name lookup (3.4.1) resolves the name in the id-expression to a
170 // non-static non-type member of some class C [...]
171 // ...if C is not X or a base class of X, the class member access expression
172 // is ill-formed.
173 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000174 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000175 R.getNamingClass()->getCanonicalDecl()) {
176 // If the naming class is not the current context, this was a qualified
177 // member name lookup, and it's sufficient to check that we have the naming
178 // class as a base class.
179 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000180 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000181 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000182
183 // If we can prove that the current context is unrelated to all the
184 // declaring classes, it can't be an implicit member reference (in
185 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000186 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000187 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000188 AbstractInstanceResult ? AbstractInstanceResult :
189 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000190
191 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
192}
193
194/// Diagnose a reference to a field with no object available.
Richard Smithfa0a1f52012-04-05 01:13:04 +0000195static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000196 const CXXScopeSpec &SS,
Richard Smithfa0a1f52012-04-05 01:13:04 +0000197 NamedDecl *Rep,
Eli Friedman456f0182012-01-20 01:26:23 +0000198 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000199 SourceLocation Loc = nameInfo.getLoc();
200 SourceRange Range(Loc);
201 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000202
Reid Klecknerae628962014-12-18 00:42:51 +0000203 // Look through using shadow decls and aliases.
204 Rep = Rep->getUnderlyingDecl();
205
Richard Smithfa0a1f52012-04-05 01:13:04 +0000206 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
207 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000208 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000209 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
210
211 bool InStaticMethod = Method && Method->isStatic();
212 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
213
214 if (IsField && InStaticMethod)
215 // "invalid use of member 'x' in static member function"
216 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
217 << Range << nameInfo.getName();
218 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
219 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
220 // Unqualified lookup in a non-static member function found a member of an
221 // enclosing class.
222 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
223 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
224 else if (IsField)
Eli Friedman456f0182012-01-20 01:26:23 +0000225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000226 << nameInfo.getName() << Range;
227 else
228 SemaRef.Diag(Loc, diag::err_member_call_without_object)
229 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000230}
231
232/// Builds an expression which might be an implicit member expression.
233ExprResult
234Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000235 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000236 LookupResult &R,
237 const TemplateArgumentListInfo *TemplateArgs) {
Reid Klecknerae628962014-12-18 00:42:51 +0000238 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000239 case IMA_Instance:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000240 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000241
242 case IMA_Mixed:
243 case IMA_Mixed_Unrelated:
244 case IMA_Unresolved:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000245 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000246
Richard Smith2a986112012-02-25 10:20:59 +0000247 case IMA_Field_Uneval_Context:
248 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
249 << R.getLookupNameInfo().getName();
250 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000251 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000252 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000253 case IMA_Mixed_StaticContext:
254 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000255 if (TemplateArgs || TemplateKWLoc.isValid())
256 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000257 return BuildDeclarationNameExpr(SS, R, false);
258
259 case IMA_Error_StaticContext:
260 case IMA_Error_Unrelated:
Richard Smithfa0a1f52012-04-05 01:13:04 +0000261 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000262 R.getLookupNameInfo());
263 return ExprError();
264 }
265
266 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000267}
268
269/// Check an ext-vector component access expression.
270///
271/// VK should be set in advance to the value kind of the base
272/// expression.
273static QualType
274CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
275 SourceLocation OpLoc, const IdentifierInfo *CompName,
276 SourceLocation CompLoc) {
277 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
278 // see FIXME there.
279 //
280 // FIXME: This logic can be greatly simplified by splitting it along
281 // halving/not halving and reworking the component checking.
282 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
283
284 // The vector accessor can't exceed the number of elements.
285 const char *compStr = CompName->getNameStart();
286
287 // This flag determines whether or not the component is one of the four
288 // special names that indicate a subset of exactly half the elements are
289 // to be selected.
290 bool HalvingSwizzle = false;
291
292 // This flag determines whether or not CompName has an 's' char prefix,
293 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000294 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000295
296 bool HasRepeated = false;
297 bool HasIndex[16] = {};
298
299 int Idx;
300
301 // Check that we've found one of the special components, or that the component
302 // names must come from the same set.
303 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
304 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
305 HalvingSwizzle = true;
306 } else if (!HexSwizzle &&
307 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
308 do {
309 if (HasIndex[Idx]) HasRepeated = true;
310 HasIndex[Idx] = true;
311 compStr++;
312 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
313 } else {
314 if (HexSwizzle) compStr++;
315 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
316 if (HasIndex[Idx]) HasRepeated = true;
317 HasIndex[Idx] = true;
318 compStr++;
319 }
320 }
321
322 if (!HalvingSwizzle && *compStr) {
323 // We didn't get to the end of the string. This means the component names
324 // didn't come from the same set *or* we encountered an illegal name.
325 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000326 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000327 return QualType();
328 }
329
330 // Ensure no component accessor exceeds the width of the vector type it
331 // operates on.
332 if (!HalvingSwizzle) {
333 compStr = CompName->getNameStart();
334
335 if (HexSwizzle)
336 compStr++;
337
338 while (*compStr) {
339 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
340 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
341 << baseType << SourceRange(CompLoc);
342 return QualType();
343 }
344 }
345 }
346
347 // The component accessor looks fine - now we need to compute the actual type.
348 // The vector type is implied by the component accessor. For example,
349 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
350 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
351 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
352 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
353 : CompName->getLength();
354 if (HexSwizzle)
355 CompSize--;
356
357 if (CompSize == 1)
358 return vecType->getElementType();
359
360 if (HasRepeated) VK = VK_RValue;
361
362 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
363 // Now look up the TypeDefDecl from the vector type. Without this,
364 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000365 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000366 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000367 E = S.ExtVectorDecls.end();
368 I != E; ++I) {
369 if ((*I)->getUnderlyingType() == VT)
370 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000371 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000372
Douglas Gregor5476205b2011-06-23 00:49:38 +0000373 return VT; // should never get here (a typedef type should always be found).
374}
375
376static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
377 IdentifierInfo *Member,
378 const Selector &Sel,
379 ASTContext &Context) {
380 if (Member)
381 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
382 return PD;
383 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
384 return OMD;
385
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000386 for (const auto *I : PDecl->protocols()) {
387 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000388 Context))
389 return D;
390 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000391 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000392}
393
394static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
395 IdentifierInfo *Member,
396 const Selector &Sel,
397 ASTContext &Context) {
398 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000399 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000400 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000401 if (Member)
Aaron Ballman83731462014-03-17 16:14:00 +0000402 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000403 GDecl = PD;
404 break;
405 }
406 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000407 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000408 GDecl = OMD;
409 break;
410 }
411 }
412 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000413 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000414 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000415 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000416 if (GDecl)
417 return GDecl;
418 }
419 }
420 return GDecl;
421}
422
423ExprResult
424Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
425 bool IsArrow, SourceLocation OpLoc,
426 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000427 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000428 NamedDecl *FirstQualifierInScope,
429 const DeclarationNameInfo &NameInfo,
430 const TemplateArgumentListInfo *TemplateArgs) {
431 // Even in dependent contexts, try to diagnose base expressions with
432 // obviously wrong types, e.g.:
433 //
434 // T* t;
435 // t.f;
436 //
437 // In Obj-C++, however, the above expression is valid, since it could be
438 // accessing the 'f' property if T is an Obj-C interface. The extra check
439 // allows this, while still reporting an error if T is a struct pointer.
440 if (!IsArrow) {
441 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000442 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000443 PT->getPointeeType()->isRecordType())) {
444 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000445 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000446 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000447 return ExprError();
448 }
449 }
450
451 assert(BaseType->isDependentType() ||
452 NameInfo.getName().isDependentName() ||
453 isDependentScopeSpecifier(SS));
454
455 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
456 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000457 return CXXDependentScopeMemberExpr::Create(
458 Context, BaseExpr, BaseType, IsArrow, OpLoc,
459 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
460 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000461}
462
463/// We know that the given qualified member reference points only to
464/// declarations which do not belong to the static type of the base
465/// expression. Diagnose the problem.
466static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
467 Expr *BaseExpr,
468 QualType BaseType,
469 const CXXScopeSpec &SS,
470 NamedDecl *rep,
471 const DeclarationNameInfo &nameInfo) {
472 // If this is an implicit member access, use a different set of
473 // diagnostics.
474 if (!BaseExpr)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000475 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000476
477 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
478 << SS.getRange() << rep << BaseType;
479}
480
481// Check whether the declarations we found through a nested-name
482// specifier in a member expression are actually members of the base
483// type. The restriction here is:
484//
485// C++ [expr.ref]p2:
486// ... In these cases, the id-expression shall name a
487// member of the class or of one of its base classes.
488//
489// So it's perfectly legitimate for the nested-name specifier to name
490// an unrelated class, and for us to find an overload set including
491// decls from classes which are not superclasses, as long as the decl
492// we actually pick through overload resolution is from a superclass.
493bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
494 QualType BaseType,
495 const CXXScopeSpec &SS,
496 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000497 CXXRecordDecl *BaseRecord =
498 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
499 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000500 // We can't check this yet because the base type is still
501 // dependent.
502 assert(BaseType->isDependentType());
503 return false;
504 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000505
506 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
507 // If this is an implicit member reference and we find a
508 // non-instance member, it's not an error.
509 if (!BaseExpr && !(*I)->isCXXInstanceMember())
510 return false;
511
512 // Note that we use the DC of the decl, not the underlying decl.
513 DeclContext *DC = (*I)->getDeclContext();
514 while (DC->isTransparentContext())
515 DC = DC->getParent();
516
517 if (!DC->isRecord())
518 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000519
Richard Smithd80b2d52012-11-22 00:24:47 +0000520 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
521 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
522 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000523 return false;
524 }
525
526 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
527 R.getRepresentativeDecl(),
528 R.getLookupNameInfo());
529 return true;
530}
531
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000532namespace {
533
534// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000535// FunctionTemplateDecl and are declared in the current record or, for a C++
536// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000537class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000538public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000539 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000540 : Record(RTy->getDecl()) {
541 // Don't add bare keywords to the consumer since they will always fail
542 // validation by virtue of not being associated with any decls.
543 WantTypeSpecifiers = false;
544 WantExpressionKeywords = false;
545 WantCXXNamedCasts = false;
546 WantFunctionLikeCasts = false;
547 WantRemainingKeywords = false;
548 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000549
Craig Toppere14c0f82014-03-12 04:55:44 +0000550 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000551 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000552 // Don't accept candidates that cannot be member functions, constants,
553 // variables, or templates.
554 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
555 return false;
556
557 // Accept candidates that occur in the current record.
558 if (Record->containsDecl(ND))
559 return true;
560
561 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
562 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000563 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000564 if (const RecordType *BSTy =
565 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000566 if (BSTy->getDecl()->containsDecl(ND))
567 return true;
568 }
569 }
570 }
571
572 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000573 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000574
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000575private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000576 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000577};
578
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000579}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000580
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000581static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000582 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000583 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000584 SourceLocation OpLoc, bool IsArrow,
585 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000586 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000587 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000588 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000589 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
590 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000591 diag::err_typecheck_incomplete_tag,
592 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000593 return true;
594
595 if (HasTemplateArgs) {
596 // LookupTemplateName doesn't expect these both to exist simultaneously.
597 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
598
599 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000600 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000601 return false;
602 }
603
604 DeclContext *DC = RDecl;
605 if (SS.isSet()) {
606 // If the member name was a qualified-id, look into the
607 // nested-name-specifier.
608 DC = SemaRef.computeDeclContext(SS, false);
609
610 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
611 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000612 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000613 return true;
614 }
615
616 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
617
618 if (!isa<TypeDecl>(DC)) {
619 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000620 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000621 return true;
622 }
623 }
624
625 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000626 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000627
628 if (!R.empty())
629 return false;
630
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000631 DeclarationName Typo = R.getLookupName();
632 SourceLocation TypoLoc = R.getNameLoc();
633 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000634 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
635 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000636 [=, &SemaRef](const TypoCorrection &TC) {
637 if (TC) {
638 assert(!TC.isKeyword() &&
639 "Got a keyword as a correction for a member!");
640 bool DroppedSpecifier =
641 TC.WillReplaceSpecifier() &&
642 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
643 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
644 << Typo << DC << DroppedSpecifier
645 << SS.getRange());
646 } else {
647 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
648 }
649 },
650 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
651 R.clear(); // Ensure there's no decls lingering in the shared state.
652 R.suppressDiagnostics();
653 R.setLookupName(TC.getCorrection());
654 for (NamedDecl *ND : TC)
655 R.addDecl(ND);
656 R.resolveKind();
657 return SemaRef.BuildMemberReferenceExpr(
658 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
659 nullptr, R, nullptr);
660 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000661 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000662
663 return false;
664}
665
Richard Smitha0edd302014-05-31 00:18:32 +0000666static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
667 ExprResult &BaseExpr, bool &IsArrow,
668 SourceLocation OpLoc, CXXScopeSpec &SS,
669 Decl *ObjCImpDecl, bool HasTemplateArgs);
670
Douglas Gregor5476205b2011-06-23 00:49:38 +0000671ExprResult
672Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
673 SourceLocation OpLoc, bool IsArrow,
674 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000675 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000676 NamedDecl *FirstQualifierInScope,
677 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000678 const TemplateArgumentListInfo *TemplateArgs,
679 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000680 if (BaseType->isDependentType() ||
681 (SS.isSet() && isDependentScopeSpecifier(SS)))
682 return ActOnDependentMemberExpr(Base, BaseType,
683 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000684 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000685 NameInfo, TemplateArgs);
686
687 LookupResult R(*this, NameInfo, LookupMemberName);
688
689 // Implicit member accesses.
690 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000691 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000692 QualType RecordTy = BaseType;
693 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000694 if (LookupMemberExprInRecord(*this, R, nullptr,
695 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000696 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000697 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000698 if (TE)
699 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000700
701 // Explicit member accesses.
702 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000703 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000704 ExprResult Result = LookupMemberExpr(
705 *this, R, BaseResult, IsArrow, OpLoc, SS,
706 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
707 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000708
709 if (BaseResult.isInvalid())
710 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000711 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000712
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000713 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000714 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000715
716 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000717 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000718
719 // LookupMemberExpr can modify Base, and thus change BaseType
720 BaseType = Base->getType();
721 }
722
723 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000724 OpLoc, IsArrow, SS, TemplateKWLoc,
Richard Smitha0edd302014-05-31 00:18:32 +0000725 FirstQualifierInScope, R, TemplateArgs,
726 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000727}
728
729static ExprResult
730BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000731 SourceLocation OpLoc, const CXXScopeSpec &SS,
732 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000733 const DeclarationNameInfo &MemberNameInfo);
734
735ExprResult
736Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
737 SourceLocation loc,
738 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000739 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000740 Expr *baseObjectExpr,
741 SourceLocation opLoc) {
742 // First, build the expression that refers to the base object.
743
744 bool baseObjectIsPointer = false;
745 Qualifiers baseQuals;
746
747 // Case 1: the base of the indirect field is not a field.
748 VarDecl *baseVariable = indirectField->getVarDecl();
749 CXXScopeSpec EmptySS;
750 if (baseVariable) {
751 assert(baseVariable->getType()->isRecordType());
752
753 // In principle we could have a member access expression that
754 // accesses an anonymous struct/union that's a static member of
755 // the base object's class. However, under the current standard,
756 // static data members cannot be anonymous structs or unions.
757 // Supporting this is as easy as building a MemberExpr here.
758 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
759
760 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
761
762 ExprResult result
763 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
764 if (result.isInvalid()) return ExprError();
765
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000766 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000767 baseObjectIsPointer = false;
768 baseQuals = baseObjectExpr->getType().getQualifiers();
769
770 // Case 2: the base of the indirect field is a field and the user
771 // wrote a member expression.
772 } else if (baseObjectExpr) {
773 // The caller provided the base object expression. Determine
774 // whether its a pointer and whether it adds any qualifiers to the
775 // anonymous struct/union fields we're looking into.
776 QualType objectType = baseObjectExpr->getType();
777
778 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
779 baseObjectIsPointer = true;
780 objectType = ptr->getPointeeType();
781 } else {
782 baseObjectIsPointer = false;
783 }
784 baseQuals = objectType.getQualifiers();
785
786 // Case 3: the base of the indirect field is a field and we should
787 // build an implicit member access.
788 } else {
789 // We've found a member of an anonymous struct/union that is
790 // inside a non-anonymous struct/union, so in a well-formed
791 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000792 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000793 if (ThisTy.isNull()) {
794 Diag(loc, diag::err_invalid_member_use_in_static_method)
795 << indirectField->getDeclName();
796 return ExprError();
797 }
798
799 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000800 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000801 baseObjectExpr
802 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
803 baseObjectIsPointer = true;
804 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
805 }
806
807 // Build the implicit member references to the field of the
808 // anonymous struct/union.
809 Expr *result = baseObjectExpr;
810 IndirectFieldDecl::chain_iterator
811 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
812
813 // Build the first member access in the chain with full information.
814 if (!baseVariable) {
815 FieldDecl *field = cast<FieldDecl>(*FI);
816
Douglas Gregor5476205b2011-06-23 00:49:38 +0000817 // Make a nameInfo that properly uses the anonymous name.
818 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000819
Douglas Gregor5476205b2011-06-23 00:49:38 +0000820 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000821 SourceLocation(), EmptySS, field,
822 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000823 if (!result)
824 return ExprError();
825
Douglas Gregor5476205b2011-06-23 00:49:38 +0000826 // FIXME: check qualified member access
827 }
828
829 // In all cases, we should now skip the first declaration in the chain.
830 ++FI;
831
832 while (FI != FEnd) {
833 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000834
Douglas Gregor5476205b2011-06-23 00:49:38 +0000835 // FIXME: these are somewhat meaningless
836 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000837 DeclAccessPair fakeFoundDecl =
838 DeclAccessPair::make(field, field->getAccess());
839
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000840 result =
841 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
842 SourceLocation(), (FI == FEnd ? SS : EmptySS),
843 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000844 }
845
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000846 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000847}
848
John McCall5e77d762013-04-16 07:28:30 +0000849static ExprResult
850BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
851 const CXXScopeSpec &SS,
852 MSPropertyDecl *PD,
853 const DeclarationNameInfo &NameInfo) {
854 // Property names are always simple identifiers and therefore never
855 // require any interesting additional storage.
856 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
857 S.Context.PseudoObjectTy, VK_LValue,
858 SS.getWithLocInContext(S.Context),
859 NameInfo.getLoc());
860}
861
Douglas Gregor5476205b2011-06-23 00:49:38 +0000862/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000863static MemberExpr *BuildMemberExpr(
864 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
865 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
866 ValueDecl *Member, DeclAccessPair FoundDecl,
867 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
868 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000869 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000870 MemberExpr *E = MemberExpr::Create(
871 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
872 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000873 SemaRef.MarkMemberReferenced(E);
874 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000875}
876
877ExprResult
878Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
879 SourceLocation OpLoc, bool IsArrow,
880 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000881 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000882 NamedDecl *FirstQualifierInScope,
883 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000884 const TemplateArgumentListInfo *TemplateArgs,
885 bool SuppressQualifierCheck,
886 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000887 QualType BaseType = BaseExprType;
888 if (IsArrow) {
889 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000890 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000891 }
892 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000893
894 LambdaScopeInfo *const CurLSI = getCurLambda();
895 // If this is an implicit member reference and the overloaded
896 // name refers to both static and non-static member functions
897 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
898 // check if we should/can capture 'this'...
899 // Keep this example in mind:
900 // struct X {
901 // void f(int) { }
902 // static void f(double) { }
903 //
904 // int g() {
905 // auto L = [=](auto a) {
906 // return [](int i) {
907 // return [=](auto b) {
908 // f(b);
909 // //f(decltype(a){});
910 // };
911 // };
912 // };
913 // auto M = L(0.0);
914 // auto N = M(3);
915 // N(5.32); // OK, must not error.
916 // return 0;
917 // }
918 // };
919 //
920 if (!BaseExpr && CurLSI) {
921 SourceLocation Loc = R.getNameLoc();
922 if (SS.getRange().isValid())
923 Loc = SS.getRange().getBegin();
924 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
925 // If the enclosing function is not dependent, then this lambda is
926 // capture ready, so if we can capture this, do so.
927 if (!EnclosingFunctionCtx->isDependentContext()) {
928 // If the current lambda and all enclosing lambdas can capture 'this' -
929 // then go ahead and capture 'this' (since our unresolved overload set
930 // contains both static and non-static member functions).
931 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
932 CheckCXXThisCapture(Loc);
933 } else if (CurContext->isDependentContext()) {
934 // ... since this is an implicit member reference, that might potentially
935 // involve a 'this' capture, mark 'this' for potential capture in
936 // enclosing lambdas.
937 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
938 CurLSI->addPotentialThisCapture(Loc);
939 }
940 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000941 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
942 DeclarationName MemberName = MemberNameInfo.getName();
943 SourceLocation MemberLoc = MemberNameInfo.getLoc();
944
945 if (R.isAmbiguous())
946 return ExprError();
947
948 if (R.empty()) {
949 // Rederive where we looked up.
950 DeclContext *DC = (SS.isSet()
951 ? computeDeclContext(SS, false)
952 : BaseType->getAs<RecordType>()->getDecl());
953
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000954 if (ExtraArgs) {
955 ExprResult RetryExpr;
956 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000957 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000958 ParsedType ObjectType;
959 bool MayBePseudoDestructor = false;
960 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
961 OpLoc, tok::arrow, ObjectType,
962 MayBePseudoDestructor);
963 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
964 CXXScopeSpec TempSS(SS);
965 RetryExpr = ActOnMemberAccessExpr(
966 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +0000967 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000968 }
969 if (Trap.hasErrorOccurred())
970 RetryExpr = ExprError();
971 }
972 if (RetryExpr.isUsable()) {
973 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
974 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
975 return RetryExpr;
976 }
977 }
978
Douglas Gregor5476205b2011-06-23 00:49:38 +0000979 Diag(R.getNameLoc(), diag::err_no_member)
980 << MemberName << DC
981 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
982 return ExprError();
983 }
984
985 // Diagnose lookups that find only declarations from a non-base
986 // type. This is possible for either qualified lookups (which may
987 // have been qualified with an unrelated type) or implicit member
988 // expressions (which were found with unqualified lookup and thus
989 // may have come from an enclosing scope). Note that it's okay for
990 // lookup to find declarations from a non-base type as long as those
991 // aren't the ones picked by overload resolution.
992 if ((SS.isSet() || !BaseExpr ||
993 (isa<CXXThisExpr>(BaseExpr) &&
994 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
995 !SuppressQualifierCheck &&
996 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
997 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +0000998
Douglas Gregor5476205b2011-06-23 00:49:38 +0000999 // Construct an unresolved result if we in fact got an unresolved
1000 // result.
1001 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1002 // Suppress any lookup-related diagnostics; we'll do these when we
1003 // pick a member.
1004 R.suppressDiagnostics();
1005
1006 UnresolvedMemberExpr *MemExpr
1007 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1008 BaseExpr, BaseExprType,
1009 IsArrow, OpLoc,
1010 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001011 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001012 TemplateArgs, R.begin(), R.end());
1013
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001014 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001015 }
1016
1017 assert(R.isSingleResult());
1018 DeclAccessPair FoundDecl = R.begin().getPair();
1019 NamedDecl *MemberDecl = R.getFoundDecl();
1020
1021 // FIXME: diagnose the presence of template arguments now.
1022
1023 // If the decl being referenced had an error, return an error for this
1024 // sub-expr without emitting another error, in order to avoid cascading
1025 // error cases.
1026 if (MemberDecl->isInvalidDecl())
1027 return ExprError();
1028
1029 // Handle the implicit-member-access case.
1030 if (!BaseExpr) {
1031 // If this is not an instance member, convert to a non-member access.
1032 if (!MemberDecl->isCXXInstanceMember())
1033 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1034
1035 SourceLocation Loc = R.getNameLoc();
1036 if (SS.getRange().isValid())
1037 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001038 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001039 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1040 }
1041
Douglas Gregor5476205b2011-06-23 00:49:38 +00001042 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001043 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001044 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001045
Douglas Gregor5476205b2011-06-23 00:49:38 +00001046 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001047 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1048 FoundDecl, MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001049
John McCall5e77d762013-04-16 07:28:30 +00001050 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1051 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1052 MemberNameInfo);
1053
Douglas Gregor5476205b2011-06-23 00:49:38 +00001054 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1055 // We may have found a field within an anonymous union or struct
1056 // (C++ [class.union]).
1057 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001058 FoundDecl, BaseExpr,
1059 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001060
1061 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001062 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1063 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001064 Var->getType().getNonReferenceType(), VK_LValue,
1065 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001066 }
1067
1068 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1069 ExprValueKind valueKind;
1070 QualType type;
1071 if (MemberFn->isInstance()) {
1072 valueKind = VK_RValue;
1073 type = Context.BoundMemberTy;
1074 } else {
1075 valueKind = VK_LValue;
1076 type = MemberFn->getType();
1077 }
1078
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001079 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1080 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1081 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001082 }
1083 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1084
1085 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001086 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1087 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1088 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001089 }
1090
Douglas Gregor5476205b2011-06-23 00:49:38 +00001091 // We found something that we didn't expect. Complain.
1092 if (isa<TypeDecl>(MemberDecl))
1093 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1094 << MemberName << BaseType << int(IsArrow);
1095 else
1096 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1097 << MemberName << BaseType << int(IsArrow);
1098
1099 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1100 << MemberName;
1101 R.suppressDiagnostics();
1102 return ExprError();
1103}
1104
1105/// Given that normal member access failed on the given expression,
1106/// and given that the expression's type involves builtin-id or
1107/// builtin-Class, decide whether substituting in the redefinition
1108/// types would be profitable. The redefinition type is whatever
1109/// this translation unit tried to typedef to id/Class; we store
1110/// it to the side and then re-use it in places like this.
1111static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1112 const ObjCObjectPointerType *opty
1113 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1114 if (!opty) return false;
1115
1116 const ObjCObjectType *ty = opty->getObjectType();
1117
1118 QualType redef;
1119 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001120 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001121 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001122 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001123 } else {
1124 return false;
1125 }
1126
1127 // Do the substitution as long as the redefinition type isn't just a
1128 // possibly-qualified pointer to builtin-id or builtin-Class again.
1129 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001130 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001131 return false;
1132
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001133 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001134 return true;
1135}
1136
John McCall50a2c2c2011-10-11 23:14:30 +00001137static bool isRecordType(QualType T) {
1138 return T->isRecordType();
1139}
1140static bool isPointerToRecordType(QualType T) {
1141 if (const PointerType *PT = T->getAs<PointerType>())
1142 return PT->getPointeeType()->isRecordType();
1143 return false;
1144}
1145
Richard Smithcab9a7d2011-10-26 19:06:56 +00001146/// Perform conversions on the LHS of a member access expression.
1147ExprResult
1148Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001149 if (IsArrow && !Base->getType()->isFunctionType())
1150 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001151
Eli Friedman9a766c42012-01-13 02:20:01 +00001152 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001153}
1154
Douglas Gregor5476205b2011-06-23 00:49:38 +00001155/// Look up the given member of the given non-type-dependent
1156/// expression. This can return in one of two ways:
1157/// * If it returns a sentinel null-but-valid result, the caller will
1158/// assume that lookup was performed and the results written into
1159/// the provided structure. It will take over from there.
1160/// * Otherwise, the returned expression will be produced in place of
1161/// an ordinary member expression.
1162///
1163/// The ObjCImpDecl bit is a gross hack that will need to be properly
1164/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001165static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1166 ExprResult &BaseExpr, bool &IsArrow,
1167 SourceLocation OpLoc, CXXScopeSpec &SS,
1168 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001169 assert(BaseExpr.get() && "no base expression");
1170
1171 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001172 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001173 if (BaseExpr.isInvalid())
1174 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001175
Douglas Gregor5476205b2011-06-23 00:49:38 +00001176 QualType BaseType = BaseExpr.get()->getType();
1177 assert(!BaseType->isDependentType());
1178
1179 DeclarationName MemberName = R.getLookupName();
1180 SourceLocation MemberLoc = R.getNameLoc();
1181
1182 // For later type-checking purposes, turn arrow accesses into dot
1183 // accesses. The only access type we support that doesn't follow
1184 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1185 // and those never use arrows, so this is unaffected.
1186 if (IsArrow) {
1187 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1188 BaseType = Ptr->getPointeeType();
1189 else if (const ObjCObjectPointerType *Ptr
1190 = BaseType->getAs<ObjCObjectPointerType>())
1191 BaseType = Ptr->getPointeeType();
1192 else if (BaseType->isRecordType()) {
1193 // Recover from arrow accesses to records, e.g.:
1194 // struct MyRecord foo;
1195 // foo->bar
1196 // This is actually well-formed in C++ if MyRecord has an
1197 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001198 // by now--or a diagnostic message already issued if a problem
1199 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001200 if (!S.getLangOpts().CPlusPlus) {
1201 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001202 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1203 << FixItHint::CreateReplacement(OpLoc, ".");
1204 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001205 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001206 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001207 goto fail;
1208 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001209 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001210 << BaseType << BaseExpr.get()->getSourceRange();
1211 return ExprError();
1212 }
1213 }
1214
1215 // Handle field access to simple records.
1216 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001217 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001218 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001219 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001220 return ExprError();
1221
1222 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001223 // the lookup result was filled in. If typo correction was attempted and
1224 // failed, the lookup result will have been cleared--that combined with the
1225 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1226 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001227 }
1228
1229 // Handle ivar access to Objective-C objects.
1230 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001231 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001232 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001233 << 1 << SS.getScopeRep()
1234 << FixItHint::CreateRemoval(SS.getRange());
1235 SS.clear();
1236 }
Richard Smitha0edd302014-05-31 00:18:32 +00001237
Douglas Gregor5476205b2011-06-23 00:49:38 +00001238 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1239
1240 // There are three cases for the base type:
1241 // - builtin id (qualified or unqualified)
1242 // - builtin Class (qualified or unqualified)
1243 // - an interface
1244 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1245 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001246 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001247 (OTy->isObjCId() || OTy->isObjCClass()))
1248 goto fail;
1249 // There's an implicit 'isa' ivar on all objects.
1250 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001251 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001252 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001253 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1254 OpLoc, S.Context.getObjCClassType());
1255 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1256 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001257 ObjCImpDecl, HasTemplateArgs);
1258 goto fail;
1259 }
Richard Smitha0edd302014-05-31 00:18:32 +00001260
1261 if (S.RequireCompleteType(OpLoc, BaseType,
1262 diag::err_typecheck_incomplete_tag,
1263 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001264 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001265
1266 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001267 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1268
1269 if (!IV) {
1270 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001271 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1272 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001273 if (TypoCorrection Corrected = S.CorrectTypo(
1274 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001275 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001276 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001277 S.diagnoseTypo(
1278 Corrected,
1279 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1280 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001281
Ted Kremenek679b4782012-03-17 00:53:39 +00001282 // Figure out the class that declares the ivar.
1283 assert(!ClassDeclared);
1284 Decl *D = cast<Decl>(IV->getDeclContext());
1285 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1286 D = CAT->getClassInterface();
1287 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001288 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001289 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001290 S.Diag(MemberLoc, diag::err_property_found_suggest)
1291 << Member << BaseExpr.get()->getType()
1292 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001293 return ExprError();
1294 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001295
Richard Smitha0edd302014-05-31 00:18:32 +00001296 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1297 << IDecl->getDeclName() << MemberName
1298 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001299 return ExprError();
1300 }
1301 }
Richard Smitha0edd302014-05-31 00:18:32 +00001302
Ted Kremenek679b4782012-03-17 00:53:39 +00001303 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001304
1305 // If the decl being referenced had an error, return an error for this
1306 // sub-expr without emitting another error, in order to avoid cascading
1307 // error cases.
1308 if (IV->isInvalidDecl())
1309 return ExprError();
1310
1311 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001312 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001313 return ExprError();
1314 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1315 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001316 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001317 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001318 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001319 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001320 // Case of a c-function declared inside an objc implementation.
1321 // FIXME: For a c-style function nested inside an objc implementation
1322 // class, there is no implementation context available, so we pass
1323 // down the context as argument to this routine. Ideally, this context
1324 // need be passed down in the AST node and somehow calculated from the
1325 // AST for a function decl.
1326 if (ObjCImplementationDecl *IMPD =
1327 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1328 ClassOfMethodDecl = IMPD->getClassInterface();
1329 else if (ObjCCategoryImplDecl* CatImplClass =
1330 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1331 ClassOfMethodDecl = CatImplClass->getClassInterface();
1332 }
Richard Smitha0edd302014-05-31 00:18:32 +00001333 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001334 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1335 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1336 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001337 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001338 << IV->getDeclName();
1339 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1340 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001341 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1342 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001343 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001344 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001345 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001346 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001347 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1348 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1349 if (UO->getOpcode() == UO_Deref)
1350 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1351
1352 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001353 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001354 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001355 warn = false;
1356 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001357 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001358 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001359 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001360 ObjCMethodFamily MF = MD->getMethodFamily();
1361 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001362 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001363 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001364 }
1365 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001366 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001367 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001368
Richard Smitha0edd302014-05-31 00:18:32 +00001369 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001370 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1371 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001372
Richard Smitha0edd302014-05-31 00:18:32 +00001373 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001374 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001375 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001376 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001377 }
1378 }
1379
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001380 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001381 }
1382
1383 // Objective-C property access.
1384 const ObjCObjectPointerType *OPT;
1385 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001386 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001387 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1388 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001389 SS.clear();
1390 }
1391
Douglas Gregor5476205b2011-06-23 00:49:38 +00001392 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001393 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001394 if (BaseExpr.isInvalid())
1395 return ExprError();
1396
Richard Smitha0edd302014-05-31 00:18:32 +00001397 assert(S.Context.hasSameUnqualifiedType(BaseType,
1398 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001399
1400 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1401
1402 const ObjCObjectType *OT = OPT->getObjectType();
1403
1404 // id, with and without qualifiers.
1405 if (OT->isObjCId()) {
1406 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001407 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1408 if (Decl *PMDecl =
1409 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001410 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1411 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001412 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001413 return ExprError();
1414
Richard Smitha0edd302014-05-31 00:18:32 +00001415 return new (S.Context)
1416 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001417 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001418 }
1419
1420 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1421 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001422 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001423 return ExprError();
1424 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001425 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1426 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001427 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001428 ObjCMethodDecl *SMD = nullptr;
1429 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001430 /*Property id*/ nullptr,
1431 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001432 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001433
1434 return new (S.Context)
1435 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001436 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001437 }
1438 }
1439 // Use of id.member can only be for a property reference. Do not
1440 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001441 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1442 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001443 ObjCImpDecl, HasTemplateArgs);
1444
Richard Smitha0edd302014-05-31 00:18:32 +00001445 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001446 << MemberName << BaseType);
1447 }
1448
1449 // 'Class', unqualified only.
1450 if (OT->isObjCClass()) {
1451 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001452 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001453 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001454 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1455 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001456 ObjCImpDecl, HasTemplateArgs);
1457
1458 goto fail;
1459 }
1460
1461 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001462 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001463 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1464 ObjCMethodDecl *Getter;
1465 if ((Getter = IFace->lookupClassMethod(Sel))) {
1466 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001467 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001468 return ExprError();
1469 } else
1470 Getter = IFace->lookupPrivateMethod(Sel, false);
1471 // If we found a getter then this may be a valid dot-reference, we
1472 // will look for the matching setter, in case it is needed.
1473 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001474 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1475 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001476 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001477 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1478 if (!Setter) {
1479 // If this reference is in an @implementation, also check for 'private'
1480 // methods.
1481 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1482 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001483
Richard Smitha0edd302014-05-31 00:18:32 +00001484 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001485 return ExprError();
1486
1487 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001488 return new (S.Context) ObjCPropertyRefExpr(
1489 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1490 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001491 }
1492
Richard Smitha0edd302014-05-31 00:18:32 +00001493 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1494 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001495 ObjCImpDecl, HasTemplateArgs);
1496
Richard Smitha0edd302014-05-31 00:18:32 +00001497 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001498 << MemberName << BaseType);
1499 }
1500
1501 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001502 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1503 MemberLoc, SourceLocation(), QualType(),
1504 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001505 }
1506
1507 // Handle 'field access' to vectors, such as 'V.xx'.
1508 if (BaseType->isExtVectorType()) {
1509 // FIXME: this expr should store IsArrow.
1510 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001511 ExprValueKind VK;
1512 if (IsArrow)
1513 VK = VK_LValue;
1514 else {
1515 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1516 VK = POE->getSyntacticForm()->getValueKind();
1517 else
1518 VK = BaseExpr.get()->getValueKind();
1519 }
Richard Smitha0edd302014-05-31 00:18:32 +00001520 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001521 Member, MemberLoc);
1522 if (ret.isNull())
1523 return ExprError();
1524
Richard Smitha0edd302014-05-31 00:18:32 +00001525 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001526 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001527 }
1528
1529 // Adjust builtin-sel to the appropriate redefinition type if that's
1530 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001531 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1532 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1533 BaseExpr = S.ImpCastExprToType(
1534 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1535 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001536 ObjCImpDecl, HasTemplateArgs);
1537 }
1538
1539 // Failure cases.
1540 fail:
1541
1542 // Recover from dot accesses to pointers, e.g.:
1543 // type *foo;
1544 // foo.bar
1545 // This is actually well-formed in two cases:
1546 // - 'type' is an Objective C type
1547 // - 'bar' is a pseudo-destructor name which happens to refer to
1548 // the appropriate pointer type
1549 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1550 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1551 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001552 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1553 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001554 << FixItHint::CreateReplacement(OpLoc, "->");
1555
1556 // Recurse as an -> access.
1557 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001558 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001559 ObjCImpDecl, HasTemplateArgs);
1560 }
1561 }
1562
1563 // If the user is trying to apply -> or . to a function name, it's probably
1564 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001565 if (S.tryToRecoverWithCall(
1566 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1567 /*complain*/ false,
1568 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001569 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001570 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001571 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1572 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001573 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001574 }
1575
Richard Smitha0edd302014-05-31 00:18:32 +00001576 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001577 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001578
1579 return ExprError();
1580}
1581
1582/// The main callback when the parser finds something like
1583/// expression . [nested-name-specifier] identifier
1584/// expression -> [nested-name-specifier] identifier
1585/// where 'identifier' encompasses a fairly broad spectrum of
1586/// possibilities, including destructor and operator references.
1587///
1588/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001589/// \param ObjCImpDecl the current Objective-C \@implementation
1590/// decl; this is an ugly hack around the fact that Objective-C
1591/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001592ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1593 SourceLocation OpLoc,
1594 tok::TokenKind OpKind,
1595 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001596 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001597 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001598 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001599 if (SS.isSet() && SS.isInvalid())
1600 return ExprError();
1601
1602 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001603 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001604 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1605 Diag(Id.getSourceRange().getBegin(),
1606 diag::ext_ms_explicit_constructor_call);
1607
1608 TemplateArgumentListInfo TemplateArgsBuffer;
1609
1610 // Decompose the name into its component parts.
1611 DeclarationNameInfo NameInfo;
1612 const TemplateArgumentListInfo *TemplateArgs;
1613 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1614 NameInfo, TemplateArgs);
1615
1616 DeclarationName Name = NameInfo.getName();
1617 bool IsArrow = (OpKind == tok::arrow);
1618
1619 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001620 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001621
1622 // This is a postfix expression, so get rid of ParenListExprs.
1623 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1624 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001625 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001626
1627 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1628 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001629 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1630 TemplateKWLoc, FirstQualifierInScope,
1631 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001632 }
1633
David Majnemerced8bdf2015-02-25 17:36:15 +00001634 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001635 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1636 TemplateKWLoc, FirstQualifierInScope,
1637 NameInfo, TemplateArgs, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001638}
1639
1640static ExprResult
1641BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001642 SourceLocation OpLoc, const CXXScopeSpec &SS,
1643 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001644 const DeclarationNameInfo &MemberNameInfo) {
1645 // x.a is an l-value if 'a' has a reference type. Otherwise:
1646 // x.a is an l-value/x-value/pr-value if the base is (and note
1647 // that *x is always an l-value), except that if the base isn't
1648 // an ordinary object then we must have an rvalue.
1649 ExprValueKind VK = VK_LValue;
1650 ExprObjectKind OK = OK_Ordinary;
1651 if (!IsArrow) {
1652 if (BaseExpr->getObjectKind() == OK_Ordinary)
1653 VK = BaseExpr->getValueKind();
1654 else
1655 VK = VK_RValue;
1656 }
1657 if (VK != VK_RValue && Field->isBitField())
1658 OK = OK_BitField;
1659
1660 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1661 QualType MemberType = Field->getType();
1662 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1663 MemberType = Ref->getPointeeType();
1664 VK = VK_LValue;
1665 } else {
1666 QualType BaseType = BaseExpr->getType();
1667 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001668
Douglas Gregor5476205b2011-06-23 00:49:38 +00001669 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001670
Douglas Gregor5476205b2011-06-23 00:49:38 +00001671 // GC attributes are never picked up by members.
1672 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001673
Douglas Gregor5476205b2011-06-23 00:49:38 +00001674 // CVR attributes from the base are picked up by members,
1675 // except that 'mutable' members don't pick up 'const'.
1676 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001677
Douglas Gregor5476205b2011-06-23 00:49:38 +00001678 Qualifiers MemberQuals
1679 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001680
Douglas Gregor5476205b2011-06-23 00:49:38 +00001681 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001682
1683
Douglas Gregor5476205b2011-06-23 00:49:38 +00001684 Qualifiers Combined = BaseQuals + MemberQuals;
1685 if (Combined != MemberQuals)
1686 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1687 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001688
Daniel Jasper0baec5492012-06-06 08:32:04 +00001689 S.UnusedPrivateFields.remove(Field);
1690
Douglas Gregor5476205b2011-06-23 00:49:38 +00001691 ExprResult Base =
1692 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1693 FoundDecl, Field);
1694 if (Base.isInvalid())
1695 return ExprError();
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001696 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001697 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1698 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001699}
1700
1701/// Builds an implicit member access expression. The current context
1702/// is known to be an instance method, and the given unqualified lookup
1703/// set is known to contain only instance members, at least one of which
1704/// is from an appropriate type.
1705ExprResult
1706Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001707 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001708 LookupResult &R,
1709 const TemplateArgumentListInfo *TemplateArgs,
1710 bool IsKnownInstance) {
1711 assert(!R.empty() && !R.isAmbiguous());
1712
1713 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001714
Douglas Gregor5476205b2011-06-23 00:49:38 +00001715 // If this is known to be an instance access, go ahead and build an
1716 // implicit 'this' expression now.
1717 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001718 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001719 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001720
1721 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001722 if (IsKnownInstance) {
1723 SourceLocation Loc = R.getNameLoc();
1724 if (SS.getRange().isValid())
1725 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001726 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001727 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1728 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001729
Douglas Gregor5476205b2011-06-23 00:49:38 +00001730 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1731 /*OpLoc*/ SourceLocation(),
1732 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001733 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001734 /*FirstQualifierInScope*/ nullptr,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001735 R, TemplateArgs);
1736}