blob: f62b5a58e84ed2fb92a7d2ef58b24179edd77134 [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;
Reid Kleckner077fe122015-10-20 18:12:08 +0000105 for (NamedDecl *D : R) {
106 // Look through any using decls.
107 D = D->getUnderlyingDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000108
109 if (D->isCXXInstanceMember()) {
Benjamin Kramera008d3a2015-04-10 11:37:55 +0000110 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
111 isa<IndirectFieldDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000112
113 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
114 Classes.insert(R->getCanonicalDecl());
Reid Kleckner077fe122015-10-20 18:12:08 +0000115 } else
Douglas Gregor5476205b2011-06-23 00:49:38 +0000116 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.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000195static void diagnoseInstanceReference(Sema &SemaRef,
196 const CXXScopeSpec &SS,
197 NamedDecl *Rep,
198 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
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000206 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
Richard Smithfa0a1f52012-04-05 01:13:04 +0000207 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"
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000216 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000217 << 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.
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000222 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
223 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000224 else if (IsField)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
226 << nameInfo.getName() << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000227 else
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000228 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,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000237 const TemplateArgumentListInfo *TemplateArgs,
238 const Scope *S) {
Reid Klecknerae628962014-12-18 00:42:51 +0000239 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000240 case IMA_Instance:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000241 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000242
243 case IMA_Mixed:
244 case IMA_Mixed_Unrelated:
245 case IMA_Unresolved:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000246 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
247 S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000248
Richard Smith2a986112012-02-25 10:20:59 +0000249 case IMA_Field_Uneval_Context:
250 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
251 << R.getLookupNameInfo().getName();
252 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000253 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000254 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000255 case IMA_Mixed_StaticContext:
256 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000257 if (TemplateArgs || TemplateKWLoc.isValid())
258 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000259 return BuildDeclarationNameExpr(SS, R, false);
260
261 case IMA_Error_StaticContext:
262 case IMA_Error_Unrelated:
Reid Kleckner7d3a2f02015-10-20 00:31:42 +0000263 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000264 R.getLookupNameInfo());
265 return ExprError();
266 }
267
268 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000269}
270
271/// Check an ext-vector component access expression.
272///
273/// VK should be set in advance to the value kind of the base
274/// expression.
275static QualType
276CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
277 SourceLocation OpLoc, const IdentifierInfo *CompName,
278 SourceLocation CompLoc) {
279 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
280 // see FIXME there.
281 //
282 // FIXME: This logic can be greatly simplified by splitting it along
283 // halving/not halving and reworking the component checking.
284 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
285
286 // The vector accessor can't exceed the number of elements.
287 const char *compStr = CompName->getNameStart();
288
289 // This flag determines whether or not the component is one of the four
290 // special names that indicate a subset of exactly half the elements are
291 // to be selected.
292 bool HalvingSwizzle = false;
293
294 // This flag determines whether or not CompName has an 's' char prefix,
295 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000296 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000297
298 bool HasRepeated = false;
299 bool HasIndex[16] = {};
300
301 int Idx;
302
303 // Check that we've found one of the special components, or that the component
304 // names must come from the same set.
305 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
306 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
307 HalvingSwizzle = true;
308 } else if (!HexSwizzle &&
309 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
310 do {
311 if (HasIndex[Idx]) HasRepeated = true;
312 HasIndex[Idx] = true;
313 compStr++;
314 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
315 } else {
316 if (HexSwizzle) compStr++;
317 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
318 if (HasIndex[Idx]) HasRepeated = true;
319 HasIndex[Idx] = true;
320 compStr++;
321 }
322 }
323
324 if (!HalvingSwizzle && *compStr) {
325 // We didn't get to the end of the string. This means the component names
326 // didn't come from the same set *or* we encountered an illegal name.
327 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000328 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000329 return QualType();
330 }
331
332 // Ensure no component accessor exceeds the width of the vector type it
333 // operates on.
334 if (!HalvingSwizzle) {
335 compStr = CompName->getNameStart();
336
337 if (HexSwizzle)
338 compStr++;
339
340 while (*compStr) {
341 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
342 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
343 << baseType << SourceRange(CompLoc);
344 return QualType();
345 }
346 }
347 }
348
349 // The component accessor looks fine - now we need to compute the actual type.
350 // The vector type is implied by the component accessor. For example,
351 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
352 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
353 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
354 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
355 : CompName->getLength();
356 if (HexSwizzle)
357 CompSize--;
358
359 if (CompSize == 1)
360 return vecType->getElementType();
361
362 if (HasRepeated) VK = VK_RValue;
363
364 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
365 // Now look up the TypeDefDecl from the vector type. Without this,
366 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000367 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000368 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000369 E = S.ExtVectorDecls.end();
370 I != E; ++I) {
371 if ((*I)->getUnderlyingType() == VT)
372 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000373 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000374
Douglas Gregor5476205b2011-06-23 00:49:38 +0000375 return VT; // should never get here (a typedef type should always be found).
376}
377
378static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
379 IdentifierInfo *Member,
380 const Selector &Sel,
381 ASTContext &Context) {
382 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000383 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(
384 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000385 return PD;
386 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
387 return OMD;
388
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000389 for (const auto *I : PDecl->protocols()) {
390 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000391 Context))
392 return D;
393 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000394 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000395}
396
397static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
398 IdentifierInfo *Member,
399 const Selector &Sel,
400 ASTContext &Context) {
401 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000402 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000403 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000404 if (Member)
Manman Ren5b786402016-01-28 18:49:28 +0000405 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(
406 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
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)
Reid Kleckner7d3a2f02015-10-20 00:31:42 +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
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000583}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000584
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();
David Blaikiea8173ba2015-09-28 23:48:55 +0000637
638 struct QueryState {
639 Sema &SemaRef;
640 DeclarationNameInfo NameInfo;
641 Sema::LookupNameKind LookupKind;
642 Sema::RedeclarationKind Redecl;
643 };
644 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
645 R.isForRedeclaration() ? Sema::ForRedeclaration
646 : Sema::NotForRedeclaration};
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000647 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000648 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
649 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000650 [=, &SemaRef](const TypoCorrection &TC) {
651 if (TC) {
652 assert(!TC.isKeyword() &&
653 "Got a keyword as a correction for a member!");
654 bool DroppedSpecifier =
655 TC.WillReplaceSpecifier() &&
656 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
657 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
658 << Typo << DC << DroppedSpecifier
659 << SS.getRange());
660 } else {
661 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
662 }
663 },
664 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
David Blaikiea8173ba2015-09-28 23:48:55 +0000665 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000666 R.clear(); // Ensure there's no decls lingering in the shared state.
667 R.suppressDiagnostics();
668 R.setLookupName(TC.getCorrection());
669 for (NamedDecl *ND : TC)
670 R.addDecl(ND);
671 R.resolveKind();
672 return SemaRef.BuildMemberReferenceExpr(
673 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000674 nullptr, R, nullptr, nullptr);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000675 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000676 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000677
678 return false;
679}
680
Richard Smitha0edd302014-05-31 00:18:32 +0000681static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
682 ExprResult &BaseExpr, bool &IsArrow,
683 SourceLocation OpLoc, CXXScopeSpec &SS,
684 Decl *ObjCImpDecl, bool HasTemplateArgs);
685
Douglas Gregor5476205b2011-06-23 00:49:38 +0000686ExprResult
687Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
688 SourceLocation OpLoc, bool IsArrow,
689 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000690 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000691 NamedDecl *FirstQualifierInScope,
692 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000693 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000694 const Scope *S,
Richard Smitha0edd302014-05-31 00:18:32 +0000695 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000696 if (BaseType->isDependentType() ||
697 (SS.isSet() && isDependentScopeSpecifier(SS)))
698 return ActOnDependentMemberExpr(Base, BaseType,
699 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000700 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000701 NameInfo, TemplateArgs);
702
703 LookupResult R(*this, NameInfo, LookupMemberName);
704
705 // Implicit member accesses.
706 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000707 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000708 QualType RecordTy = BaseType;
709 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000710 if (LookupMemberExprInRecord(*this, R, nullptr,
711 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000712 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000713 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000714 if (TE)
715 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000716
717 // Explicit member accesses.
718 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000719 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000720 ExprResult Result = LookupMemberExpr(
721 *this, R, BaseResult, IsArrow, OpLoc, SS,
722 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
723 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000724
725 if (BaseResult.isInvalid())
726 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000727 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000728
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000729 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000730 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000731
732 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000733 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000734
735 // LookupMemberExpr can modify Base, and thus change BaseType
736 BaseType = Base->getType();
737 }
738
739 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000740 OpLoc, IsArrow, SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000741 FirstQualifierInScope, R, TemplateArgs, S,
Richard Smitha0edd302014-05-31 00:18:32 +0000742 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000743}
744
745static ExprResult
746BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000747 SourceLocation OpLoc, const CXXScopeSpec &SS,
748 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000749 const DeclarationNameInfo &MemberNameInfo);
750
751ExprResult
752Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
753 SourceLocation loc,
754 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000755 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000756 Expr *baseObjectExpr,
757 SourceLocation opLoc) {
758 // First, build the expression that refers to the base object.
759
760 bool baseObjectIsPointer = false;
761 Qualifiers baseQuals;
762
763 // Case 1: the base of the indirect field is not a field.
764 VarDecl *baseVariable = indirectField->getVarDecl();
765 CXXScopeSpec EmptySS;
766 if (baseVariable) {
767 assert(baseVariable->getType()->isRecordType());
768
769 // In principle we could have a member access expression that
770 // accesses an anonymous struct/union that's a static member of
771 // the base object's class. However, under the current standard,
772 // static data members cannot be anonymous structs or unions.
773 // Supporting this is as easy as building a MemberExpr here.
774 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
775
776 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
777
778 ExprResult result
779 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
780 if (result.isInvalid()) return ExprError();
781
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000782 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000783 baseObjectIsPointer = false;
784 baseQuals = baseObjectExpr->getType().getQualifiers();
785
786 // Case 2: the base of the indirect field is a field and the user
787 // wrote a member expression.
788 } else if (baseObjectExpr) {
789 // The caller provided the base object expression. Determine
790 // whether its a pointer and whether it adds any qualifiers to the
791 // anonymous struct/union fields we're looking into.
792 QualType objectType = baseObjectExpr->getType();
793
794 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
795 baseObjectIsPointer = true;
796 objectType = ptr->getPointeeType();
797 } else {
798 baseObjectIsPointer = false;
799 }
800 baseQuals = objectType.getQualifiers();
801
802 // Case 3: the base of the indirect field is a field and we should
803 // build an implicit member access.
804 } else {
805 // We've found a member of an anonymous struct/union that is
806 // inside a non-anonymous struct/union, so in a well-formed
807 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000808 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000809 if (ThisTy.isNull()) {
810 Diag(loc, diag::err_invalid_member_use_in_static_method)
811 << indirectField->getDeclName();
812 return ExprError();
813 }
814
815 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000816 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000817 baseObjectExpr
818 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
819 baseObjectIsPointer = true;
820 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
821 }
822
823 // Build the implicit member references to the field of the
824 // anonymous struct/union.
825 Expr *result = baseObjectExpr;
826 IndirectFieldDecl::chain_iterator
827 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
828
829 // Build the first member access in the chain with full information.
830 if (!baseVariable) {
831 FieldDecl *field = cast<FieldDecl>(*FI);
832
Douglas Gregor5476205b2011-06-23 00:49:38 +0000833 // Make a nameInfo that properly uses the anonymous name.
834 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000835
Douglas Gregor5476205b2011-06-23 00:49:38 +0000836 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000837 SourceLocation(), EmptySS, field,
838 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000839 if (!result)
840 return ExprError();
841
Douglas Gregor5476205b2011-06-23 00:49:38 +0000842 // FIXME: check qualified member access
843 }
844
845 // In all cases, we should now skip the first declaration in the chain.
846 ++FI;
847
848 while (FI != FEnd) {
849 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000850
Douglas Gregor5476205b2011-06-23 00:49:38 +0000851 // FIXME: these are somewhat meaningless
852 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000853 DeclAccessPair fakeFoundDecl =
854 DeclAccessPair::make(field, field->getAccess());
855
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000856 result =
857 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
858 SourceLocation(), (FI == FEnd ? SS : EmptySS),
859 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000860 }
861
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000862 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000863}
864
John McCall5e77d762013-04-16 07:28:30 +0000865static ExprResult
866BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
867 const CXXScopeSpec &SS,
868 MSPropertyDecl *PD,
869 const DeclarationNameInfo &NameInfo) {
870 // Property names are always simple identifiers and therefore never
871 // require any interesting additional storage.
872 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
873 S.Context.PseudoObjectTy, VK_LValue,
874 SS.getWithLocInContext(S.Context),
875 NameInfo.getLoc());
876}
877
Douglas Gregor5476205b2011-06-23 00:49:38 +0000878/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000879static MemberExpr *BuildMemberExpr(
880 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
881 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
882 ValueDecl *Member, DeclAccessPair FoundDecl,
883 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
884 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000885 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000886 MemberExpr *E = MemberExpr::Create(
887 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
888 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000889 SemaRef.MarkMemberReferenced(E);
890 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000891}
892
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000893/// \brief Determine if the given scope is within a function-try-block handler.
894static bool IsInFnTryBlockHandler(const Scope *S) {
895 // Walk the scope stack until finding a FnTryCatchScope, or leave the
896 // function scope. If a FnTryCatchScope is found, check whether the TryScope
897 // flag is set. If it is not, it's a function-try-block handler.
898 for (; S != S->getFnParent(); S = S->getParent()) {
899 if (S->getFlags() & Scope::FnTryCatchScope)
900 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
901 }
902 return false;
903}
904
Douglas Gregor5476205b2011-06-23 00:49:38 +0000905ExprResult
906Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
907 SourceLocation OpLoc, bool IsArrow,
908 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000909 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000910 NamedDecl *FirstQualifierInScope,
911 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000912 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000913 const Scope *S,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000914 bool SuppressQualifierCheck,
915 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000916 QualType BaseType = BaseExprType;
917 if (IsArrow) {
918 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000919 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000920 }
921 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000922
923 LambdaScopeInfo *const CurLSI = getCurLambda();
924 // If this is an implicit member reference and the overloaded
925 // name refers to both static and non-static member functions
926 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
927 // check if we should/can capture 'this'...
928 // Keep this example in mind:
929 // struct X {
930 // void f(int) { }
931 // static void f(double) { }
932 //
933 // int g() {
934 // auto L = [=](auto a) {
935 // return [](int i) {
936 // return [=](auto b) {
937 // f(b);
938 // //f(decltype(a){});
939 // };
940 // };
941 // };
942 // auto M = L(0.0);
943 // auto N = M(3);
944 // N(5.32); // OK, must not error.
945 // return 0;
946 // }
947 // };
948 //
949 if (!BaseExpr && CurLSI) {
950 SourceLocation Loc = R.getNameLoc();
951 if (SS.getRange().isValid())
952 Loc = SS.getRange().getBegin();
953 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
954 // If the enclosing function is not dependent, then this lambda is
955 // capture ready, so if we can capture this, do so.
956 if (!EnclosingFunctionCtx->isDependentContext()) {
957 // If the current lambda and all enclosing lambdas can capture 'this' -
958 // then go ahead and capture 'this' (since our unresolved overload set
959 // contains both static and non-static member functions).
960 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
961 CheckCXXThisCapture(Loc);
962 } else if (CurContext->isDependentContext()) {
963 // ... since this is an implicit member reference, that might potentially
964 // involve a 'this' capture, mark 'this' for potential capture in
965 // enclosing lambdas.
966 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
967 CurLSI->addPotentialThisCapture(Loc);
968 }
969 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000970 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
971 DeclarationName MemberName = MemberNameInfo.getName();
972 SourceLocation MemberLoc = MemberNameInfo.getLoc();
973
974 if (R.isAmbiguous())
975 return ExprError();
976
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000977 // [except.handle]p10: Referring to any non-static member or base class of an
978 // object in the handler for a function-try-block of a constructor or
979 // destructor for that object results in undefined behavior.
980 const auto *FD = getCurFunctionDecl();
981 if (S && BaseExpr && FD &&
982 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
983 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
984 IsInFnTryBlockHandler(S))
985 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
986 << isa<CXXDestructorDecl>(FD);
987
Douglas Gregor5476205b2011-06-23 00:49:38 +0000988 if (R.empty()) {
989 // Rederive where we looked up.
990 DeclContext *DC = (SS.isSet()
991 ? computeDeclContext(SS, false)
992 : BaseType->getAs<RecordType>()->getDecl());
993
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000994 if (ExtraArgs) {
995 ExprResult RetryExpr;
996 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000997 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000998 ParsedType ObjectType;
999 bool MayBePseudoDestructor = false;
1000 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
1001 OpLoc, tok::arrow, ObjectType,
1002 MayBePseudoDestructor);
1003 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1004 CXXScopeSpec TempSS(SS);
1005 RetryExpr = ActOnMemberAccessExpr(
1006 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +00001007 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001008 }
1009 if (Trap.hasErrorOccurred())
1010 RetryExpr = ExprError();
1011 }
1012 if (RetryExpr.isUsable()) {
1013 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1014 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1015 return RetryExpr;
1016 }
1017 }
1018
Douglas Gregor5476205b2011-06-23 00:49:38 +00001019 Diag(R.getNameLoc(), diag::err_no_member)
1020 << MemberName << DC
1021 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1022 return ExprError();
1023 }
1024
1025 // Diagnose lookups that find only declarations from a non-base
1026 // type. This is possible for either qualified lookups (which may
1027 // have been qualified with an unrelated type) or implicit member
1028 // expressions (which were found with unqualified lookup and thus
1029 // may have come from an enclosing scope). Note that it's okay for
1030 // lookup to find declarations from a non-base type as long as those
1031 // aren't the ones picked by overload resolution.
1032 if ((SS.isSet() || !BaseExpr ||
1033 (isa<CXXThisExpr>(BaseExpr) &&
1034 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1035 !SuppressQualifierCheck &&
1036 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1037 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001038
Douglas Gregor5476205b2011-06-23 00:49:38 +00001039 // Construct an unresolved result if we in fact got an unresolved
1040 // result.
1041 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1042 // Suppress any lookup-related diagnostics; we'll do these when we
1043 // pick a member.
1044 R.suppressDiagnostics();
1045
1046 UnresolvedMemberExpr *MemExpr
1047 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1048 BaseExpr, BaseExprType,
1049 IsArrow, OpLoc,
1050 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001051 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001052 TemplateArgs, R.begin(), R.end());
1053
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001054 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001055 }
1056
1057 assert(R.isSingleResult());
1058 DeclAccessPair FoundDecl = R.begin().getPair();
1059 NamedDecl *MemberDecl = R.getFoundDecl();
1060
1061 // FIXME: diagnose the presence of template arguments now.
1062
1063 // If the decl being referenced had an error, return an error for this
1064 // sub-expr without emitting another error, in order to avoid cascading
1065 // error cases.
1066 if (MemberDecl->isInvalidDecl())
1067 return ExprError();
1068
1069 // Handle the implicit-member-access case.
1070 if (!BaseExpr) {
1071 // If this is not an instance member, convert to a non-member access.
1072 if (!MemberDecl->isCXXInstanceMember())
1073 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1074
1075 SourceLocation Loc = R.getNameLoc();
1076 if (SS.getRange().isValid())
1077 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001078 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001079 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1080 }
1081
Douglas Gregor5476205b2011-06-23 00:49:38 +00001082 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001083 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001084 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001085
Douglas Gregor5476205b2011-06-23 00:49:38 +00001086 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001087 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1088 FoundDecl, MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001089
John McCall5e77d762013-04-16 07:28:30 +00001090 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1091 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1092 MemberNameInfo);
1093
Douglas Gregor5476205b2011-06-23 00:49:38 +00001094 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1095 // We may have found a field within an anonymous union or struct
1096 // (C++ [class.union]).
1097 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001098 FoundDecl, BaseExpr,
1099 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001100
1101 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001102 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1103 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001104 Var->getType().getNonReferenceType(), VK_LValue,
1105 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001106 }
1107
1108 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1109 ExprValueKind valueKind;
1110 QualType type;
1111 if (MemberFn->isInstance()) {
1112 valueKind = VK_RValue;
1113 type = Context.BoundMemberTy;
1114 } else {
1115 valueKind = VK_LValue;
1116 type = MemberFn->getType();
1117 }
1118
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001119 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1120 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1121 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001122 }
1123 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1124
1125 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001126 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1127 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1128 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001129 }
1130
Douglas Gregor5476205b2011-06-23 00:49:38 +00001131 // We found something that we didn't expect. Complain.
1132 if (isa<TypeDecl>(MemberDecl))
1133 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1134 << MemberName << BaseType << int(IsArrow);
1135 else
1136 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1137 << MemberName << BaseType << int(IsArrow);
1138
1139 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1140 << MemberName;
1141 R.suppressDiagnostics();
1142 return ExprError();
1143}
1144
1145/// Given that normal member access failed on the given expression,
1146/// and given that the expression's type involves builtin-id or
1147/// builtin-Class, decide whether substituting in the redefinition
1148/// types would be profitable. The redefinition type is whatever
1149/// this translation unit tried to typedef to id/Class; we store
1150/// it to the side and then re-use it in places like this.
1151static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1152 const ObjCObjectPointerType *opty
1153 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1154 if (!opty) return false;
1155
1156 const ObjCObjectType *ty = opty->getObjectType();
1157
1158 QualType redef;
1159 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001160 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001161 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001162 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001163 } else {
1164 return false;
1165 }
1166
1167 // Do the substitution as long as the redefinition type isn't just a
1168 // possibly-qualified pointer to builtin-id or builtin-Class again.
1169 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001170 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001171 return false;
1172
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001173 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001174 return true;
1175}
1176
John McCall50a2c2c2011-10-11 23:14:30 +00001177static bool isRecordType(QualType T) {
1178 return T->isRecordType();
1179}
1180static bool isPointerToRecordType(QualType T) {
1181 if (const PointerType *PT = T->getAs<PointerType>())
1182 return PT->getPointeeType()->isRecordType();
1183 return false;
1184}
1185
Richard Smithcab9a7d2011-10-26 19:06:56 +00001186/// Perform conversions on the LHS of a member access expression.
1187ExprResult
1188Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001189 if (IsArrow && !Base->getType()->isFunctionType())
1190 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001191
Eli Friedman9a766c42012-01-13 02:20:01 +00001192 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001193}
1194
Douglas Gregor5476205b2011-06-23 00:49:38 +00001195/// Look up the given member of the given non-type-dependent
1196/// expression. This can return in one of two ways:
1197/// * If it returns a sentinel null-but-valid result, the caller will
1198/// assume that lookup was performed and the results written into
1199/// the provided structure. It will take over from there.
1200/// * Otherwise, the returned expression will be produced in place of
1201/// an ordinary member expression.
1202///
1203/// The ObjCImpDecl bit is a gross hack that will need to be properly
1204/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001205static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1206 ExprResult &BaseExpr, bool &IsArrow,
1207 SourceLocation OpLoc, CXXScopeSpec &SS,
1208 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001209 assert(BaseExpr.get() && "no base expression");
1210
1211 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001212 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001213 if (BaseExpr.isInvalid())
1214 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001215
Douglas Gregor5476205b2011-06-23 00:49:38 +00001216 QualType BaseType = BaseExpr.get()->getType();
1217 assert(!BaseType->isDependentType());
1218
1219 DeclarationName MemberName = R.getLookupName();
1220 SourceLocation MemberLoc = R.getNameLoc();
1221
1222 // For later type-checking purposes, turn arrow accesses into dot
1223 // accesses. The only access type we support that doesn't follow
1224 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1225 // and those never use arrows, so this is unaffected.
1226 if (IsArrow) {
1227 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1228 BaseType = Ptr->getPointeeType();
1229 else if (const ObjCObjectPointerType *Ptr
1230 = BaseType->getAs<ObjCObjectPointerType>())
1231 BaseType = Ptr->getPointeeType();
1232 else if (BaseType->isRecordType()) {
1233 // Recover from arrow accesses to records, e.g.:
1234 // struct MyRecord foo;
1235 // foo->bar
1236 // This is actually well-formed in C++ if MyRecord has an
1237 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001238 // by now--or a diagnostic message already issued if a problem
1239 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001240 if (!S.getLangOpts().CPlusPlus) {
1241 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001242 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1243 << FixItHint::CreateReplacement(OpLoc, ".");
1244 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001245 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001246 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001247 goto fail;
1248 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001249 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001250 << BaseType << BaseExpr.get()->getSourceRange();
1251 return ExprError();
1252 }
1253 }
1254
1255 // Handle field access to simple records.
1256 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001257 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001258 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001259 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001260 return ExprError();
1261
1262 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001263 // the lookup result was filled in. If typo correction was attempted and
1264 // failed, the lookup result will have been cleared--that combined with the
1265 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1266 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001267 }
1268
1269 // Handle ivar access to Objective-C objects.
1270 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001271 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001272 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001273 << 1 << SS.getScopeRep()
1274 << FixItHint::CreateRemoval(SS.getRange());
1275 SS.clear();
1276 }
Richard Smitha0edd302014-05-31 00:18:32 +00001277
Douglas Gregor5476205b2011-06-23 00:49:38 +00001278 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1279
1280 // There are three cases for the base type:
1281 // - builtin id (qualified or unqualified)
1282 // - builtin Class (qualified or unqualified)
1283 // - an interface
1284 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1285 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001286 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001287 (OTy->isObjCId() || OTy->isObjCClass()))
1288 goto fail;
1289 // There's an implicit 'isa' ivar on all objects.
1290 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001291 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001292 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001293 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1294 OpLoc, S.Context.getObjCClassType());
1295 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1296 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001297 ObjCImpDecl, HasTemplateArgs);
1298 goto fail;
1299 }
Richard Smitha0edd302014-05-31 00:18:32 +00001300
1301 if (S.RequireCompleteType(OpLoc, BaseType,
1302 diag::err_typecheck_incomplete_tag,
1303 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001304 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001305
1306 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001307 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1308
1309 if (!IV) {
1310 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001311 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1312 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001313 if (TypoCorrection Corrected = S.CorrectTypo(
1314 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001315 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001316 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001317 S.diagnoseTypo(
1318 Corrected,
1319 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1320 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001321
Ted Kremenek679b4782012-03-17 00:53:39 +00001322 // Figure out the class that declares the ivar.
1323 assert(!ClassDeclared);
1324 Decl *D = cast<Decl>(IV->getDeclContext());
1325 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1326 D = CAT->getClassInterface();
1327 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001328 } else {
Manman Ren5b786402016-01-28 18:49:28 +00001329 if (IsArrow &&
1330 IDecl->FindPropertyDeclaration(
1331 Member, ObjCPropertyQueryKind::OBJC_PR_query_instance)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001332 S.Diag(MemberLoc, diag::err_property_found_suggest)
1333 << Member << BaseExpr.get()->getType()
1334 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001335 return ExprError();
1336 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001337
Richard Smitha0edd302014-05-31 00:18:32 +00001338 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1339 << IDecl->getDeclName() << MemberName
1340 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001341 return ExprError();
1342 }
1343 }
Richard Smitha0edd302014-05-31 00:18:32 +00001344
Ted Kremenek679b4782012-03-17 00:53:39 +00001345 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001346
1347 // If the decl being referenced had an error, return an error for this
1348 // sub-expr without emitting another error, in order to avoid cascading
1349 // error cases.
1350 if (IV->isInvalidDecl())
1351 return ExprError();
1352
1353 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001354 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001355 return ExprError();
1356 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1357 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001358 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001359 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001360 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001361 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001362 // Case of a c-function declared inside an objc implementation.
1363 // FIXME: For a c-style function nested inside an objc implementation
1364 // class, there is no implementation context available, so we pass
1365 // down the context as argument to this routine. Ideally, this context
1366 // need be passed down in the AST node and somehow calculated from the
1367 // AST for a function decl.
1368 if (ObjCImplementationDecl *IMPD =
1369 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1370 ClassOfMethodDecl = IMPD->getClassInterface();
1371 else if (ObjCCategoryImplDecl* CatImplClass =
1372 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1373 ClassOfMethodDecl = CatImplClass->getClassInterface();
1374 }
Richard Smitha0edd302014-05-31 00:18:32 +00001375 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001376 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1377 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1378 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001379 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001380 << IV->getDeclName();
1381 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1382 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001383 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1384 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001385 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001386 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001387 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001388 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001389 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1390 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1391 if (UO->getOpcode() == UO_Deref)
1392 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1393
1394 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001395 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001396 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001397 warn = false;
1398 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001399 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001400 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001401 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001402 ObjCMethodFamily MF = MD->getMethodFamily();
1403 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001404 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001405 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001406 }
1407 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001408 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001409 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001410
Richard Smitha0edd302014-05-31 00:18:32 +00001411 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001412 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1413 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001414
Richard Smitha0edd302014-05-31 00:18:32 +00001415 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001416 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001417 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001418 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001419 }
1420 }
1421
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001422 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001423 }
1424
1425 // Objective-C property access.
1426 const ObjCObjectPointerType *OPT;
1427 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001428 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001429 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1430 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001431 SS.clear();
1432 }
1433
Douglas Gregor5476205b2011-06-23 00:49:38 +00001434 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001435 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001436 if (BaseExpr.isInvalid())
1437 return ExprError();
1438
Richard Smitha0edd302014-05-31 00:18:32 +00001439 assert(S.Context.hasSameUnqualifiedType(BaseType,
1440 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001441
1442 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1443
1444 const ObjCObjectType *OT = OPT->getObjectType();
1445
1446 // id, with and without qualifiers.
1447 if (OT->isObjCId()) {
1448 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001449 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1450 if (Decl *PMDecl =
1451 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001452 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1453 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001454 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001455 return ExprError();
1456
Richard Smitha0edd302014-05-31 00:18:32 +00001457 return new (S.Context)
1458 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001459 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001460 }
1461
1462 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1463 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001464 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001465 return ExprError();
1466 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001467 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1468 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001469 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001470 ObjCMethodDecl *SMD = nullptr;
1471 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001472 /*Property id*/ nullptr,
1473 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001474 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001475
1476 return new (S.Context)
1477 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001478 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001479 }
1480 }
1481 // Use of id.member can only be for a property reference. Do not
1482 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001483 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1484 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001485 ObjCImpDecl, HasTemplateArgs);
1486
Richard Smitha0edd302014-05-31 00:18:32 +00001487 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001488 << MemberName << BaseType);
1489 }
1490
1491 // 'Class', unqualified only.
1492 if (OT->isObjCClass()) {
1493 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001494 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001495 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001496 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1497 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001498 ObjCImpDecl, HasTemplateArgs);
1499
1500 goto fail;
1501 }
1502
1503 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001504 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001505 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1506 ObjCMethodDecl *Getter;
1507 if ((Getter = IFace->lookupClassMethod(Sel))) {
1508 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001509 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001510 return ExprError();
1511 } else
1512 Getter = IFace->lookupPrivateMethod(Sel, false);
1513 // If we found a getter then this may be a valid dot-reference, we
1514 // will look for the matching setter, in case it is needed.
1515 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001516 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1517 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001518 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001519 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1520 if (!Setter) {
1521 // If this reference is in an @implementation, also check for 'private'
1522 // methods.
1523 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1524 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001525
Richard Smitha0edd302014-05-31 00:18:32 +00001526 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001527 return ExprError();
1528
1529 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001530 return new (S.Context) ObjCPropertyRefExpr(
1531 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1532 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001533 }
1534
Richard Smitha0edd302014-05-31 00:18:32 +00001535 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1536 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001537 ObjCImpDecl, HasTemplateArgs);
1538
Richard Smitha0edd302014-05-31 00:18:32 +00001539 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001540 << MemberName << BaseType);
1541 }
1542
1543 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001544 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1545 MemberLoc, SourceLocation(), QualType(),
1546 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001547 }
1548
1549 // Handle 'field access' to vectors, such as 'V.xx'.
1550 if (BaseType->isExtVectorType()) {
1551 // FIXME: this expr should store IsArrow.
1552 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001553 ExprValueKind VK;
1554 if (IsArrow)
1555 VK = VK_LValue;
1556 else {
1557 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1558 VK = POE->getSyntacticForm()->getValueKind();
1559 else
1560 VK = BaseExpr.get()->getValueKind();
1561 }
Richard Smitha0edd302014-05-31 00:18:32 +00001562 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001563 Member, MemberLoc);
1564 if (ret.isNull())
1565 return ExprError();
1566
Richard Smitha0edd302014-05-31 00:18:32 +00001567 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001568 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001569 }
1570
1571 // Adjust builtin-sel to the appropriate redefinition type if that's
1572 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001573 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1574 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1575 BaseExpr = S.ImpCastExprToType(
1576 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1577 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001578 ObjCImpDecl, HasTemplateArgs);
1579 }
1580
1581 // Failure cases.
1582 fail:
1583
1584 // Recover from dot accesses to pointers, e.g.:
1585 // type *foo;
1586 // foo.bar
1587 // This is actually well-formed in two cases:
1588 // - 'type' is an Objective C type
1589 // - 'bar' is a pseudo-destructor name which happens to refer to
1590 // the appropriate pointer type
1591 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1592 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1593 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001594 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1595 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001596 << FixItHint::CreateReplacement(OpLoc, "->");
1597
1598 // Recurse as an -> access.
1599 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001600 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001601 ObjCImpDecl, HasTemplateArgs);
1602 }
1603 }
1604
1605 // If the user is trying to apply -> or . to a function name, it's probably
1606 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001607 if (S.tryToRecoverWithCall(
1608 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1609 /*complain*/ false,
1610 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001611 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001612 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001613 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1614 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001615 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001616 }
1617
Richard Smitha0edd302014-05-31 00:18:32 +00001618 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001619 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001620
1621 return ExprError();
1622}
1623
1624/// The main callback when the parser finds something like
1625/// expression . [nested-name-specifier] identifier
1626/// expression -> [nested-name-specifier] identifier
1627/// where 'identifier' encompasses a fairly broad spectrum of
1628/// possibilities, including destructor and operator references.
1629///
1630/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001631/// \param ObjCImpDecl the current Objective-C \@implementation
1632/// decl; this is an ugly hack around the fact that Objective-C
1633/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001634ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1635 SourceLocation OpLoc,
1636 tok::TokenKind OpKind,
1637 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001638 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001639 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001640 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001641 if (SS.isSet() && SS.isInvalid())
1642 return ExprError();
1643
1644 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001645 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001646 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1647 Diag(Id.getSourceRange().getBegin(),
1648 diag::ext_ms_explicit_constructor_call);
1649
1650 TemplateArgumentListInfo TemplateArgsBuffer;
1651
1652 // Decompose the name into its component parts.
1653 DeclarationNameInfo NameInfo;
1654 const TemplateArgumentListInfo *TemplateArgs;
1655 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1656 NameInfo, TemplateArgs);
1657
1658 DeclarationName Name = NameInfo.getName();
1659 bool IsArrow = (OpKind == tok::arrow);
1660
1661 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001662 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001663
1664 // This is a postfix expression, so get rid of ParenListExprs.
1665 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1666 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001667 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001668
1669 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1670 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001671 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1672 TemplateKWLoc, FirstQualifierInScope,
1673 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001674 }
1675
David Majnemerced8bdf2015-02-25 17:36:15 +00001676 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001677 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1678 TemplateKWLoc, FirstQualifierInScope,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001679 NameInfo, TemplateArgs, S, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001680}
1681
1682static ExprResult
1683BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001684 SourceLocation OpLoc, const CXXScopeSpec &SS,
1685 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001686 const DeclarationNameInfo &MemberNameInfo) {
1687 // x.a is an l-value if 'a' has a reference type. Otherwise:
1688 // x.a is an l-value/x-value/pr-value if the base is (and note
1689 // that *x is always an l-value), except that if the base isn't
1690 // an ordinary object then we must have an rvalue.
1691 ExprValueKind VK = VK_LValue;
1692 ExprObjectKind OK = OK_Ordinary;
1693 if (!IsArrow) {
1694 if (BaseExpr->getObjectKind() == OK_Ordinary)
1695 VK = BaseExpr->getValueKind();
1696 else
1697 VK = VK_RValue;
1698 }
1699 if (VK != VK_RValue && Field->isBitField())
1700 OK = OK_BitField;
1701
1702 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1703 QualType MemberType = Field->getType();
1704 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1705 MemberType = Ref->getPointeeType();
1706 VK = VK_LValue;
1707 } else {
1708 QualType BaseType = BaseExpr->getType();
1709 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001710
Douglas Gregor5476205b2011-06-23 00:49:38 +00001711 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001712
Douglas Gregor5476205b2011-06-23 00:49:38 +00001713 // GC attributes are never picked up by members.
1714 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001715
Douglas Gregor5476205b2011-06-23 00:49:38 +00001716 // CVR attributes from the base are picked up by members,
1717 // except that 'mutable' members don't pick up 'const'.
1718 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001719
Douglas Gregor5476205b2011-06-23 00:49:38 +00001720 Qualifiers MemberQuals
1721 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001722
Douglas Gregor5476205b2011-06-23 00:49:38 +00001723 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001724
1725
Douglas Gregor5476205b2011-06-23 00:49:38 +00001726 Qualifiers Combined = BaseQuals + MemberQuals;
1727 if (Combined != MemberQuals)
1728 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1729 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001730
Daniel Jasper0baec5492012-06-06 08:32:04 +00001731 S.UnusedPrivateFields.remove(Field);
1732
Douglas Gregor5476205b2011-06-23 00:49:38 +00001733 ExprResult Base =
1734 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1735 FoundDecl, Field);
1736 if (Base.isInvalid())
1737 return ExprError();
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001738 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001739 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1740 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001741}
1742
1743/// Builds an implicit member access expression. The current context
1744/// is known to be an instance method, and the given unqualified lookup
1745/// set is known to contain only instance members, at least one of which
1746/// is from an appropriate type.
1747ExprResult
1748Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001749 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001750 LookupResult &R,
1751 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001752 bool IsKnownInstance, const Scope *S) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001753 assert(!R.empty() && !R.isAmbiguous());
1754
1755 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001756
Douglas Gregor5476205b2011-06-23 00:49:38 +00001757 // If this is known to be an instance access, go ahead and build an
1758 // implicit 'this' expression now.
1759 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001760 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001761 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001762
1763 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001764 if (IsKnownInstance) {
1765 SourceLocation Loc = R.getNameLoc();
1766 if (SS.getRange().isValid())
1767 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001768 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001769 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1770 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001771
Douglas Gregor5476205b2011-06-23 00:49:38 +00001772 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1773 /*OpLoc*/ SourceLocation(),
1774 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001775 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001776 /*FirstQualifierInScope*/ nullptr,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001777 R, TemplateArgs, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001778}