blob: 94716b4a71ee402686ed4804a7dcfa256050b5c8 [file] [log] [blame]
Douglas Gregor5476205b2011-06-23 00:49:38 +00001//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis member access expressions.
11//
12//===----------------------------------------------------------------------===//
Kaelyn Takatafe408a72014-10-27 18:07:46 +000013#include "clang/Sema/Overload.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000014#include "clang/AST/ASTLambda.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000015#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "clang/Sema/SemaInternal.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000025
26using namespace clang;
27using namespace sema;
28
Richard Smithd80b2d52012-11-22 00:24:47 +000029typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
30static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
31 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
32 return !Bases.count(Base->getCanonicalDecl());
33}
34
Douglas Gregor5476205b2011-06-23 00:49:38 +000035/// Determines if the given class is provably not derived from all of
36/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000037static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
38 const BaseSet &Bases) {
39 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
40 return BaseIsNotInSet(Record, BasesPtr) &&
41 Record->forallBases(BaseIsNotInSet, BasesPtr);
Douglas Gregor5476205b2011-06-23 00:49:38 +000042}
43
44enum IMAKind {
45 /// The reference is definitely not an instance member access.
46 IMA_Static,
47
48 /// The reference may be an implicit instance member access.
49 IMA_Mixed,
50
Eli Friedman7bda7f72012-01-18 03:53:45 +000051 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000052 /// so, because the context is not an instance method.
53 IMA_Mixed_StaticContext,
54
55 /// The reference may be to an instance member, but it is invalid if
56 /// so, because the context is from an unrelated class.
57 IMA_Mixed_Unrelated,
58
59 /// The reference is definitely an implicit instance member access.
60 IMA_Instance,
61
62 /// The reference may be to an unresolved using declaration.
63 IMA_Unresolved,
64
John McCallf413f5e2013-05-03 00:10:13 +000065 /// The reference is a contextually-permitted abstract member reference.
66 IMA_Abstract,
67
Douglas Gregor5476205b2011-06-23 00:49:38 +000068 /// The reference may be to an unresolved using declaration and the
69 /// context is not an instance method.
70 IMA_Unresolved_StaticContext,
71
Eli Friedman456f0182012-01-20 01:26:23 +000072 // The reference refers to a field which is not a member of the containing
73 // class, which is allowed because we're in C++11 mode and the context is
74 // unevaluated.
75 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000076
Douglas Gregor5476205b2011-06-23 00:49:38 +000077 /// All possible referrents are instance members and the current
78 /// context is not an instance method.
79 IMA_Error_StaticContext,
80
81 /// All possible referrents are instance members of an unrelated
82 /// class.
83 IMA_Error_Unrelated
84};
85
86/// The given lookup names class member(s) and is not being used for
87/// an address-of-member expression. Classify the type of access
88/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000089/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000090/// conservatively answer "yes", in which case some errors will simply
91/// not be caught until template-instantiation.
92static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +000093 const LookupResult &R) {
94 assert(!R.empty() && (*R.begin())->isCXXClassMember());
95
96 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
97
Douglas Gregor3024f072012-04-16 07:05:22 +000098 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
99 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000100
101 if (R.isUnresolvableResult())
102 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
103
104 // Collect all the declaring classes of instance members we find.
105 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000106 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000107 BaseSet Classes;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000108 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
109 NamedDecl *D = *I;
110
111 if (D->isCXXInstanceMember()) {
Benjamin Kramera008d3a2015-04-10 11:37:55 +0000112 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
113 isa<IndirectFieldDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000114
115 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
116 Classes.insert(R->getCanonicalDecl());
117 }
118 else
119 hasNonInstance = true;
120 }
121
122 // If we didn't find any instance members, it can't be an implicit
123 // member reference.
124 if (Classes.empty())
125 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000126
127 // C++11 [expr.prim.general]p12:
128 // An id-expression that denotes a non-static data member or non-static
129 // member function of a class can only be used:
130 // (...)
131 // - if that id-expression denotes a non-static data member and it
132 // appears in an unevaluated operand.
133 //
134 // This rule is specific to C++11. However, we also permit this form
135 // in unevaluated inline assembly operands, like the operand to a SIZE.
136 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
137 assert(!AbstractInstanceResult);
138 switch (SemaRef.ExprEvalContexts.back().Context) {
139 case Sema::Unevaluated:
140 if (isField && SemaRef.getLangOpts().CPlusPlus11)
141 AbstractInstanceResult = IMA_Field_Uneval_Context;
142 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000143
John McCallf413f5e2013-05-03 00:10:13 +0000144 case Sema::UnevaluatedAbstract:
145 AbstractInstanceResult = IMA_Abstract;
146 break;
147
148 case Sema::ConstantEvaluated:
149 case Sema::PotentiallyEvaluated:
150 case Sema::PotentiallyEvaluatedIfUsed:
151 break;
Richard Smitheae99682012-02-25 10:04:07 +0000152 }
153
Douglas Gregor5476205b2011-06-23 00:49:38 +0000154 // If the current context is not an instance method, it can't be
155 // an implicit member reference.
156 if (isStaticContext) {
157 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000158 return IMA_Mixed_StaticContext;
159
John McCallf413f5e2013-05-03 00:10:13 +0000160 return AbstractInstanceResult ? AbstractInstanceResult
161 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000162 }
163
164 CXXRecordDecl *contextClass;
165 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
166 contextClass = MD->getParent()->getCanonicalDecl();
167 else
168 contextClass = cast<CXXRecordDecl>(DC);
169
170 // [class.mfct.non-static]p3:
171 // ...is used in the body of a non-static member function of class X,
172 // if name lookup (3.4.1) resolves the name in the id-expression to a
173 // non-static non-type member of some class C [...]
174 // ...if C is not X or a base class of X, the class member access expression
175 // is ill-formed.
176 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000177 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000178 R.getNamingClass()->getCanonicalDecl()) {
179 // If the naming class is not the current context, this was a qualified
180 // member name lookup, and it's sufficient to check that we have the naming
181 // class as a base class.
182 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000183 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000184 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000185
186 // If we can prove that the current context is unrelated to all the
187 // declaring classes, it can't be an implicit member reference (in
188 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000189 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000190 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000191 AbstractInstanceResult ? AbstractInstanceResult :
192 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000193
194 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
195}
196
197/// Diagnose a reference to a field with no object available.
Richard Smithfa0a1f52012-04-05 01:13:04 +0000198static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000199 const CXXScopeSpec &SS,
Richard Smithfa0a1f52012-04-05 01:13:04 +0000200 NamedDecl *Rep,
Eli Friedman456f0182012-01-20 01:26:23 +0000201 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000202 SourceLocation Loc = nameInfo.getLoc();
203 SourceRange Range(Loc);
204 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000205
Reid Klecknerae628962014-12-18 00:42:51 +0000206 // Look through using shadow decls and aliases.
207 Rep = Rep->getUnderlyingDecl();
208
Richard Smithfa0a1f52012-04-05 01:13:04 +0000209 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
210 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000211 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000212 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
213
214 bool InStaticMethod = Method && Method->isStatic();
215 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
216
217 if (IsField && InStaticMethod)
218 // "invalid use of member 'x' in static member function"
219 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
220 << Range << nameInfo.getName();
221 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
222 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
223 // Unqualified lookup in a non-static member function found a member of an
224 // enclosing class.
225 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
226 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
227 else if (IsField)
Eli Friedman456f0182012-01-20 01:26:23 +0000228 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000229 << nameInfo.getName() << Range;
230 else
231 SemaRef.Diag(Loc, diag::err_member_call_without_object)
232 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000233}
234
235/// Builds an expression which might be an implicit member expression.
236ExprResult
237Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000238 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000239 LookupResult &R,
240 const TemplateArgumentListInfo *TemplateArgs) {
Reid Klecknerae628962014-12-18 00:42:51 +0000241 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000242 case IMA_Instance:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000243 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000244
245 case IMA_Mixed:
246 case IMA_Mixed_Unrelated:
247 case IMA_Unresolved:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000248 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000249
Richard Smith2a986112012-02-25 10:20:59 +0000250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
253 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000254 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000255 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000256 case IMA_Mixed_StaticContext:
257 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000258 if (TemplateArgs || TemplateKWLoc.isValid())
259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000260 return BuildDeclarationNameExpr(SS, R, false);
261
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
Richard Smithfa0a1f52012-04-05 01:13:04 +0000264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000265 R.getLookupNameInfo());
266 return ExprError();
267 }
268
269 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000270}
271
272/// Check an ext-vector component access expression.
273///
274/// VK should be set in advance to the value kind of the base
275/// expression.
276static QualType
277CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
278 SourceLocation OpLoc, const IdentifierInfo *CompName,
279 SourceLocation CompLoc) {
280 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
281 // see FIXME there.
282 //
283 // FIXME: This logic can be greatly simplified by splitting it along
284 // halving/not halving and reworking the component checking.
285 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
286
287 // The vector accessor can't exceed the number of elements.
288 const char *compStr = CompName->getNameStart();
289
290 // This flag determines whether or not the component is one of the four
291 // special names that indicate a subset of exactly half the elements are
292 // to be selected.
293 bool HalvingSwizzle = false;
294
295 // This flag determines whether or not CompName has an 's' char prefix,
296 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000297 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000298
299 bool HasRepeated = false;
300 bool HasIndex[16] = {};
301
302 int Idx;
303
304 // Check that we've found one of the special components, or that the component
305 // names must come from the same set.
306 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
307 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
308 HalvingSwizzle = true;
309 } else if (!HexSwizzle &&
310 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
311 do {
312 if (HasIndex[Idx]) HasRepeated = true;
313 HasIndex[Idx] = true;
314 compStr++;
315 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
316 } else {
317 if (HexSwizzle) compStr++;
318 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
319 if (HasIndex[Idx]) HasRepeated = true;
320 HasIndex[Idx] = true;
321 compStr++;
322 }
323 }
324
325 if (!HalvingSwizzle && *compStr) {
326 // We didn't get to the end of the string. This means the component names
327 // didn't come from the same set *or* we encountered an illegal name.
328 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000329 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000330 return QualType();
331 }
332
333 // Ensure no component accessor exceeds the width of the vector type it
334 // operates on.
335 if (!HalvingSwizzle) {
336 compStr = CompName->getNameStart();
337
338 if (HexSwizzle)
339 compStr++;
340
341 while (*compStr) {
342 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
343 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
344 << baseType << SourceRange(CompLoc);
345 return QualType();
346 }
347 }
348 }
349
350 // The component accessor looks fine - now we need to compute the actual type.
351 // The vector type is implied by the component accessor. For example,
352 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
353 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
354 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
355 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
356 : CompName->getLength();
357 if (HexSwizzle)
358 CompSize--;
359
360 if (CompSize == 1)
361 return vecType->getElementType();
362
363 if (HasRepeated) VK = VK_RValue;
364
365 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
366 // Now look up the TypeDefDecl from the vector type. Without this,
367 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000368 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000369 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000370 E = S.ExtVectorDecls.end();
371 I != E; ++I) {
372 if ((*I)->getUnderlyingType() == VT)
373 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000374 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000375
Douglas Gregor5476205b2011-06-23 00:49:38 +0000376 return VT; // should never get here (a typedef type should always be found).
377}
378
379static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
380 IdentifierInfo *Member,
381 const Selector &Sel,
382 ASTContext &Context) {
383 if (Member)
384 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
385 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)
Aaron Ballman83731462014-03-17 16:14:00 +0000405 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000406 GDecl = PD;
407 break;
408 }
409 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000410 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000411 GDecl = OMD;
412 break;
413 }
414 }
415 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000416 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000417 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000418 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000419 if (GDecl)
420 return GDecl;
421 }
422 }
423 return GDecl;
424}
425
426ExprResult
427Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
428 bool IsArrow, SourceLocation OpLoc,
429 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000430 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000431 NamedDecl *FirstQualifierInScope,
432 const DeclarationNameInfo &NameInfo,
433 const TemplateArgumentListInfo *TemplateArgs) {
434 // Even in dependent contexts, try to diagnose base expressions with
435 // obviously wrong types, e.g.:
436 //
437 // T* t;
438 // t.f;
439 //
440 // In Obj-C++, however, the above expression is valid, since it could be
441 // accessing the 'f' property if T is an Obj-C interface. The extra check
442 // allows this, while still reporting an error if T is a struct pointer.
443 if (!IsArrow) {
444 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000445 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000446 PT->getPointeeType()->isRecordType())) {
447 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000448 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000449 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000450 return ExprError();
451 }
452 }
453
454 assert(BaseType->isDependentType() ||
455 NameInfo.getName().isDependentName() ||
456 isDependentScopeSpecifier(SS));
457
458 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
459 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000460 return CXXDependentScopeMemberExpr::Create(
461 Context, BaseExpr, BaseType, IsArrow, OpLoc,
462 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
463 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000464}
465
466/// We know that the given qualified member reference points only to
467/// declarations which do not belong to the static type of the base
468/// expression. Diagnose the problem.
469static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
470 Expr *BaseExpr,
471 QualType BaseType,
472 const CXXScopeSpec &SS,
473 NamedDecl *rep,
474 const DeclarationNameInfo &nameInfo) {
475 // If this is an implicit member access, use a different set of
476 // diagnostics.
477 if (!BaseExpr)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000478 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000479
480 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
481 << SS.getRange() << rep << BaseType;
482}
483
484// Check whether the declarations we found through a nested-name
485// specifier in a member expression are actually members of the base
486// type. The restriction here is:
487//
488// C++ [expr.ref]p2:
489// ... In these cases, the id-expression shall name a
490// member of the class or of one of its base classes.
491//
492// So it's perfectly legitimate for the nested-name specifier to name
493// an unrelated class, and for us to find an overload set including
494// decls from classes which are not superclasses, as long as the decl
495// we actually pick through overload resolution is from a superclass.
496bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
497 QualType BaseType,
498 const CXXScopeSpec &SS,
499 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000500 CXXRecordDecl *BaseRecord =
501 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
502 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000503 // We can't check this yet because the base type is still
504 // dependent.
505 assert(BaseType->isDependentType());
506 return false;
507 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000508
509 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
510 // If this is an implicit member reference and we find a
511 // non-instance member, it's not an error.
512 if (!BaseExpr && !(*I)->isCXXInstanceMember())
513 return false;
514
515 // Note that we use the DC of the decl, not the underlying decl.
516 DeclContext *DC = (*I)->getDeclContext();
517 while (DC->isTransparentContext())
518 DC = DC->getParent();
519
520 if (!DC->isRecord())
521 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000522
Richard Smithd80b2d52012-11-22 00:24:47 +0000523 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
524 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
525 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000526 return false;
527 }
528
529 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
530 R.getRepresentativeDecl(),
531 R.getLookupNameInfo());
532 return true;
533}
534
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000535namespace {
536
537// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000538// FunctionTemplateDecl and are declared in the current record or, for a C++
539// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000540class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000541public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000542 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000543 : Record(RTy->getDecl()) {
544 // Don't add bare keywords to the consumer since they will always fail
545 // validation by virtue of not being associated with any decls.
546 WantTypeSpecifiers = false;
547 WantExpressionKeywords = false;
548 WantCXXNamedCasts = false;
549 WantFunctionLikeCasts = false;
550 WantRemainingKeywords = false;
551 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000552
Craig Toppere14c0f82014-03-12 04:55:44 +0000553 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000554 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000555 // Don't accept candidates that cannot be member functions, constants,
556 // variables, or templates.
557 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
558 return false;
559
560 // Accept candidates that occur in the current record.
561 if (Record->containsDecl(ND))
562 return true;
563
564 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
565 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000566 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000567 if (const RecordType *BSTy =
568 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000569 if (BSTy->getDecl()->containsDecl(ND))
570 return true;
571 }
572 }
573 }
574
575 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000576 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000577
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000578private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000579 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000580};
581
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000582}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000583
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000584static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000585 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000586 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000587 SourceLocation OpLoc, bool IsArrow,
588 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000589 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000590 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000591 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000592 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
593 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000594 diag::err_typecheck_incomplete_tag,
595 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000596 return true;
597
598 if (HasTemplateArgs) {
599 // LookupTemplateName doesn't expect these both to exist simultaneously.
600 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
601
602 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000603 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000604 return false;
605 }
606
607 DeclContext *DC = RDecl;
608 if (SS.isSet()) {
609 // If the member name was a qualified-id, look into the
610 // nested-name-specifier.
611 DC = SemaRef.computeDeclContext(SS, false);
612
613 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
614 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000615 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000616 return true;
617 }
618
619 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
620
621 if (!isa<TypeDecl>(DC)) {
622 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000623 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000624 return true;
625 }
626 }
627
628 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000629 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000630
631 if (!R.empty())
632 return false;
633
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000634 DeclarationName Typo = R.getLookupName();
635 SourceLocation TypoLoc = R.getNameLoc();
636 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000637 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
638 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000639 [=, &SemaRef](const TypoCorrection &TC) {
640 if (TC) {
641 assert(!TC.isKeyword() &&
642 "Got a keyword as a correction for a member!");
643 bool DroppedSpecifier =
644 TC.WillReplaceSpecifier() &&
645 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
646 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
647 << Typo << DC << DroppedSpecifier
648 << SS.getRange());
649 } else {
650 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
651 }
652 },
653 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
654 R.clear(); // Ensure there's no decls lingering in the shared state.
655 R.suppressDiagnostics();
656 R.setLookupName(TC.getCorrection());
657 for (NamedDecl *ND : TC)
658 R.addDecl(ND);
659 R.resolveKind();
660 return SemaRef.BuildMemberReferenceExpr(
661 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
662 nullptr, R, nullptr);
663 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000664 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000665
666 return false;
667}
668
Richard Smitha0edd302014-05-31 00:18:32 +0000669static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
670 ExprResult &BaseExpr, bool &IsArrow,
671 SourceLocation OpLoc, CXXScopeSpec &SS,
672 Decl *ObjCImpDecl, bool HasTemplateArgs);
673
Douglas Gregor5476205b2011-06-23 00:49:38 +0000674ExprResult
675Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
676 SourceLocation OpLoc, bool IsArrow,
677 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000678 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000679 NamedDecl *FirstQualifierInScope,
680 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000681 const TemplateArgumentListInfo *TemplateArgs,
682 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000683 if (BaseType->isDependentType() ||
684 (SS.isSet() && isDependentScopeSpecifier(SS)))
685 return ActOnDependentMemberExpr(Base, BaseType,
686 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000687 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000688 NameInfo, TemplateArgs);
689
690 LookupResult R(*this, NameInfo, LookupMemberName);
691
692 // Implicit member accesses.
693 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000694 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000695 QualType RecordTy = BaseType;
696 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000697 if (LookupMemberExprInRecord(*this, R, nullptr,
698 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000699 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000700 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000701 if (TE)
702 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000703
704 // Explicit member accesses.
705 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000706 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000707 ExprResult Result = LookupMemberExpr(
708 *this, R, BaseResult, IsArrow, OpLoc, SS,
709 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
710 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000711
712 if (BaseResult.isInvalid())
713 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000714 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000715
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000716 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000717 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000718
719 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000720 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000721
722 // LookupMemberExpr can modify Base, and thus change BaseType
723 BaseType = Base->getType();
724 }
725
726 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000727 OpLoc, IsArrow, SS, TemplateKWLoc,
Richard Smitha0edd302014-05-31 00:18:32 +0000728 FirstQualifierInScope, R, TemplateArgs,
729 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000730}
731
732static ExprResult
733BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000734 SourceLocation OpLoc, const CXXScopeSpec &SS,
735 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000736 const DeclarationNameInfo &MemberNameInfo);
737
738ExprResult
739Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
740 SourceLocation loc,
741 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000742 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000743 Expr *baseObjectExpr,
744 SourceLocation opLoc) {
745 // First, build the expression that refers to the base object.
746
747 bool baseObjectIsPointer = false;
748 Qualifiers baseQuals;
749
750 // Case 1: the base of the indirect field is not a field.
751 VarDecl *baseVariable = indirectField->getVarDecl();
752 CXXScopeSpec EmptySS;
753 if (baseVariable) {
754 assert(baseVariable->getType()->isRecordType());
755
756 // In principle we could have a member access expression that
757 // accesses an anonymous struct/union that's a static member of
758 // the base object's class. However, under the current standard,
759 // static data members cannot be anonymous structs or unions.
760 // Supporting this is as easy as building a MemberExpr here.
761 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
762
763 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
764
765 ExprResult result
766 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
767 if (result.isInvalid()) return ExprError();
768
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000769 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000770 baseObjectIsPointer = false;
771 baseQuals = baseObjectExpr->getType().getQualifiers();
772
773 // Case 2: the base of the indirect field is a field and the user
774 // wrote a member expression.
775 } else if (baseObjectExpr) {
776 // The caller provided the base object expression. Determine
777 // whether its a pointer and whether it adds any qualifiers to the
778 // anonymous struct/union fields we're looking into.
779 QualType objectType = baseObjectExpr->getType();
780
781 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
782 baseObjectIsPointer = true;
783 objectType = ptr->getPointeeType();
784 } else {
785 baseObjectIsPointer = false;
786 }
787 baseQuals = objectType.getQualifiers();
788
789 // Case 3: the base of the indirect field is a field and we should
790 // build an implicit member access.
791 } else {
792 // We've found a member of an anonymous struct/union that is
793 // inside a non-anonymous struct/union, so in a well-formed
794 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000795 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000796 if (ThisTy.isNull()) {
797 Diag(loc, diag::err_invalid_member_use_in_static_method)
798 << indirectField->getDeclName();
799 return ExprError();
800 }
801
802 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000803 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000804 baseObjectExpr
805 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
806 baseObjectIsPointer = true;
807 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
808 }
809
810 // Build the implicit member references to the field of the
811 // anonymous struct/union.
812 Expr *result = baseObjectExpr;
813 IndirectFieldDecl::chain_iterator
814 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
815
816 // Build the first member access in the chain with full information.
817 if (!baseVariable) {
818 FieldDecl *field = cast<FieldDecl>(*FI);
819
Douglas Gregor5476205b2011-06-23 00:49:38 +0000820 // Make a nameInfo that properly uses the anonymous name.
821 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000822
Douglas Gregor5476205b2011-06-23 00:49:38 +0000823 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000824 SourceLocation(), EmptySS, field,
825 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000826 if (!result)
827 return ExprError();
828
Douglas Gregor5476205b2011-06-23 00:49:38 +0000829 // FIXME: check qualified member access
830 }
831
832 // In all cases, we should now skip the first declaration in the chain.
833 ++FI;
834
835 while (FI != FEnd) {
836 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000837
Douglas Gregor5476205b2011-06-23 00:49:38 +0000838 // FIXME: these are somewhat meaningless
839 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000840 DeclAccessPair fakeFoundDecl =
841 DeclAccessPair::make(field, field->getAccess());
842
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000843 result =
844 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
845 SourceLocation(), (FI == FEnd ? SS : EmptySS),
846 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000847 }
848
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000849 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000850}
851
John McCall5e77d762013-04-16 07:28:30 +0000852static ExprResult
853BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
854 const CXXScopeSpec &SS,
855 MSPropertyDecl *PD,
856 const DeclarationNameInfo &NameInfo) {
857 // Property names are always simple identifiers and therefore never
858 // require any interesting additional storage.
859 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
860 S.Context.PseudoObjectTy, VK_LValue,
861 SS.getWithLocInContext(S.Context),
862 NameInfo.getLoc());
863}
864
Douglas Gregor5476205b2011-06-23 00:49:38 +0000865/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000866static MemberExpr *BuildMemberExpr(
867 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
868 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
869 ValueDecl *Member, DeclAccessPair FoundDecl,
870 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
871 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000872 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000873 MemberExpr *E = MemberExpr::Create(
874 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
875 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000876 SemaRef.MarkMemberReferenced(E);
877 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000878}
879
880ExprResult
881Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
882 SourceLocation OpLoc, bool IsArrow,
883 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000884 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000885 NamedDecl *FirstQualifierInScope,
886 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000887 const TemplateArgumentListInfo *TemplateArgs,
888 bool SuppressQualifierCheck,
889 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000890 QualType BaseType = BaseExprType;
891 if (IsArrow) {
892 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000893 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000894 }
895 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000896
897 LambdaScopeInfo *const CurLSI = getCurLambda();
898 // If this is an implicit member reference and the overloaded
899 // name refers to both static and non-static member functions
900 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
901 // check if we should/can capture 'this'...
902 // Keep this example in mind:
903 // struct X {
904 // void f(int) { }
905 // static void f(double) { }
906 //
907 // int g() {
908 // auto L = [=](auto a) {
909 // return [](int i) {
910 // return [=](auto b) {
911 // f(b);
912 // //f(decltype(a){});
913 // };
914 // };
915 // };
916 // auto M = L(0.0);
917 // auto N = M(3);
918 // N(5.32); // OK, must not error.
919 // return 0;
920 // }
921 // };
922 //
923 if (!BaseExpr && CurLSI) {
924 SourceLocation Loc = R.getNameLoc();
925 if (SS.getRange().isValid())
926 Loc = SS.getRange().getBegin();
927 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
928 // If the enclosing function is not dependent, then this lambda is
929 // capture ready, so if we can capture this, do so.
930 if (!EnclosingFunctionCtx->isDependentContext()) {
931 // If the current lambda and all enclosing lambdas can capture 'this' -
932 // then go ahead and capture 'this' (since our unresolved overload set
933 // contains both static and non-static member functions).
934 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
935 CheckCXXThisCapture(Loc);
936 } else if (CurContext->isDependentContext()) {
937 // ... since this is an implicit member reference, that might potentially
938 // involve a 'this' capture, mark 'this' for potential capture in
939 // enclosing lambdas.
940 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
941 CurLSI->addPotentialThisCapture(Loc);
942 }
943 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000944 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
945 DeclarationName MemberName = MemberNameInfo.getName();
946 SourceLocation MemberLoc = MemberNameInfo.getLoc();
947
948 if (R.isAmbiguous())
949 return ExprError();
950
951 if (R.empty()) {
952 // Rederive where we looked up.
953 DeclContext *DC = (SS.isSet()
954 ? computeDeclContext(SS, false)
955 : BaseType->getAs<RecordType>()->getDecl());
956
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000957 if (ExtraArgs) {
958 ExprResult RetryExpr;
959 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000960 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000961 ParsedType ObjectType;
962 bool MayBePseudoDestructor = false;
963 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
964 OpLoc, tok::arrow, ObjectType,
965 MayBePseudoDestructor);
966 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
967 CXXScopeSpec TempSS(SS);
968 RetryExpr = ActOnMemberAccessExpr(
969 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +0000970 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000971 }
972 if (Trap.hasErrorOccurred())
973 RetryExpr = ExprError();
974 }
975 if (RetryExpr.isUsable()) {
976 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
977 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
978 return RetryExpr;
979 }
980 }
981
Douglas Gregor5476205b2011-06-23 00:49:38 +0000982 Diag(R.getNameLoc(), diag::err_no_member)
983 << MemberName << DC
984 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
985 return ExprError();
986 }
987
988 // Diagnose lookups that find only declarations from a non-base
989 // type. This is possible for either qualified lookups (which may
990 // have been qualified with an unrelated type) or implicit member
991 // expressions (which were found with unqualified lookup and thus
992 // may have come from an enclosing scope). Note that it's okay for
993 // lookup to find declarations from a non-base type as long as those
994 // aren't the ones picked by overload resolution.
995 if ((SS.isSet() || !BaseExpr ||
996 (isa<CXXThisExpr>(BaseExpr) &&
997 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
998 !SuppressQualifierCheck &&
999 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1000 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001001
Douglas Gregor5476205b2011-06-23 00:49:38 +00001002 // Construct an unresolved result if we in fact got an unresolved
1003 // result.
1004 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1005 // Suppress any lookup-related diagnostics; we'll do these when we
1006 // pick a member.
1007 R.suppressDiagnostics();
1008
1009 UnresolvedMemberExpr *MemExpr
1010 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1011 BaseExpr, BaseExprType,
1012 IsArrow, OpLoc,
1013 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001014 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001015 TemplateArgs, R.begin(), R.end());
1016
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001017 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001018 }
1019
1020 assert(R.isSingleResult());
1021 DeclAccessPair FoundDecl = R.begin().getPair();
1022 NamedDecl *MemberDecl = R.getFoundDecl();
1023
1024 // FIXME: diagnose the presence of template arguments now.
1025
1026 // If the decl being referenced had an error, return an error for this
1027 // sub-expr without emitting another error, in order to avoid cascading
1028 // error cases.
1029 if (MemberDecl->isInvalidDecl())
1030 return ExprError();
1031
1032 // Handle the implicit-member-access case.
1033 if (!BaseExpr) {
1034 // If this is not an instance member, convert to a non-member access.
1035 if (!MemberDecl->isCXXInstanceMember())
1036 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1037
1038 SourceLocation Loc = R.getNameLoc();
1039 if (SS.getRange().isValid())
1040 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001041 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001042 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1043 }
1044
Douglas Gregor5476205b2011-06-23 00:49:38 +00001045 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001046 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001047 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001048
Douglas Gregor5476205b2011-06-23 00:49:38 +00001049 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001050 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1051 FoundDecl, MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001052
John McCall5e77d762013-04-16 07:28:30 +00001053 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1054 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1055 MemberNameInfo);
1056
Douglas Gregor5476205b2011-06-23 00:49:38 +00001057 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1058 // We may have found a field within an anonymous union or struct
1059 // (C++ [class.union]).
1060 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001061 FoundDecl, BaseExpr,
1062 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001063
1064 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001065 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1066 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001067 Var->getType().getNonReferenceType(), VK_LValue,
1068 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001069 }
1070
1071 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1072 ExprValueKind valueKind;
1073 QualType type;
1074 if (MemberFn->isInstance()) {
1075 valueKind = VK_RValue;
1076 type = Context.BoundMemberTy;
1077 } else {
1078 valueKind = VK_LValue;
1079 type = MemberFn->getType();
1080 }
1081
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001082 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1083 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1084 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001085 }
1086 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1087
1088 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001089 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1090 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1091 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001092 }
1093
Douglas Gregor5476205b2011-06-23 00:49:38 +00001094 // We found something that we didn't expect. Complain.
1095 if (isa<TypeDecl>(MemberDecl))
1096 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1097 << MemberName << BaseType << int(IsArrow);
1098 else
1099 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1100 << MemberName << BaseType << int(IsArrow);
1101
1102 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1103 << MemberName;
1104 R.suppressDiagnostics();
1105 return ExprError();
1106}
1107
1108/// Given that normal member access failed on the given expression,
1109/// and given that the expression's type involves builtin-id or
1110/// builtin-Class, decide whether substituting in the redefinition
1111/// types would be profitable. The redefinition type is whatever
1112/// this translation unit tried to typedef to id/Class; we store
1113/// it to the side and then re-use it in places like this.
1114static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1115 const ObjCObjectPointerType *opty
1116 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1117 if (!opty) return false;
1118
1119 const ObjCObjectType *ty = opty->getObjectType();
1120
1121 QualType redef;
1122 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001123 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001124 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001125 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001126 } else {
1127 return false;
1128 }
1129
1130 // Do the substitution as long as the redefinition type isn't just a
1131 // possibly-qualified pointer to builtin-id or builtin-Class again.
1132 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001133 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001134 return false;
1135
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001136 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001137 return true;
1138}
1139
John McCall50a2c2c2011-10-11 23:14:30 +00001140static bool isRecordType(QualType T) {
1141 return T->isRecordType();
1142}
1143static bool isPointerToRecordType(QualType T) {
1144 if (const PointerType *PT = T->getAs<PointerType>())
1145 return PT->getPointeeType()->isRecordType();
1146 return false;
1147}
1148
Richard Smithcab9a7d2011-10-26 19:06:56 +00001149/// Perform conversions on the LHS of a member access expression.
1150ExprResult
1151Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001152 if (IsArrow && !Base->getType()->isFunctionType())
1153 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001154
Eli Friedman9a766c42012-01-13 02:20:01 +00001155 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001156}
1157
Douglas Gregor5476205b2011-06-23 00:49:38 +00001158/// Look up the given member of the given non-type-dependent
1159/// expression. This can return in one of two ways:
1160/// * If it returns a sentinel null-but-valid result, the caller will
1161/// assume that lookup was performed and the results written into
1162/// the provided structure. It will take over from there.
1163/// * Otherwise, the returned expression will be produced in place of
1164/// an ordinary member expression.
1165///
1166/// The ObjCImpDecl bit is a gross hack that will need to be properly
1167/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001168static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1169 ExprResult &BaseExpr, bool &IsArrow,
1170 SourceLocation OpLoc, CXXScopeSpec &SS,
1171 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001172 assert(BaseExpr.get() && "no base expression");
1173
1174 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001175 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001176 if (BaseExpr.isInvalid())
1177 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001178
Douglas Gregor5476205b2011-06-23 00:49:38 +00001179 QualType BaseType = BaseExpr.get()->getType();
1180 assert(!BaseType->isDependentType());
1181
1182 DeclarationName MemberName = R.getLookupName();
1183 SourceLocation MemberLoc = R.getNameLoc();
1184
1185 // For later type-checking purposes, turn arrow accesses into dot
1186 // accesses. The only access type we support that doesn't follow
1187 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1188 // and those never use arrows, so this is unaffected.
1189 if (IsArrow) {
1190 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1191 BaseType = Ptr->getPointeeType();
1192 else if (const ObjCObjectPointerType *Ptr
1193 = BaseType->getAs<ObjCObjectPointerType>())
1194 BaseType = Ptr->getPointeeType();
1195 else if (BaseType->isRecordType()) {
1196 // Recover from arrow accesses to records, e.g.:
1197 // struct MyRecord foo;
1198 // foo->bar
1199 // This is actually well-formed in C++ if MyRecord has an
1200 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001201 // by now--or a diagnostic message already issued if a problem
1202 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001203 if (!S.getLangOpts().CPlusPlus) {
1204 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001205 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1206 << FixItHint::CreateReplacement(OpLoc, ".");
1207 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001208 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001209 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001210 goto fail;
1211 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001212 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001213 << BaseType << BaseExpr.get()->getSourceRange();
1214 return ExprError();
1215 }
1216 }
1217
1218 // Handle field access to simple records.
1219 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001220 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001221 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001222 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001223 return ExprError();
1224
1225 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001226 // the lookup result was filled in. If typo correction was attempted and
1227 // failed, the lookup result will have been cleared--that combined with the
1228 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1229 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001230 }
1231
1232 // Handle ivar access to Objective-C objects.
1233 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001234 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001235 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001236 << 1 << SS.getScopeRep()
1237 << FixItHint::CreateRemoval(SS.getRange());
1238 SS.clear();
1239 }
Richard Smitha0edd302014-05-31 00:18:32 +00001240
Douglas Gregor5476205b2011-06-23 00:49:38 +00001241 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1242
1243 // There are three cases for the base type:
1244 // - builtin id (qualified or unqualified)
1245 // - builtin Class (qualified or unqualified)
1246 // - an interface
1247 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1248 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001249 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001250 (OTy->isObjCId() || OTy->isObjCClass()))
1251 goto fail;
1252 // There's an implicit 'isa' ivar on all objects.
1253 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001254 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001255 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001256 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1257 OpLoc, S.Context.getObjCClassType());
1258 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1259 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001260 ObjCImpDecl, HasTemplateArgs);
1261 goto fail;
1262 }
Richard Smitha0edd302014-05-31 00:18:32 +00001263
1264 if (S.RequireCompleteType(OpLoc, BaseType,
1265 diag::err_typecheck_incomplete_tag,
1266 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001267 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001268
1269 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001270 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1271
1272 if (!IV) {
1273 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001274 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1275 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001276 if (TypoCorrection Corrected = S.CorrectTypo(
1277 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001278 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001279 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001280 S.diagnoseTypo(
1281 Corrected,
1282 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1283 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001284
Ted Kremenek679b4782012-03-17 00:53:39 +00001285 // Figure out the class that declares the ivar.
1286 assert(!ClassDeclared);
1287 Decl *D = cast<Decl>(IV->getDeclContext());
1288 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1289 D = CAT->getClassInterface();
1290 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001291 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001292 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001293 S.Diag(MemberLoc, diag::err_property_found_suggest)
1294 << Member << BaseExpr.get()->getType()
1295 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001296 return ExprError();
1297 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001298
Richard Smitha0edd302014-05-31 00:18:32 +00001299 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1300 << IDecl->getDeclName() << MemberName
1301 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001302 return ExprError();
1303 }
1304 }
Richard Smitha0edd302014-05-31 00:18:32 +00001305
Ted Kremenek679b4782012-03-17 00:53:39 +00001306 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001307
1308 // If the decl being referenced had an error, return an error for this
1309 // sub-expr without emitting another error, in order to avoid cascading
1310 // error cases.
1311 if (IV->isInvalidDecl())
1312 return ExprError();
1313
1314 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001315 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001316 return ExprError();
1317 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1318 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001319 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001320 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001321 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001322 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001323 // Case of a c-function declared inside an objc implementation.
1324 // FIXME: For a c-style function nested inside an objc implementation
1325 // class, there is no implementation context available, so we pass
1326 // down the context as argument to this routine. Ideally, this context
1327 // need be passed down in the AST node and somehow calculated from the
1328 // AST for a function decl.
1329 if (ObjCImplementationDecl *IMPD =
1330 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1331 ClassOfMethodDecl = IMPD->getClassInterface();
1332 else if (ObjCCategoryImplDecl* CatImplClass =
1333 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1334 ClassOfMethodDecl = CatImplClass->getClassInterface();
1335 }
Richard Smitha0edd302014-05-31 00:18:32 +00001336 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001337 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1338 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1339 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001340 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001341 << IV->getDeclName();
1342 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1343 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001344 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1345 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001346 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001347 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001348 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001349 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001350 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1351 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1352 if (UO->getOpcode() == UO_Deref)
1353 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1354
1355 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001356 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001357 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001358 warn = false;
1359 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001360 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001361 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001362 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001363 ObjCMethodFamily MF = MD->getMethodFamily();
1364 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001365 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001366 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001367 }
1368 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001369 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001370 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001371
Richard Smitha0edd302014-05-31 00:18:32 +00001372 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001373 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1374 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001375
Richard Smitha0edd302014-05-31 00:18:32 +00001376 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001377 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001378 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001379 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001380 }
1381 }
1382
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001383 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001384 }
1385
1386 // Objective-C property access.
1387 const ObjCObjectPointerType *OPT;
1388 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001389 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001390 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1391 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001392 SS.clear();
1393 }
1394
Douglas Gregor5476205b2011-06-23 00:49:38 +00001395 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001396 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001397 if (BaseExpr.isInvalid())
1398 return ExprError();
1399
Richard Smitha0edd302014-05-31 00:18:32 +00001400 assert(S.Context.hasSameUnqualifiedType(BaseType,
1401 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001402
1403 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1404
1405 const ObjCObjectType *OT = OPT->getObjectType();
1406
1407 // id, with and without qualifiers.
1408 if (OT->isObjCId()) {
1409 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001410 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1411 if (Decl *PMDecl =
1412 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001413 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1414 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001415 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001416 return ExprError();
1417
Richard Smitha0edd302014-05-31 00:18:32 +00001418 return new (S.Context)
1419 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001420 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001421 }
1422
1423 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1424 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001425 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001426 return ExprError();
1427 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001428 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1429 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001430 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001431 ObjCMethodDecl *SMD = nullptr;
1432 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001433 /*Property id*/ nullptr,
1434 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001435 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001436
1437 return new (S.Context)
1438 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001439 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001440 }
1441 }
1442 // Use of id.member can only be for a property reference. Do not
1443 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001444 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1445 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001446 ObjCImpDecl, HasTemplateArgs);
1447
Richard Smitha0edd302014-05-31 00:18:32 +00001448 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001449 << MemberName << BaseType);
1450 }
1451
1452 // 'Class', unqualified only.
1453 if (OT->isObjCClass()) {
1454 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001455 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001456 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001457 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1458 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001459 ObjCImpDecl, HasTemplateArgs);
1460
1461 goto fail;
1462 }
1463
1464 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001465 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001466 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1467 ObjCMethodDecl *Getter;
1468 if ((Getter = IFace->lookupClassMethod(Sel))) {
1469 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001470 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001471 return ExprError();
1472 } else
1473 Getter = IFace->lookupPrivateMethod(Sel, false);
1474 // If we found a getter then this may be a valid dot-reference, we
1475 // will look for the matching setter, in case it is needed.
1476 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001477 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1478 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001479 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001480 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1481 if (!Setter) {
1482 // If this reference is in an @implementation, also check for 'private'
1483 // methods.
1484 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1485 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001486
Richard Smitha0edd302014-05-31 00:18:32 +00001487 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001488 return ExprError();
1489
1490 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001491 return new (S.Context) ObjCPropertyRefExpr(
1492 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1493 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001494 }
1495
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
Richard Smitha0edd302014-05-31 00:18:32 +00001500 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001501 << MemberName << BaseType);
1502 }
1503
1504 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001505 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1506 MemberLoc, SourceLocation(), QualType(),
1507 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001508 }
1509
1510 // Handle 'field access' to vectors, such as 'V.xx'.
1511 if (BaseType->isExtVectorType()) {
1512 // FIXME: this expr should store IsArrow.
1513 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001514 ExprValueKind VK;
1515 if (IsArrow)
1516 VK = VK_LValue;
1517 else {
1518 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1519 VK = POE->getSyntacticForm()->getValueKind();
1520 else
1521 VK = BaseExpr.get()->getValueKind();
1522 }
Richard Smitha0edd302014-05-31 00:18:32 +00001523 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001524 Member, MemberLoc);
1525 if (ret.isNull())
1526 return ExprError();
1527
Richard Smitha0edd302014-05-31 00:18:32 +00001528 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001529 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001530 }
1531
1532 // Adjust builtin-sel to the appropriate redefinition type if that's
1533 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001534 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1535 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1536 BaseExpr = S.ImpCastExprToType(
1537 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1538 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001539 ObjCImpDecl, HasTemplateArgs);
1540 }
1541
1542 // Failure cases.
1543 fail:
1544
1545 // Recover from dot accesses to pointers, e.g.:
1546 // type *foo;
1547 // foo.bar
1548 // This is actually well-formed in two cases:
1549 // - 'type' is an Objective C type
1550 // - 'bar' is a pseudo-destructor name which happens to refer to
1551 // the appropriate pointer type
1552 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1553 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1554 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001555 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1556 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001557 << FixItHint::CreateReplacement(OpLoc, "->");
1558
1559 // Recurse as an -> access.
1560 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001561 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001562 ObjCImpDecl, HasTemplateArgs);
1563 }
1564 }
1565
1566 // If the user is trying to apply -> or . to a function name, it's probably
1567 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001568 if (S.tryToRecoverWithCall(
1569 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1570 /*complain*/ false,
1571 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001572 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001573 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001574 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1575 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001576 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001577 }
1578
Richard Smitha0edd302014-05-31 00:18:32 +00001579 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001580 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001581
1582 return ExprError();
1583}
1584
1585/// The main callback when the parser finds something like
1586/// expression . [nested-name-specifier] identifier
1587/// expression -> [nested-name-specifier] identifier
1588/// where 'identifier' encompasses a fairly broad spectrum of
1589/// possibilities, including destructor and operator references.
1590///
1591/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001592/// \param ObjCImpDecl the current Objective-C \@implementation
1593/// decl; this is an ugly hack around the fact that Objective-C
1594/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001595ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1596 SourceLocation OpLoc,
1597 tok::TokenKind OpKind,
1598 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001599 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001600 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001601 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001602 if (SS.isSet() && SS.isInvalid())
1603 return ExprError();
1604
1605 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001606 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001607 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1608 Diag(Id.getSourceRange().getBegin(),
1609 diag::ext_ms_explicit_constructor_call);
1610
1611 TemplateArgumentListInfo TemplateArgsBuffer;
1612
1613 // Decompose the name into its component parts.
1614 DeclarationNameInfo NameInfo;
1615 const TemplateArgumentListInfo *TemplateArgs;
1616 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1617 NameInfo, TemplateArgs);
1618
1619 DeclarationName Name = NameInfo.getName();
1620 bool IsArrow = (OpKind == tok::arrow);
1621
1622 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001623 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001624
1625 // This is a postfix expression, so get rid of ParenListExprs.
1626 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1627 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001628 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001629
1630 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1631 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001632 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1633 TemplateKWLoc, FirstQualifierInScope,
1634 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001635 }
1636
David Majnemerced8bdf2015-02-25 17:36:15 +00001637 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001638 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1639 TemplateKWLoc, FirstQualifierInScope,
1640 NameInfo, TemplateArgs, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001641}
1642
1643static ExprResult
1644BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001645 SourceLocation OpLoc, const CXXScopeSpec &SS,
1646 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001647 const DeclarationNameInfo &MemberNameInfo) {
1648 // x.a is an l-value if 'a' has a reference type. Otherwise:
1649 // x.a is an l-value/x-value/pr-value if the base is (and note
1650 // that *x is always an l-value), except that if the base isn't
1651 // an ordinary object then we must have an rvalue.
1652 ExprValueKind VK = VK_LValue;
1653 ExprObjectKind OK = OK_Ordinary;
1654 if (!IsArrow) {
1655 if (BaseExpr->getObjectKind() == OK_Ordinary)
1656 VK = BaseExpr->getValueKind();
1657 else
1658 VK = VK_RValue;
1659 }
1660 if (VK != VK_RValue && Field->isBitField())
1661 OK = OK_BitField;
1662
1663 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1664 QualType MemberType = Field->getType();
1665 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1666 MemberType = Ref->getPointeeType();
1667 VK = VK_LValue;
1668 } else {
1669 QualType BaseType = BaseExpr->getType();
1670 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001671
Douglas Gregor5476205b2011-06-23 00:49:38 +00001672 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001673
Douglas Gregor5476205b2011-06-23 00:49:38 +00001674 // GC attributes are never picked up by members.
1675 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001676
Douglas Gregor5476205b2011-06-23 00:49:38 +00001677 // CVR attributes from the base are picked up by members,
1678 // except that 'mutable' members don't pick up 'const'.
1679 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001680
Douglas Gregor5476205b2011-06-23 00:49:38 +00001681 Qualifiers MemberQuals
1682 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001683
Douglas Gregor5476205b2011-06-23 00:49:38 +00001684 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001685
1686
Douglas Gregor5476205b2011-06-23 00:49:38 +00001687 Qualifiers Combined = BaseQuals + MemberQuals;
1688 if (Combined != MemberQuals)
1689 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1690 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001691
Daniel Jasper0baec5492012-06-06 08:32:04 +00001692 S.UnusedPrivateFields.remove(Field);
1693
Douglas Gregor5476205b2011-06-23 00:49:38 +00001694 ExprResult Base =
1695 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1696 FoundDecl, Field);
1697 if (Base.isInvalid())
1698 return ExprError();
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001699 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001700 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1701 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001702}
1703
1704/// Builds an implicit member access expression. The current context
1705/// is known to be an instance method, and the given unqualified lookup
1706/// set is known to contain only instance members, at least one of which
1707/// is from an appropriate type.
1708ExprResult
1709Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001710 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001711 LookupResult &R,
1712 const TemplateArgumentListInfo *TemplateArgs,
1713 bool IsKnownInstance) {
1714 assert(!R.empty() && !R.isAmbiguous());
1715
1716 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001717
Douglas Gregor5476205b2011-06-23 00:49:38 +00001718 // If this is known to be an instance access, go ahead and build an
1719 // implicit 'this' expression now.
1720 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001721 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001722 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001723
1724 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001725 if (IsKnownInstance) {
1726 SourceLocation Loc = R.getNameLoc();
1727 if (SS.getRange().isValid())
1728 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001729 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001730 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1731 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001732
Douglas Gregor5476205b2011-06-23 00:49:38 +00001733 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1734 /*OpLoc*/ SourceLocation(),
1735 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001736 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001737 /*FirstQualifierInScope*/ nullptr,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001738 R, TemplateArgs);
1739}