blob: 3256bd986ff2519b9aada104250e3ee2a2e0406a [file] [log] [blame]
Douglas Gregor5476205b2011-06-23 00:49:38 +00001//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis member access expressions.
11//
12//===----------------------------------------------------------------------===//
Kaelyn Takatafe408a72014-10-27 18:07:46 +000013#include "clang/Sema/Overload.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000014#include "clang/AST/ASTLambda.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000015#include "clang/AST/DeclCXX.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/AST/DeclTemplate.h"
18#include "clang/AST/ExprCXX.h"
19#include "clang/AST/ExprObjC.h"
20#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
23#include "clang/Sema/ScopeInfo.h"
Chandler Carruth0d9593d2015-01-14 11:29:14 +000024#include "clang/Sema/SemaInternal.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000025
26using namespace clang;
27using namespace sema;
28
Richard Smithd80b2d52012-11-22 00:24:47 +000029typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
Richard Smithd80b2d52012-11-22 00:24:47 +000030
Douglas Gregor5476205b2011-06-23 00:49:38 +000031/// Determines if the given class is provably not derived from all of
32/// the prospective base classes.
Richard Smithd80b2d52012-11-22 00:24:47 +000033static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
34 const BaseSet &Bases) {
Benjamin Kramer6e4f6e12015-07-25 15:07:25 +000035 auto BaseIsNotInSet = [&Bases](const CXXRecordDecl *Base) {
36 return !Bases.count(Base->getCanonicalDecl());
37 };
38 return BaseIsNotInSet(Record) && Record->forallBases(BaseIsNotInSet);
Douglas Gregor5476205b2011-06-23 00:49:38 +000039}
40
41enum IMAKind {
42 /// The reference is definitely not an instance member access.
43 IMA_Static,
44
45 /// The reference may be an implicit instance member access.
46 IMA_Mixed,
47
Eli Friedman7bda7f72012-01-18 03:53:45 +000048 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor5476205b2011-06-23 00:49:38 +000049 /// so, because the context is not an instance method.
50 IMA_Mixed_StaticContext,
51
52 /// The reference may be to an instance member, but it is invalid if
53 /// so, because the context is from an unrelated class.
54 IMA_Mixed_Unrelated,
55
56 /// The reference is definitely an implicit instance member access.
57 IMA_Instance,
58
59 /// The reference may be to an unresolved using declaration.
60 IMA_Unresolved,
61
John McCallf413f5e2013-05-03 00:10:13 +000062 /// The reference is a contextually-permitted abstract member reference.
63 IMA_Abstract,
64
Douglas Gregor5476205b2011-06-23 00:49:38 +000065 /// The reference may be to an unresolved using declaration and the
66 /// context is not an instance method.
67 IMA_Unresolved_StaticContext,
68
Eli Friedman456f0182012-01-20 01:26:23 +000069 // The reference refers to a field which is not a member of the containing
70 // class, which is allowed because we're in C++11 mode and the context is
71 // unevaluated.
72 IMA_Field_Uneval_Context,
Eli Friedman7bda7f72012-01-18 03:53:45 +000073
Douglas Gregor5476205b2011-06-23 00:49:38 +000074 /// All possible referrents are instance members and the current
75 /// context is not an instance method.
76 IMA_Error_StaticContext,
77
78 /// All possible referrents are instance members of an unrelated
79 /// class.
80 IMA_Error_Unrelated
81};
82
83/// The given lookup names class member(s) and is not being used for
84/// an address-of-member expression. Classify the type of access
85/// according to whether it's possible that this reference names an
Eli Friedman7bda7f72012-01-18 03:53:45 +000086/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor5476205b2011-06-23 00:49:38 +000087/// conservatively answer "yes", in which case some errors will simply
88/// not be caught until template-instantiation.
89static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +000090 const LookupResult &R) {
91 assert(!R.empty() && (*R.begin())->isCXXClassMember());
92
93 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
94
Douglas Gregor3024f072012-04-16 07:05:22 +000095 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
96 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +000097
98 if (R.isUnresolvableResult())
99 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
100
101 // Collect all the declaring classes of instance members we find.
102 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000103 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000104 BaseSet Classes;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000105 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
106 NamedDecl *D = *I;
107
108 if (D->isCXXInstanceMember()) {
Benjamin Kramera008d3a2015-04-10 11:37:55 +0000109 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
110 isa<IndirectFieldDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000111
112 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
113 Classes.insert(R->getCanonicalDecl());
114 }
115 else
116 hasNonInstance = true;
117 }
118
119 // If we didn't find any instance members, it can't be an implicit
120 // member reference.
121 if (Classes.empty())
122 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000123
124 // C++11 [expr.prim.general]p12:
125 // An id-expression that denotes a non-static data member or non-static
126 // member function of a class can only be used:
127 // (...)
128 // - if that id-expression denotes a non-static data member and it
129 // appears in an unevaluated operand.
130 //
131 // This rule is specific to C++11. However, we also permit this form
132 // in unevaluated inline assembly operands, like the operand to a SIZE.
133 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
134 assert(!AbstractInstanceResult);
135 switch (SemaRef.ExprEvalContexts.back().Context) {
136 case Sema::Unevaluated:
137 if (isField && SemaRef.getLangOpts().CPlusPlus11)
138 AbstractInstanceResult = IMA_Field_Uneval_Context;
139 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000140
John McCallf413f5e2013-05-03 00:10:13 +0000141 case Sema::UnevaluatedAbstract:
142 AbstractInstanceResult = IMA_Abstract;
143 break;
144
145 case Sema::ConstantEvaluated:
146 case Sema::PotentiallyEvaluated:
147 case Sema::PotentiallyEvaluatedIfUsed:
148 break;
Richard Smitheae99682012-02-25 10:04:07 +0000149 }
150
Douglas Gregor5476205b2011-06-23 00:49:38 +0000151 // If the current context is not an instance method, it can't be
152 // an implicit member reference.
153 if (isStaticContext) {
154 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000155 return IMA_Mixed_StaticContext;
156
John McCallf413f5e2013-05-03 00:10:13 +0000157 return AbstractInstanceResult ? AbstractInstanceResult
158 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000159 }
160
161 CXXRecordDecl *contextClass;
162 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
163 contextClass = MD->getParent()->getCanonicalDecl();
164 else
165 contextClass = cast<CXXRecordDecl>(DC);
166
167 // [class.mfct.non-static]p3:
168 // ...is used in the body of a non-static member function of class X,
169 // if name lookup (3.4.1) resolves the name in the id-expression to a
170 // non-static non-type member of some class C [...]
171 // ...if C is not X or a base class of X, the class member access expression
172 // is ill-formed.
173 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000174 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000175 R.getNamingClass()->getCanonicalDecl()) {
176 // If the naming class is not the current context, this was a qualified
177 // member name lookup, and it's sufficient to check that we have the naming
178 // class as a base class.
179 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000180 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000181 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000182
183 // If we can prove that the current context is unrelated to all the
184 // declaring classes, it can't be an implicit member reference (in
185 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000186 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000187 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000188 AbstractInstanceResult ? AbstractInstanceResult :
189 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000190
191 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
192}
193
194/// Diagnose a reference to a field with no object available.
Reid Klecknerf438a022015-10-17 00:19:04 +0000195void Sema::DiagnoseInstanceReference(const CXXScopeSpec &SS, NamedDecl *Rep,
196 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000197 SourceLocation Loc = nameInfo.getLoc();
198 SourceRange Range(Loc);
199 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000200
Reid Klecknerae628962014-12-18 00:42:51 +0000201 // Look through using shadow decls and aliases.
202 Rep = Rep->getUnderlyingDecl();
203
Reid Klecknerf438a022015-10-17 00:19:04 +0000204 DeclContext *FunctionLevelDC = getFunctionLevelDeclContext();
Richard Smithfa0a1f52012-04-05 01:13:04 +0000205 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000206 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000207 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
208
209 bool InStaticMethod = Method && Method->isStatic();
210 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
211
212 if (IsField && InStaticMethod)
213 // "invalid use of member 'x' in static member function"
Reid Klecknerf438a022015-10-17 00:19:04 +0000214 Diag(Loc, diag::err_invalid_member_use_in_static_method)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000215 << Range << nameInfo.getName();
216 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
217 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
218 // Unqualified lookup in a non-static member function found a member of an
219 // enclosing class.
Reid Klecknerf438a022015-10-17 00:19:04 +0000220 Diag(Loc, diag::err_nested_non_static_member_use)
221 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000222 else if (IsField)
Reid Klecknerf438a022015-10-17 00:19:04 +0000223 Diag(Loc, diag::err_invalid_non_static_member_use) << nameInfo.getName()
224 << Range;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000225 else
Reid Klecknerf438a022015-10-17 00:19:04 +0000226 Diag(Loc, diag::err_member_call_without_object) << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000227}
228
229/// Builds an expression which might be an implicit member expression.
230ExprResult
231Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000232 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000233 LookupResult &R,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000234 const TemplateArgumentListInfo *TemplateArgs,
235 const Scope *S) {
Reid Klecknerae628962014-12-18 00:42:51 +0000236 switch (ClassifyImplicitMemberAccess(*this, R)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000237 case IMA_Instance:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000238 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000239
240 case IMA_Mixed:
241 case IMA_Mixed_Unrelated:
242 case IMA_Unresolved:
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000243 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
244 S);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000245
Richard Smith2a986112012-02-25 10:20:59 +0000246 case IMA_Field_Uneval_Context:
247 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
248 << R.getLookupNameInfo().getName();
249 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000250 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000251 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000252 case IMA_Mixed_StaticContext:
253 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000254 if (TemplateArgs || TemplateKWLoc.isValid())
255 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000256 return BuildDeclarationNameExpr(SS, R, false);
257
258 case IMA_Error_StaticContext:
259 case IMA_Error_Unrelated:
Reid Klecknerf438a022015-10-17 00:19:04 +0000260 DiagnoseInstanceReference(SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000261 R.getLookupNameInfo());
262 return ExprError();
263 }
264
265 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000266}
267
268/// Check an ext-vector component access expression.
269///
270/// VK should be set in advance to the value kind of the base
271/// expression.
272static QualType
273CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
274 SourceLocation OpLoc, const IdentifierInfo *CompName,
275 SourceLocation CompLoc) {
276 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
277 // see FIXME there.
278 //
279 // FIXME: This logic can be greatly simplified by splitting it along
280 // halving/not halving and reworking the component checking.
281 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
282
283 // The vector accessor can't exceed the number of elements.
284 const char *compStr = CompName->getNameStart();
285
286 // This flag determines whether or not the component is one of the four
287 // special names that indicate a subset of exactly half the elements are
288 // to be selected.
289 bool HalvingSwizzle = false;
290
291 // This flag determines whether or not CompName has an 's' char prefix,
292 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000293 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000294
295 bool HasRepeated = false;
296 bool HasIndex[16] = {};
297
298 int Idx;
299
300 // Check that we've found one of the special components, or that the component
301 // names must come from the same set.
302 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
303 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
304 HalvingSwizzle = true;
305 } else if (!HexSwizzle &&
306 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
307 do {
308 if (HasIndex[Idx]) HasRepeated = true;
309 HasIndex[Idx] = true;
310 compStr++;
311 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
312 } else {
313 if (HexSwizzle) compStr++;
314 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
315 if (HasIndex[Idx]) HasRepeated = true;
316 HasIndex[Idx] = true;
317 compStr++;
318 }
319 }
320
321 if (!HalvingSwizzle && *compStr) {
322 // We didn't get to the end of the string. This means the component names
323 // didn't come from the same set *or* we encountered an illegal name.
324 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000325 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000326 return QualType();
327 }
328
329 // Ensure no component accessor exceeds the width of the vector type it
330 // operates on.
331 if (!HalvingSwizzle) {
332 compStr = CompName->getNameStart();
333
334 if (HexSwizzle)
335 compStr++;
336
337 while (*compStr) {
338 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
339 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
340 << baseType << SourceRange(CompLoc);
341 return QualType();
342 }
343 }
344 }
345
346 // The component accessor looks fine - now we need to compute the actual type.
347 // The vector type is implied by the component accessor. For example,
348 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
349 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
350 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
351 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
352 : CompName->getLength();
353 if (HexSwizzle)
354 CompSize--;
355
356 if (CompSize == 1)
357 return vecType->getElementType();
358
359 if (HasRepeated) VK = VK_RValue;
360
361 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
362 // Now look up the TypeDefDecl from the vector type. Without this,
363 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000364 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000365 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000366 E = S.ExtVectorDecls.end();
367 I != E; ++I) {
368 if ((*I)->getUnderlyingType() == VT)
369 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000370 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000371
Douglas Gregor5476205b2011-06-23 00:49:38 +0000372 return VT; // should never get here (a typedef type should always be found).
373}
374
375static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
376 IdentifierInfo *Member,
377 const Selector &Sel,
378 ASTContext &Context) {
379 if (Member)
380 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
381 return PD;
382 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
383 return OMD;
384
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000385 for (const auto *I : PDecl->protocols()) {
386 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000387 Context))
388 return D;
389 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000390 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000391}
392
393static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
394 IdentifierInfo *Member,
395 const Selector &Sel,
396 ASTContext &Context) {
397 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000398 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000399 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000400 if (Member)
Aaron Ballman83731462014-03-17 16:14:00 +0000401 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000402 GDecl = PD;
403 break;
404 }
405 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000406 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000407 GDecl = OMD;
408 break;
409 }
410 }
411 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000412 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000413 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000414 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000415 if (GDecl)
416 return GDecl;
417 }
418 }
419 return GDecl;
420}
421
422ExprResult
423Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
424 bool IsArrow, SourceLocation OpLoc,
425 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000426 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000427 NamedDecl *FirstQualifierInScope,
428 const DeclarationNameInfo &NameInfo,
429 const TemplateArgumentListInfo *TemplateArgs) {
430 // Even in dependent contexts, try to diagnose base expressions with
431 // obviously wrong types, e.g.:
432 //
433 // T* t;
434 // t.f;
435 //
436 // In Obj-C++, however, the above expression is valid, since it could be
437 // accessing the 'f' property if T is an Obj-C interface. The extra check
438 // allows this, while still reporting an error if T is a struct pointer.
439 if (!IsArrow) {
440 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000441 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000442 PT->getPointeeType()->isRecordType())) {
443 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000444 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000445 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000446 return ExprError();
447 }
448 }
449
450 assert(BaseType->isDependentType() ||
451 NameInfo.getName().isDependentName() ||
452 isDependentScopeSpecifier(SS));
453
454 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
455 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000456 return CXXDependentScopeMemberExpr::Create(
457 Context, BaseExpr, BaseType, IsArrow, OpLoc,
458 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
459 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000460}
461
462/// We know that the given qualified member reference points only to
463/// declarations which do not belong to the static type of the base
464/// expression. Diagnose the problem.
465static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
466 Expr *BaseExpr,
467 QualType BaseType,
468 const CXXScopeSpec &SS,
469 NamedDecl *rep,
470 const DeclarationNameInfo &nameInfo) {
471 // If this is an implicit member access, use a different set of
472 // diagnostics.
473 if (!BaseExpr)
Reid Klecknerf438a022015-10-17 00:19:04 +0000474 return SemaRef.DiagnoseInstanceReference(SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000475
476 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
477 << SS.getRange() << rep << BaseType;
478}
479
480// Check whether the declarations we found through a nested-name
481// specifier in a member expression are actually members of the base
482// type. The restriction here is:
483//
484// C++ [expr.ref]p2:
485// ... In these cases, the id-expression shall name a
486// member of the class or of one of its base classes.
487//
488// So it's perfectly legitimate for the nested-name specifier to name
489// an unrelated class, and for us to find an overload set including
490// decls from classes which are not superclasses, as long as the decl
491// we actually pick through overload resolution is from a superclass.
492bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
493 QualType BaseType,
494 const CXXScopeSpec &SS,
495 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000496 CXXRecordDecl *BaseRecord =
497 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
498 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000499 // We can't check this yet because the base type is still
500 // dependent.
501 assert(BaseType->isDependentType());
502 return false;
503 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000504
505 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
506 // If this is an implicit member reference and we find a
507 // non-instance member, it's not an error.
508 if (!BaseExpr && !(*I)->isCXXInstanceMember())
509 return false;
510
511 // Note that we use the DC of the decl, not the underlying decl.
512 DeclContext *DC = (*I)->getDeclContext();
513 while (DC->isTransparentContext())
514 DC = DC->getParent();
515
516 if (!DC->isRecord())
517 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000518
Richard Smithd80b2d52012-11-22 00:24:47 +0000519 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
520 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
521 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000522 return false;
523 }
524
525 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
526 R.getRepresentativeDecl(),
527 R.getLookupNameInfo());
528 return true;
529}
530
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000531namespace {
532
533// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000534// FunctionTemplateDecl and are declared in the current record or, for a C++
535// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000536class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000537public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000538 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000539 : Record(RTy->getDecl()) {
540 // Don't add bare keywords to the consumer since they will always fail
541 // validation by virtue of not being associated with any decls.
542 WantTypeSpecifiers = false;
543 WantExpressionKeywords = false;
544 WantCXXNamedCasts = false;
545 WantFunctionLikeCasts = false;
546 WantRemainingKeywords = false;
547 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000548
Craig Toppere14c0f82014-03-12 04:55:44 +0000549 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000550 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000551 // Don't accept candidates that cannot be member functions, constants,
552 // variables, or templates.
553 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
554 return false;
555
556 // Accept candidates that occur in the current record.
557 if (Record->containsDecl(ND))
558 return true;
559
560 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
561 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000562 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000563 if (const RecordType *BSTy =
564 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000565 if (BSTy->getDecl()->containsDecl(ND))
566 return true;
567 }
568 }
569 }
570
571 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000572 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000573
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000574private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000575 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000576};
577
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000578}
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000579
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000580static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000581 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000582 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000583 SourceLocation OpLoc, bool IsArrow,
584 CXXScopeSpec &SS, bool HasTemplateArgs,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000585 TypoExpr *&TE) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000586 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000587 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000588 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
589 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000590 diag::err_typecheck_incomplete_tag,
591 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000592 return true;
593
594 if (HasTemplateArgs) {
595 // LookupTemplateName doesn't expect these both to exist simultaneously.
596 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
597
598 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000599 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000600 return false;
601 }
602
603 DeclContext *DC = RDecl;
604 if (SS.isSet()) {
605 // If the member name was a qualified-id, look into the
606 // nested-name-specifier.
607 DC = SemaRef.computeDeclContext(SS, false);
608
609 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
610 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000611 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000612 return true;
613 }
614
615 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
616
617 if (!isa<TypeDecl>(DC)) {
618 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000619 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000620 return true;
621 }
622 }
623
624 // The record definition is complete, now look up the member.
Nikola Smiljanicfce370e2014-12-01 23:15:01 +0000625 SemaRef.LookupQualifiedName(R, DC, SS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000626
627 if (!R.empty())
628 return false;
629
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000630 DeclarationName Typo = R.getLookupName();
631 SourceLocation TypoLoc = R.getNameLoc();
David Blaikiea8173ba2015-09-28 23:48:55 +0000632
633 struct QueryState {
634 Sema &SemaRef;
635 DeclarationNameInfo NameInfo;
636 Sema::LookupNameKind LookupKind;
637 Sema::RedeclarationKind Redecl;
638 };
639 QueryState Q = {R.getSema(), R.getLookupNameInfo(), R.getLookupKind(),
640 R.isForRedeclaration() ? Sema::ForRedeclaration
641 : Sema::NotForRedeclaration};
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000642 TE = SemaRef.CorrectTypoDelayed(
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000643 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
644 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000645 [=, &SemaRef](const TypoCorrection &TC) {
646 if (TC) {
647 assert(!TC.isKeyword() &&
648 "Got a keyword as a correction for a member!");
649 bool DroppedSpecifier =
650 TC.WillReplaceSpecifier() &&
651 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
652 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
653 << Typo << DC << DroppedSpecifier
654 << SS.getRange());
655 } else {
656 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
657 }
658 },
659 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
David Blaikiea8173ba2015-09-28 23:48:55 +0000660 LookupResult R(Q.SemaRef, Q.NameInfo, Q.LookupKind, Q.Redecl);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000661 R.clear(); // Ensure there's no decls lingering in the shared state.
662 R.suppressDiagnostics();
663 R.setLookupName(TC.getCorrection());
664 for (NamedDecl *ND : TC)
665 R.addDecl(ND);
666 R.resolveKind();
667 return SemaRef.BuildMemberReferenceExpr(
668 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000669 nullptr, R, nullptr, nullptr);
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000670 },
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000671 Sema::CTK_ErrorRecovery, DC);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000672
673 return false;
674}
675
Richard Smitha0edd302014-05-31 00:18:32 +0000676static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
677 ExprResult &BaseExpr, bool &IsArrow,
678 SourceLocation OpLoc, CXXScopeSpec &SS,
679 Decl *ObjCImpDecl, bool HasTemplateArgs);
680
Douglas Gregor5476205b2011-06-23 00:49:38 +0000681ExprResult
682Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
683 SourceLocation OpLoc, bool IsArrow,
684 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000685 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000686 NamedDecl *FirstQualifierInScope,
687 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000688 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000689 const Scope *S,
Richard Smitha0edd302014-05-31 00:18:32 +0000690 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000691 if (BaseType->isDependentType() ||
692 (SS.isSet() && isDependentScopeSpecifier(SS)))
693 return ActOnDependentMemberExpr(Base, BaseType,
694 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000695 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000696 NameInfo, TemplateArgs);
697
698 LookupResult R(*this, NameInfo, LookupMemberName);
699
700 // Implicit member accesses.
701 if (!Base) {
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000702 TypoExpr *TE = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000703 QualType RecordTy = BaseType;
704 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000705 if (LookupMemberExprInRecord(*this, R, nullptr,
706 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000707 SS, TemplateArgs != nullptr, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000708 return ExprError();
Kaelyn Takata2e764b82014-11-11 23:26:58 +0000709 if (TE)
710 return TE;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000711
712 // Explicit member accesses.
713 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000714 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000715 ExprResult Result = LookupMemberExpr(
716 *this, R, BaseResult, IsArrow, OpLoc, SS,
717 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
718 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000719
720 if (BaseResult.isInvalid())
721 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000722 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000723
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000724 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000725 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000726
727 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000728 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000729
730 // LookupMemberExpr can modify Base, and thus change BaseType
731 BaseType = Base->getType();
732 }
733
734 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000735 OpLoc, IsArrow, SS, TemplateKWLoc,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000736 FirstQualifierInScope, R, TemplateArgs, S,
Richard Smitha0edd302014-05-31 00:18:32 +0000737 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000738}
739
740static ExprResult
741BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000742 SourceLocation OpLoc, const CXXScopeSpec &SS,
743 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000744 const DeclarationNameInfo &MemberNameInfo);
745
746ExprResult
747Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
748 SourceLocation loc,
749 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000750 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000751 Expr *baseObjectExpr,
752 SourceLocation opLoc) {
753 // First, build the expression that refers to the base object.
754
755 bool baseObjectIsPointer = false;
756 Qualifiers baseQuals;
757
758 // Case 1: the base of the indirect field is not a field.
759 VarDecl *baseVariable = indirectField->getVarDecl();
760 CXXScopeSpec EmptySS;
761 if (baseVariable) {
762 assert(baseVariable->getType()->isRecordType());
763
764 // In principle we could have a member access expression that
765 // accesses an anonymous struct/union that's a static member of
766 // the base object's class. However, under the current standard,
767 // static data members cannot be anonymous structs or unions.
768 // Supporting this is as easy as building a MemberExpr here.
769 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
770
771 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
772
773 ExprResult result
774 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
775 if (result.isInvalid()) return ExprError();
776
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000777 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000778 baseObjectIsPointer = false;
779 baseQuals = baseObjectExpr->getType().getQualifiers();
780
781 // Case 2: the base of the indirect field is a field and the user
782 // wrote a member expression.
783 } else if (baseObjectExpr) {
784 // The caller provided the base object expression. Determine
785 // whether its a pointer and whether it adds any qualifiers to the
786 // anonymous struct/union fields we're looking into.
787 QualType objectType = baseObjectExpr->getType();
788
789 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
790 baseObjectIsPointer = true;
791 objectType = ptr->getPointeeType();
792 } else {
793 baseObjectIsPointer = false;
794 }
795 baseQuals = objectType.getQualifiers();
796
797 // Case 3: the base of the indirect field is a field and we should
798 // build an implicit member access.
799 } else {
800 // We've found a member of an anonymous struct/union that is
801 // inside a non-anonymous struct/union, so in a well-formed
802 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000803 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000804 if (ThisTy.isNull()) {
805 Diag(loc, diag::err_invalid_member_use_in_static_method)
806 << indirectField->getDeclName();
807 return ExprError();
808 }
809
810 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000811 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000812 baseObjectExpr
813 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
814 baseObjectIsPointer = true;
815 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
816 }
817
818 // Build the implicit member references to the field of the
819 // anonymous struct/union.
820 Expr *result = baseObjectExpr;
821 IndirectFieldDecl::chain_iterator
822 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
823
824 // Build the first member access in the chain with full information.
825 if (!baseVariable) {
826 FieldDecl *field = cast<FieldDecl>(*FI);
827
Douglas Gregor5476205b2011-06-23 00:49:38 +0000828 // Make a nameInfo that properly uses the anonymous name.
829 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000830
Douglas Gregor5476205b2011-06-23 00:49:38 +0000831 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000832 SourceLocation(), EmptySS, field,
833 foundDecl, memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000834 if (!result)
835 return ExprError();
836
Douglas Gregor5476205b2011-06-23 00:49:38 +0000837 // FIXME: check qualified member access
838 }
839
840 // In all cases, we should now skip the first declaration in the chain.
841 ++FI;
842
843 while (FI != FEnd) {
844 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000845
Douglas Gregor5476205b2011-06-23 00:49:38 +0000846 // FIXME: these are somewhat meaningless
847 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000848 DeclAccessPair fakeFoundDecl =
849 DeclAccessPair::make(field, field->getAccess());
850
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000851 result =
852 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
853 SourceLocation(), (FI == FEnd ? SS : EmptySS),
854 field, fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000855 }
856
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000857 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000858}
859
John McCall5e77d762013-04-16 07:28:30 +0000860static ExprResult
861BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
862 const CXXScopeSpec &SS,
863 MSPropertyDecl *PD,
864 const DeclarationNameInfo &NameInfo) {
865 // Property names are always simple identifiers and therefore never
866 // require any interesting additional storage.
867 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
868 S.Context.PseudoObjectTy, VK_LValue,
869 SS.getWithLocInContext(S.Context),
870 NameInfo.getLoc());
871}
872
Douglas Gregor5476205b2011-06-23 00:49:38 +0000873/// \brief Build a MemberExpr AST node.
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000874static MemberExpr *BuildMemberExpr(
875 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
876 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
877 ValueDecl *Member, DeclAccessPair FoundDecl,
878 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
879 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000880 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +0000881 MemberExpr *E = MemberExpr::Create(
882 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
883 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
Eli Friedmanfa0df832012-02-02 03:46:19 +0000884 SemaRef.MarkMemberReferenced(E);
885 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000886}
887
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000888/// \brief Determine if the given scope is within a function-try-block handler.
889static bool IsInFnTryBlockHandler(const Scope *S) {
890 // Walk the scope stack until finding a FnTryCatchScope, or leave the
891 // function scope. If a FnTryCatchScope is found, check whether the TryScope
892 // flag is set. If it is not, it's a function-try-block handler.
893 for (; S != S->getFnParent(); S = S->getParent()) {
894 if (S->getFlags() & Scope::FnTryCatchScope)
895 return (S->getFlags() & Scope::TryScope) != Scope::TryScope;
896 }
897 return false;
898}
899
Douglas Gregor5476205b2011-06-23 00:49:38 +0000900ExprResult
901Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
902 SourceLocation OpLoc, bool IsArrow,
903 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000904 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000905 NamedDecl *FirstQualifierInScope,
906 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000907 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000908 const Scope *S,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000909 bool SuppressQualifierCheck,
910 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000911 QualType BaseType = BaseExprType;
912 if (IsArrow) {
913 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000914 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000915 }
916 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000917
918 LambdaScopeInfo *const CurLSI = getCurLambda();
919 // If this is an implicit member reference and the overloaded
920 // name refers to both static and non-static member functions
921 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
922 // check if we should/can capture 'this'...
923 // Keep this example in mind:
924 // struct X {
925 // void f(int) { }
926 // static void f(double) { }
927 //
928 // int g() {
929 // auto L = [=](auto a) {
930 // return [](int i) {
931 // return [=](auto b) {
932 // f(b);
933 // //f(decltype(a){});
934 // };
935 // };
936 // };
937 // auto M = L(0.0);
938 // auto N = M(3);
939 // N(5.32); // OK, must not error.
940 // return 0;
941 // }
942 // };
943 //
944 if (!BaseExpr && CurLSI) {
945 SourceLocation Loc = R.getNameLoc();
946 if (SS.getRange().isValid())
947 Loc = SS.getRange().getBegin();
948 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
949 // If the enclosing function is not dependent, then this lambda is
950 // capture ready, so if we can capture this, do so.
951 if (!EnclosingFunctionCtx->isDependentContext()) {
952 // If the current lambda and all enclosing lambdas can capture 'this' -
953 // then go ahead and capture 'this' (since our unresolved overload set
954 // contains both static and non-static member functions).
955 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
956 CheckCXXThisCapture(Loc);
957 } else if (CurContext->isDependentContext()) {
958 // ... since this is an implicit member reference, that might potentially
959 // involve a 'this' capture, mark 'this' for potential capture in
960 // enclosing lambdas.
961 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
962 CurLSI->addPotentialThisCapture(Loc);
963 }
964 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000965 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
966 DeclarationName MemberName = MemberNameInfo.getName();
967 SourceLocation MemberLoc = MemberNameInfo.getLoc();
968
969 if (R.isAmbiguous())
970 return ExprError();
971
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000972 // [except.handle]p10: Referring to any non-static member or base class of an
973 // object in the handler for a function-try-block of a constructor or
974 // destructor for that object results in undefined behavior.
975 const auto *FD = getCurFunctionDecl();
976 if (S && BaseExpr && FD &&
977 (isa<CXXDestructorDecl>(FD) || isa<CXXConstructorDecl>(FD)) &&
978 isa<CXXThisExpr>(BaseExpr->IgnoreImpCasts()) &&
979 IsInFnTryBlockHandler(S))
980 Diag(MemberLoc, diag::warn_cdtor_function_try_handler_mem_expr)
981 << isa<CXXDestructorDecl>(FD);
982
Douglas Gregor5476205b2011-06-23 00:49:38 +0000983 if (R.empty()) {
984 // Rederive where we looked up.
985 DeclContext *DC = (SS.isSet()
986 ? computeDeclContext(SS, false)
987 : BaseType->getAs<RecordType>()->getDecl());
988
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000989 if (ExtraArgs) {
990 ExprResult RetryExpr;
991 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000992 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000993 ParsedType ObjectType;
994 bool MayBePseudoDestructor = false;
995 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
996 OpLoc, tok::arrow, ObjectType,
997 MayBePseudoDestructor);
998 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
999 CXXScopeSpec TempSS(SS);
1000 RetryExpr = ActOnMemberAccessExpr(
1001 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
David Majnemerced8bdf2015-02-25 17:36:15 +00001002 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +00001003 }
1004 if (Trap.hasErrorOccurred())
1005 RetryExpr = ExprError();
1006 }
1007 if (RetryExpr.isUsable()) {
1008 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1009 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1010 return RetryExpr;
1011 }
1012 }
1013
Douglas Gregor5476205b2011-06-23 00:49:38 +00001014 Diag(R.getNameLoc(), diag::err_no_member)
1015 << MemberName << DC
1016 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1017 return ExprError();
1018 }
1019
1020 // Diagnose lookups that find only declarations from a non-base
1021 // type. This is possible for either qualified lookups (which may
1022 // have been qualified with an unrelated type) or implicit member
1023 // expressions (which were found with unqualified lookup and thus
1024 // may have come from an enclosing scope). Note that it's okay for
1025 // lookup to find declarations from a non-base type as long as those
1026 // aren't the ones picked by overload resolution.
1027 if ((SS.isSet() || !BaseExpr ||
1028 (isa<CXXThisExpr>(BaseExpr) &&
1029 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1030 !SuppressQualifierCheck &&
1031 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1032 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001033
Douglas Gregor5476205b2011-06-23 00:49:38 +00001034 // Construct an unresolved result if we in fact got an unresolved
1035 // result.
1036 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1037 // Suppress any lookup-related diagnostics; we'll do these when we
1038 // pick a member.
1039 R.suppressDiagnostics();
1040
1041 UnresolvedMemberExpr *MemExpr
1042 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1043 BaseExpr, BaseExprType,
1044 IsArrow, OpLoc,
1045 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001046 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001047 TemplateArgs, R.begin(), R.end());
1048
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001049 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001050 }
1051
1052 assert(R.isSingleResult());
1053 DeclAccessPair FoundDecl = R.begin().getPair();
1054 NamedDecl *MemberDecl = R.getFoundDecl();
1055
1056 // FIXME: diagnose the presence of template arguments now.
1057
1058 // If the decl being referenced had an error, return an error for this
1059 // sub-expr without emitting another error, in order to avoid cascading
1060 // error cases.
1061 if (MemberDecl->isInvalidDecl())
1062 return ExprError();
1063
1064 // Handle the implicit-member-access case.
1065 if (!BaseExpr) {
1066 // If this is not an instance member, convert to a non-member access.
1067 if (!MemberDecl->isCXXInstanceMember())
1068 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1069
1070 SourceLocation Loc = R.getNameLoc();
1071 if (SS.getRange().isValid())
1072 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001073 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001074 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1075 }
1076
Douglas Gregor5476205b2011-06-23 00:49:38 +00001077 // Check the use of this member.
Davide Italianof179e362015-07-22 00:30:58 +00001078 if (DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001079 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001080
Douglas Gregor5476205b2011-06-23 00:49:38 +00001081 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001082 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1083 FoundDecl, MemberNameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001084
John McCall5e77d762013-04-16 07:28:30 +00001085 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1086 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1087 MemberNameInfo);
1088
Douglas Gregor5476205b2011-06-23 00:49:38 +00001089 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1090 // We may have found a field within an anonymous union or struct
1091 // (C++ [class.union]).
1092 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001093 FoundDecl, BaseExpr,
1094 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001095
1096 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001097 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1098 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001099 Var->getType().getNonReferenceType(), VK_LValue,
1100 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001101 }
1102
1103 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1104 ExprValueKind valueKind;
1105 QualType type;
1106 if (MemberFn->isInstance()) {
1107 valueKind = VK_RValue;
1108 type = Context.BoundMemberTy;
1109 } else {
1110 valueKind = VK_LValue;
1111 type = MemberFn->getType();
1112 }
1113
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001114 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1115 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1116 type, valueKind, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001117 }
1118 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1119
1120 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001121 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1122 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1123 Enum->getType(), VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001124 }
1125
Douglas Gregor5476205b2011-06-23 00:49:38 +00001126 // We found something that we didn't expect. Complain.
1127 if (isa<TypeDecl>(MemberDecl))
1128 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1129 << MemberName << BaseType << int(IsArrow);
1130 else
1131 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1132 << MemberName << BaseType << int(IsArrow);
1133
1134 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1135 << MemberName;
1136 R.suppressDiagnostics();
1137 return ExprError();
1138}
1139
1140/// Given that normal member access failed on the given expression,
1141/// and given that the expression's type involves builtin-id or
1142/// builtin-Class, decide whether substituting in the redefinition
1143/// types would be profitable. The redefinition type is whatever
1144/// this translation unit tried to typedef to id/Class; we store
1145/// it to the side and then re-use it in places like this.
1146static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1147 const ObjCObjectPointerType *opty
1148 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1149 if (!opty) return false;
1150
1151 const ObjCObjectType *ty = opty->getObjectType();
1152
1153 QualType redef;
1154 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001155 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001156 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001157 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001158 } else {
1159 return false;
1160 }
1161
1162 // Do the substitution as long as the redefinition type isn't just a
1163 // possibly-qualified pointer to builtin-id or builtin-Class again.
1164 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001165 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001166 return false;
1167
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001168 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001169 return true;
1170}
1171
John McCall50a2c2c2011-10-11 23:14:30 +00001172static bool isRecordType(QualType T) {
1173 return T->isRecordType();
1174}
1175static bool isPointerToRecordType(QualType T) {
1176 if (const PointerType *PT = T->getAs<PointerType>())
1177 return PT->getPointeeType()->isRecordType();
1178 return false;
1179}
1180
Richard Smithcab9a7d2011-10-26 19:06:56 +00001181/// Perform conversions on the LHS of a member access expression.
1182ExprResult
1183Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001184 if (IsArrow && !Base->getType()->isFunctionType())
1185 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001186
Eli Friedman9a766c42012-01-13 02:20:01 +00001187 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001188}
1189
Douglas Gregor5476205b2011-06-23 00:49:38 +00001190/// Look up the given member of the given non-type-dependent
1191/// expression. This can return in one of two ways:
1192/// * If it returns a sentinel null-but-valid result, the caller will
1193/// assume that lookup was performed and the results written into
1194/// the provided structure. It will take over from there.
1195/// * Otherwise, the returned expression will be produced in place of
1196/// an ordinary member expression.
1197///
1198/// The ObjCImpDecl bit is a gross hack that will need to be properly
1199/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001200static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1201 ExprResult &BaseExpr, bool &IsArrow,
1202 SourceLocation OpLoc, CXXScopeSpec &SS,
1203 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001204 assert(BaseExpr.get() && "no base expression");
1205
1206 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001207 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001208 if (BaseExpr.isInvalid())
1209 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001210
Douglas Gregor5476205b2011-06-23 00:49:38 +00001211 QualType BaseType = BaseExpr.get()->getType();
1212 assert(!BaseType->isDependentType());
1213
1214 DeclarationName MemberName = R.getLookupName();
1215 SourceLocation MemberLoc = R.getNameLoc();
1216
1217 // For later type-checking purposes, turn arrow accesses into dot
1218 // accesses. The only access type we support that doesn't follow
1219 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1220 // and those never use arrows, so this is unaffected.
1221 if (IsArrow) {
1222 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1223 BaseType = Ptr->getPointeeType();
1224 else if (const ObjCObjectPointerType *Ptr
1225 = BaseType->getAs<ObjCObjectPointerType>())
1226 BaseType = Ptr->getPointeeType();
1227 else if (BaseType->isRecordType()) {
1228 // Recover from arrow accesses to records, e.g.:
1229 // struct MyRecord foo;
1230 // foo->bar
1231 // This is actually well-formed in C++ if MyRecord has an
1232 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001233 // by now--or a diagnostic message already issued if a problem
1234 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001235 if (!S.getLangOpts().CPlusPlus) {
1236 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001237 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1238 << FixItHint::CreateReplacement(OpLoc, ".");
1239 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001240 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001241 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001242 goto fail;
1243 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001244 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001245 << BaseType << BaseExpr.get()->getSourceRange();
1246 return ExprError();
1247 }
1248 }
1249
1250 // Handle field access to simple records.
1251 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001252 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001253 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
Kaelyn Takata2e764b82014-11-11 23:26:58 +00001254 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001255 return ExprError();
1256
1257 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001258 // the lookup result was filled in. If typo correction was attempted and
1259 // failed, the lookup result will have been cleared--that combined with the
1260 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1261 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001262 }
1263
1264 // Handle ivar access to Objective-C objects.
1265 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001266 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001267 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001268 << 1 << SS.getScopeRep()
1269 << FixItHint::CreateRemoval(SS.getRange());
1270 SS.clear();
1271 }
Richard Smitha0edd302014-05-31 00:18:32 +00001272
Douglas Gregor5476205b2011-06-23 00:49:38 +00001273 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1274
1275 // There are three cases for the base type:
1276 // - builtin id (qualified or unqualified)
1277 // - builtin Class (qualified or unqualified)
1278 // - an interface
1279 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1280 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001281 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001282 (OTy->isObjCId() || OTy->isObjCClass()))
1283 goto fail;
1284 // There's an implicit 'isa' ivar on all objects.
1285 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001286 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001287 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001288 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1289 OpLoc, S.Context.getObjCClassType());
1290 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1291 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001292 ObjCImpDecl, HasTemplateArgs);
1293 goto fail;
1294 }
Richard Smitha0edd302014-05-31 00:18:32 +00001295
1296 if (S.RequireCompleteType(OpLoc, BaseType,
1297 diag::err_typecheck_incomplete_tag,
1298 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001299 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001300
1301 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001302 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1303
1304 if (!IV) {
1305 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001306 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1307 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001308 if (TypoCorrection Corrected = S.CorrectTypo(
1309 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001310 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001311 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001312 S.diagnoseTypo(
1313 Corrected,
1314 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1315 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001316
Ted Kremenek679b4782012-03-17 00:53:39 +00001317 // Figure out the class that declares the ivar.
1318 assert(!ClassDeclared);
1319 Decl *D = cast<Decl>(IV->getDeclContext());
1320 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1321 D = CAT->getClassInterface();
1322 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001323 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001324 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001325 S.Diag(MemberLoc, diag::err_property_found_suggest)
1326 << Member << BaseExpr.get()->getType()
1327 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001328 return ExprError();
1329 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001330
Richard Smitha0edd302014-05-31 00:18:32 +00001331 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1332 << IDecl->getDeclName() << MemberName
1333 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001334 return ExprError();
1335 }
1336 }
Richard Smitha0edd302014-05-31 00:18:32 +00001337
Ted Kremenek679b4782012-03-17 00:53:39 +00001338 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001339
1340 // If the decl being referenced had an error, return an error for this
1341 // sub-expr without emitting another error, in order to avoid cascading
1342 // error cases.
1343 if (IV->isInvalidDecl())
1344 return ExprError();
1345
1346 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001347 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001348 return ExprError();
1349 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1350 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001351 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001352 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001353 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001354 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001355 // Case of a c-function declared inside an objc implementation.
1356 // FIXME: For a c-style function nested inside an objc implementation
1357 // class, there is no implementation context available, so we pass
1358 // down the context as argument to this routine. Ideally, this context
1359 // need be passed down in the AST node and somehow calculated from the
1360 // AST for a function decl.
1361 if (ObjCImplementationDecl *IMPD =
1362 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1363 ClassOfMethodDecl = IMPD->getClassInterface();
1364 else if (ObjCCategoryImplDecl* CatImplClass =
1365 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1366 ClassOfMethodDecl = CatImplClass->getClassInterface();
1367 }
Richard Smitha0edd302014-05-31 00:18:32 +00001368 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001369 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1370 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1371 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001372 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001373 << IV->getDeclName();
1374 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1375 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001376 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1377 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001378 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001379 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001380 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001381 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001382 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1383 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1384 if (UO->getOpcode() == UO_Deref)
1385 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1386
1387 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001388 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001389 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001390 warn = false;
1391 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001392 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001393 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001394 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001395 ObjCMethodFamily MF = MD->getMethodFamily();
1396 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001397 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001398 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001399 }
1400 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001401 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001402 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001403
Richard Smitha0edd302014-05-31 00:18:32 +00001404 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
Douglas Gregore83b9562015-07-07 03:57:53 +00001405 IV, IV->getUsageType(BaseType), MemberLoc, OpLoc, BaseExpr.get(),
1406 IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001407
Richard Smitha0edd302014-05-31 00:18:32 +00001408 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001409 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001410 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001411 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001412 }
1413 }
1414
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001415 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001416 }
1417
1418 // Objective-C property access.
1419 const ObjCObjectPointerType *OPT;
1420 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001421 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001422 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1423 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001424 SS.clear();
1425 }
1426
Douglas Gregor5476205b2011-06-23 00:49:38 +00001427 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001428 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001429 if (BaseExpr.isInvalid())
1430 return ExprError();
1431
Richard Smitha0edd302014-05-31 00:18:32 +00001432 assert(S.Context.hasSameUnqualifiedType(BaseType,
1433 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001434
1435 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1436
1437 const ObjCObjectType *OT = OPT->getObjectType();
1438
1439 // id, with and without qualifiers.
1440 if (OT->isObjCId()) {
1441 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001442 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1443 if (Decl *PMDecl =
1444 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001445 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1446 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001447 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001448 return ExprError();
1449
Richard Smitha0edd302014-05-31 00:18:32 +00001450 return new (S.Context)
1451 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001452 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001453 }
1454
1455 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1456 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001457 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001458 return ExprError();
1459 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001460 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1461 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001462 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001463 ObjCMethodDecl *SMD = nullptr;
1464 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001465 /*Property id*/ nullptr,
1466 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001467 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001468
1469 return new (S.Context)
1470 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001471 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001472 }
1473 }
1474 // Use of id.member can only be for a property reference. Do not
1475 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001476 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1477 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001478 ObjCImpDecl, HasTemplateArgs);
1479
Richard Smitha0edd302014-05-31 00:18:32 +00001480 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001481 << MemberName << BaseType);
1482 }
1483
1484 // 'Class', unqualified only.
1485 if (OT->isObjCClass()) {
1486 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001487 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001488 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001489 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1490 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001491 ObjCImpDecl, HasTemplateArgs);
1492
1493 goto fail;
1494 }
1495
1496 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001497 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001498 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1499 ObjCMethodDecl *Getter;
1500 if ((Getter = IFace->lookupClassMethod(Sel))) {
1501 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001502 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001503 return ExprError();
1504 } else
1505 Getter = IFace->lookupPrivateMethod(Sel, false);
1506 // If we found a getter then this may be a valid dot-reference, we
1507 // will look for the matching setter, in case it is needed.
1508 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001509 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1510 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001511 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001512 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1513 if (!Setter) {
1514 // If this reference is in an @implementation, also check for 'private'
1515 // methods.
1516 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1517 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001518
Richard Smitha0edd302014-05-31 00:18:32 +00001519 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001520 return ExprError();
1521
1522 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001523 return new (S.Context) ObjCPropertyRefExpr(
1524 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1525 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001526 }
1527
Richard Smitha0edd302014-05-31 00:18:32 +00001528 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1529 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001530 ObjCImpDecl, HasTemplateArgs);
1531
Richard Smitha0edd302014-05-31 00:18:32 +00001532 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001533 << MemberName << BaseType);
1534 }
1535
1536 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001537 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1538 MemberLoc, SourceLocation(), QualType(),
1539 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001540 }
1541
1542 // Handle 'field access' to vectors, such as 'V.xx'.
1543 if (BaseType->isExtVectorType()) {
1544 // FIXME: this expr should store IsArrow.
1545 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
Fariborz Jahanian220d08d2015-04-06 16:56:39 +00001546 ExprValueKind VK;
1547 if (IsArrow)
1548 VK = VK_LValue;
1549 else {
1550 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1551 VK = POE->getSyntacticForm()->getValueKind();
1552 else
1553 VK = BaseExpr.get()->getValueKind();
1554 }
Richard Smitha0edd302014-05-31 00:18:32 +00001555 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001556 Member, MemberLoc);
1557 if (ret.isNull())
1558 return ExprError();
1559
Richard Smitha0edd302014-05-31 00:18:32 +00001560 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001561 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001562 }
1563
1564 // Adjust builtin-sel to the appropriate redefinition type if that's
1565 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001566 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1567 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1568 BaseExpr = S.ImpCastExprToType(
1569 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1570 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001571 ObjCImpDecl, HasTemplateArgs);
1572 }
1573
1574 // Failure cases.
1575 fail:
1576
1577 // Recover from dot accesses to pointers, e.g.:
1578 // type *foo;
1579 // foo.bar
1580 // This is actually well-formed in two cases:
1581 // - 'type' is an Objective C type
1582 // - 'bar' is a pseudo-destructor name which happens to refer to
1583 // the appropriate pointer type
1584 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1585 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1586 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001587 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1588 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001589 << FixItHint::CreateReplacement(OpLoc, "->");
1590
1591 // Recurse as an -> access.
1592 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001593 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001594 ObjCImpDecl, HasTemplateArgs);
1595 }
1596 }
1597
1598 // If the user is trying to apply -> or . to a function name, it's probably
1599 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001600 if (S.tryToRecoverWithCall(
1601 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1602 /*complain*/ false,
1603 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001604 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001605 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001606 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1607 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001608 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001609 }
1610
Richard Smitha0edd302014-05-31 00:18:32 +00001611 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001612 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001613
1614 return ExprError();
1615}
1616
1617/// The main callback when the parser finds something like
1618/// expression . [nested-name-specifier] identifier
1619/// expression -> [nested-name-specifier] identifier
1620/// where 'identifier' encompasses a fairly broad spectrum of
1621/// possibilities, including destructor and operator references.
1622///
1623/// \param OpKind either tok::arrow or tok::period
James Dennett2a4d13c2012-06-15 07:13:21 +00001624/// \param ObjCImpDecl the current Objective-C \@implementation
1625/// decl; this is an ugly hack around the fact that Objective-C
1626/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001627ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1628 SourceLocation OpLoc,
1629 tok::TokenKind OpKind,
1630 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001631 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001632 UnqualifiedId &Id,
David Majnemerced8bdf2015-02-25 17:36:15 +00001633 Decl *ObjCImpDecl) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001634 if (SS.isSet() && SS.isInvalid())
1635 return ExprError();
1636
1637 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001638 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001639 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1640 Diag(Id.getSourceRange().getBegin(),
1641 diag::ext_ms_explicit_constructor_call);
1642
1643 TemplateArgumentListInfo TemplateArgsBuffer;
1644
1645 // Decompose the name into its component parts.
1646 DeclarationNameInfo NameInfo;
1647 const TemplateArgumentListInfo *TemplateArgs;
1648 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1649 NameInfo, TemplateArgs);
1650
1651 DeclarationName Name = NameInfo.getName();
1652 bool IsArrow = (OpKind == tok::arrow);
1653
1654 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001655 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001656
1657 // This is a postfix expression, so get rid of ParenListExprs.
1658 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1659 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001660 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001661
1662 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1663 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001664 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1665 TemplateKWLoc, FirstQualifierInScope,
1666 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001667 }
1668
David Majnemerced8bdf2015-02-25 17:36:15 +00001669 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
Richard Smitha0edd302014-05-31 00:18:32 +00001670 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1671 TemplateKWLoc, FirstQualifierInScope,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001672 NameInfo, TemplateArgs, S, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001673}
1674
1675static ExprResult
1676BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001677 SourceLocation OpLoc, const CXXScopeSpec &SS,
1678 FieldDecl *Field, DeclAccessPair FoundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001679 const DeclarationNameInfo &MemberNameInfo) {
1680 // x.a is an l-value if 'a' has a reference type. Otherwise:
1681 // x.a is an l-value/x-value/pr-value if the base is (and note
1682 // that *x is always an l-value), except that if the base isn't
1683 // an ordinary object then we must have an rvalue.
1684 ExprValueKind VK = VK_LValue;
1685 ExprObjectKind OK = OK_Ordinary;
1686 if (!IsArrow) {
1687 if (BaseExpr->getObjectKind() == OK_Ordinary)
1688 VK = BaseExpr->getValueKind();
1689 else
1690 VK = VK_RValue;
1691 }
1692 if (VK != VK_RValue && Field->isBitField())
1693 OK = OK_BitField;
1694
1695 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1696 QualType MemberType = Field->getType();
1697 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1698 MemberType = Ref->getPointeeType();
1699 VK = VK_LValue;
1700 } else {
1701 QualType BaseType = BaseExpr->getType();
1702 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001703
Douglas Gregor5476205b2011-06-23 00:49:38 +00001704 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001705
Douglas Gregor5476205b2011-06-23 00:49:38 +00001706 // GC attributes are never picked up by members.
1707 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001708
Douglas Gregor5476205b2011-06-23 00:49:38 +00001709 // CVR attributes from the base are picked up by members,
1710 // except that 'mutable' members don't pick up 'const'.
1711 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001712
Douglas Gregor5476205b2011-06-23 00:49:38 +00001713 Qualifiers MemberQuals
1714 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001715
Douglas Gregor5476205b2011-06-23 00:49:38 +00001716 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001717
1718
Douglas Gregor5476205b2011-06-23 00:49:38 +00001719 Qualifiers Combined = BaseQuals + MemberQuals;
1720 if (Combined != MemberQuals)
1721 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1722 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001723
Daniel Jasper0baec5492012-06-06 08:32:04 +00001724 S.UnusedPrivateFields.remove(Field);
1725
Douglas Gregor5476205b2011-06-23 00:49:38 +00001726 ExprResult Base =
1727 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1728 FoundDecl, Field);
1729 if (Base.isInvalid())
1730 return ExprError();
Aaron Ballmanf4cb2be2015-03-24 15:07:53 +00001731 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001732 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1733 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001734}
1735
1736/// Builds an implicit member access expression. The current context
1737/// is known to be an instance method, and the given unqualified lookup
1738/// set is known to contain only instance members, at least one of which
1739/// is from an appropriate type.
1740ExprResult
1741Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001742 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001743 LookupResult &R,
1744 const TemplateArgumentListInfo *TemplateArgs,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001745 bool IsKnownInstance, const Scope *S) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001746 assert(!R.empty() && !R.isAmbiguous());
1747
1748 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001749
Douglas Gregor5476205b2011-06-23 00:49:38 +00001750 // If this is known to be an instance access, go ahead and build an
1751 // implicit 'this' expression now.
1752 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001753 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001754 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001755
1756 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001757 if (IsKnownInstance) {
1758 SourceLocation Loc = R.getNameLoc();
1759 if (SS.getRange().isValid())
1760 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001761 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001762 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1763 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001764
Douglas Gregor5476205b2011-06-23 00:49:38 +00001765 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1766 /*OpLoc*/ SourceLocation(),
1767 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001768 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001769 /*FirstQualifierInScope*/ nullptr,
Aaron Ballman6924dcd2015-09-01 14:49:24 +00001770 R, TemplateArgs, S);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001771}