blob: deecc4122d890f987518a6809dcf3081ea48e618 [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"
Douglas Gregor5476205b2011-06-23 00:49:38 +000014#include "clang/Sema/SemaInternal.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000015#include "clang/AST/ASTLambda.h"
Douglas Gregor5476205b2011-06-23 00:49:38 +000016#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/Lookup.h"
23#include "clang/Sema/Scope.h"
24#include "clang/Sema/ScopeInfo.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,
93 Scope *CurScope,
94 const LookupResult &R) {
95 assert(!R.empty() && (*R.begin())->isCXXClassMember());
96
97 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
98
Douglas Gregor3024f072012-04-16 07:05:22 +000099 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
100 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000101
102 if (R.isUnresolvableResult())
103 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
104
105 // Collect all the declaring classes of instance members we find.
106 bool hasNonInstance = false;
Eli Friedman7bda7f72012-01-18 03:53:45 +0000107 bool isField = false;
Richard Smithd80b2d52012-11-22 00:24:47 +0000108 BaseSet Classes;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000109 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
110 NamedDecl *D = *I;
111
112 if (D->isCXXInstanceMember()) {
John McCall5e77d762013-04-16 07:28:30 +0000113 if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
114 || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman7bda7f72012-01-18 03:53:45 +0000115 isField = true;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000116
117 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
118 Classes.insert(R->getCanonicalDecl());
119 }
120 else
121 hasNonInstance = true;
122 }
123
124 // If we didn't find any instance members, it can't be an implicit
125 // member reference.
126 if (Classes.empty())
127 return IMA_Static;
John McCallf413f5e2013-05-03 00:10:13 +0000128
129 // C++11 [expr.prim.general]p12:
130 // An id-expression that denotes a non-static data member or non-static
131 // member function of a class can only be used:
132 // (...)
133 // - if that id-expression denotes a non-static data member and it
134 // appears in an unevaluated operand.
135 //
136 // This rule is specific to C++11. However, we also permit this form
137 // in unevaluated inline assembly operands, like the operand to a SIZE.
138 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
139 assert(!AbstractInstanceResult);
140 switch (SemaRef.ExprEvalContexts.back().Context) {
141 case Sema::Unevaluated:
142 if (isField && SemaRef.getLangOpts().CPlusPlus11)
143 AbstractInstanceResult = IMA_Field_Uneval_Context;
144 break;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000145
John McCallf413f5e2013-05-03 00:10:13 +0000146 case Sema::UnevaluatedAbstract:
147 AbstractInstanceResult = IMA_Abstract;
148 break;
149
150 case Sema::ConstantEvaluated:
151 case Sema::PotentiallyEvaluated:
152 case Sema::PotentiallyEvaluatedIfUsed:
153 break;
Richard Smitheae99682012-02-25 10:04:07 +0000154 }
155
Douglas Gregor5476205b2011-06-23 00:49:38 +0000156 // If the current context is not an instance method, it can't be
157 // an implicit member reference.
158 if (isStaticContext) {
159 if (hasNonInstance)
Richard Smitheae99682012-02-25 10:04:07 +0000160 return IMA_Mixed_StaticContext;
161
John McCallf413f5e2013-05-03 00:10:13 +0000162 return AbstractInstanceResult ? AbstractInstanceResult
163 : IMA_Error_StaticContext;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000164 }
165
166 CXXRecordDecl *contextClass;
167 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
168 contextClass = MD->getParent()->getCanonicalDecl();
169 else
170 contextClass = cast<CXXRecordDecl>(DC);
171
172 // [class.mfct.non-static]p3:
173 // ...is used in the body of a non-static member function of class X,
174 // if name lookup (3.4.1) resolves the name in the id-expression to a
175 // non-static non-type member of some class C [...]
176 // ...if C is not X or a base class of X, the class member access expression
177 // is ill-formed.
178 if (R.getNamingClass() &&
DeLesley Hutchins5b330db2012-02-25 00:11:55 +0000179 contextClass->getCanonicalDecl() !=
Richard Smithd80b2d52012-11-22 00:24:47 +0000180 R.getNamingClass()->getCanonicalDecl()) {
181 // If the naming class is not the current context, this was a qualified
182 // member name lookup, and it's sufficient to check that we have the naming
183 // class as a base class.
184 Classes.clear();
Richard Smithb2c5f962012-11-22 00:40:54 +0000185 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithd80b2d52012-11-22 00:24:47 +0000186 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000187
188 // If we can prove that the current context is unrelated to all the
189 // declaring classes, it can't be an implicit member reference (in
190 // which case it's an error if any of those members are selected).
Richard Smithd80b2d52012-11-22 00:24:47 +0000191 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smith2a986112012-02-25 10:20:59 +0000192 return hasNonInstance ? IMA_Mixed_Unrelated :
John McCallf413f5e2013-05-03 00:10:13 +0000193 AbstractInstanceResult ? AbstractInstanceResult :
194 IMA_Error_Unrelated;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000195
196 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
197}
198
199/// Diagnose a reference to a field with no object available.
Richard Smithfa0a1f52012-04-05 01:13:04 +0000200static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000201 const CXXScopeSpec &SS,
Richard Smithfa0a1f52012-04-05 01:13:04 +0000202 NamedDecl *Rep,
Eli Friedman456f0182012-01-20 01:26:23 +0000203 const DeclarationNameInfo &nameInfo) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000204 SourceLocation Loc = nameInfo.getLoc();
205 SourceRange Range(Loc);
206 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman7bda7f72012-01-18 03:53:45 +0000207
Richard Smithfa0a1f52012-04-05 01:13:04 +0000208 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
209 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
Craig Topperc3ec1492014-05-26 06:22:03 +0000210 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
Richard Smithfa0a1f52012-04-05 01:13:04 +0000211 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
212
213 bool InStaticMethod = Method && Method->isStatic();
214 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
215
216 if (IsField && InStaticMethod)
217 // "invalid use of member 'x' in static member function"
218 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
219 << Range << nameInfo.getName();
220 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
221 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
222 // Unqualified lookup in a non-static member function found a member of an
223 // enclosing class.
224 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
225 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
226 else if (IsField)
Eli Friedman456f0182012-01-20 01:26:23 +0000227 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000228 << nameInfo.getName() << Range;
229 else
230 SemaRef.Diag(Loc, diag::err_member_call_without_object)
231 << Range;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000232}
233
234/// Builds an expression which might be an implicit member expression.
235ExprResult
236Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000237 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000238 LookupResult &R,
239 const TemplateArgumentListInfo *TemplateArgs) {
240 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
241 case IMA_Instance:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000242 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000243
244 case IMA_Mixed:
245 case IMA_Mixed_Unrelated:
246 case IMA_Unresolved:
Abramo Bagnara7945c982012-01-27 09:46:47 +0000247 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000248
Richard Smith2a986112012-02-25 10:20:59 +0000249 case IMA_Field_Uneval_Context:
250 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
251 << R.getLookupNameInfo().getName();
252 // Fall through.
Douglas Gregor5476205b2011-06-23 00:49:38 +0000253 case IMA_Static:
John McCallf413f5e2013-05-03 00:10:13 +0000254 case IMA_Abstract:
Douglas Gregor5476205b2011-06-23 00:49:38 +0000255 case IMA_Mixed_StaticContext:
256 case IMA_Unresolved_StaticContext:
Abramo Bagnara65f7c3d2012-02-06 14:31:00 +0000257 if (TemplateArgs || TemplateKWLoc.isValid())
258 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000259 return BuildDeclarationNameExpr(SS, R, false);
260
261 case IMA_Error_StaticContext:
262 case IMA_Error_Unrelated:
Richard Smithfa0a1f52012-04-05 01:13:04 +0000263 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor5476205b2011-06-23 00:49:38 +0000264 R.getLookupNameInfo());
265 return ExprError();
266 }
267
268 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor5476205b2011-06-23 00:49:38 +0000269}
270
271/// Check an ext-vector component access expression.
272///
273/// VK should be set in advance to the value kind of the base
274/// expression.
275static QualType
276CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
277 SourceLocation OpLoc, const IdentifierInfo *CompName,
278 SourceLocation CompLoc) {
279 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
280 // see FIXME there.
281 //
282 // FIXME: This logic can be greatly simplified by splitting it along
283 // halving/not halving and reworking the component checking.
284 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
285
286 // The vector accessor can't exceed the number of elements.
287 const char *compStr = CompName->getNameStart();
288
289 // This flag determines whether or not the component is one of the four
290 // special names that indicate a subset of exactly half the elements are
291 // to be selected.
292 bool HalvingSwizzle = false;
293
294 // This flag determines whether or not CompName has an 's' char prefix,
295 // indicating that it is a string of hex values to be used as vector indices.
Fariborz Jahanian275542a2014-04-03 19:43:01 +0000296 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
Douglas Gregor5476205b2011-06-23 00:49:38 +0000297
298 bool HasRepeated = false;
299 bool HasIndex[16] = {};
300
301 int Idx;
302
303 // Check that we've found one of the special components, or that the component
304 // names must come from the same set.
305 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
306 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
307 HalvingSwizzle = true;
308 } else if (!HexSwizzle &&
309 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
310 do {
311 if (HasIndex[Idx]) HasRepeated = true;
312 HasIndex[Idx] = true;
313 compStr++;
314 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
315 } else {
316 if (HexSwizzle) compStr++;
317 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
318 if (HasIndex[Idx]) HasRepeated = true;
319 HasIndex[Idx] = true;
320 compStr++;
321 }
322 }
323
324 if (!HalvingSwizzle && *compStr) {
325 // We didn't get to the end of the string. This means the component names
326 // didn't come from the same set *or* we encountered an illegal name.
327 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000328 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000329 return QualType();
330 }
331
332 // Ensure no component accessor exceeds the width of the vector type it
333 // operates on.
334 if (!HalvingSwizzle) {
335 compStr = CompName->getNameStart();
336
337 if (HexSwizzle)
338 compStr++;
339
340 while (*compStr) {
341 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
342 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
343 << baseType << SourceRange(CompLoc);
344 return QualType();
345 }
346 }
347 }
348
349 // The component accessor looks fine - now we need to compute the actual type.
350 // The vector type is implied by the component accessor. For example,
351 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
352 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
353 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
354 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
355 : CompName->getLength();
356 if (HexSwizzle)
357 CompSize--;
358
359 if (CompSize == 1)
360 return vecType->getElementType();
361
362 if (HasRepeated) VK = VK_RValue;
363
364 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
365 // Now look up the TypeDefDecl from the vector type. Without this,
366 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregorb7098a32011-07-28 00:39:29 +0000367 for (Sema::ExtVectorDeclsType::iterator
Axel Naumanndd433f02012-10-18 19:05:02 +0000368 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregorb7098a32011-07-28 00:39:29 +0000369 E = S.ExtVectorDecls.end();
370 I != E; ++I) {
371 if ((*I)->getUnderlyingType() == VT)
372 return S.Context.getTypedefType(*I);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000373 }
Douglas Gregorb7098a32011-07-28 00:39:29 +0000374
Douglas Gregor5476205b2011-06-23 00:49:38 +0000375 return VT; // should never get here (a typedef type should always be found).
376}
377
378static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
379 IdentifierInfo *Member,
380 const Selector &Sel,
381 ASTContext &Context) {
382 if (Member)
383 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
384 return PD;
385 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
386 return OMD;
387
Aaron Ballman0f6e64d2014-03-13 22:58:06 +0000388 for (const auto *I : PDecl->protocols()) {
389 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000390 Context))
391 return D;
392 }
Craig Topperc3ec1492014-05-26 06:22:03 +0000393 return nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000394}
395
396static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
397 IdentifierInfo *Member,
398 const Selector &Sel,
399 ASTContext &Context) {
400 // Check protocols on qualified interfaces.
Craig Topperc3ec1492014-05-26 06:22:03 +0000401 Decl *GDecl = nullptr;
Aaron Ballman83731462014-03-17 16:14:00 +0000402 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000403 if (Member)
Aaron Ballman83731462014-03-17 16:14:00 +0000404 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000405 GDecl = PD;
406 break;
407 }
408 // Also must look for a getter or setter name which uses property syntax.
Aaron Ballman83731462014-03-17 16:14:00 +0000409 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000410 GDecl = OMD;
411 break;
412 }
413 }
414 if (!GDecl) {
Aaron Ballman83731462014-03-17 16:14:00 +0000415 for (const auto *I : QIdTy->quals()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000416 // Search in the protocol-qualifier list of current protocol.
Aaron Ballman83731462014-03-17 16:14:00 +0000417 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000418 if (GDecl)
419 return GDecl;
420 }
421 }
422 return GDecl;
423}
424
425ExprResult
426Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
427 bool IsArrow, SourceLocation OpLoc,
428 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000429 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000430 NamedDecl *FirstQualifierInScope,
431 const DeclarationNameInfo &NameInfo,
432 const TemplateArgumentListInfo *TemplateArgs) {
433 // Even in dependent contexts, try to diagnose base expressions with
434 // obviously wrong types, e.g.:
435 //
436 // T* t;
437 // t.f;
438 //
439 // In Obj-C++, however, the above expression is valid, since it could be
440 // accessing the 'f' property if T is an Obj-C interface. The extra check
441 // allows this, while still reporting an error if T is a struct pointer.
442 if (!IsArrow) {
443 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikiebbafb8a2012-03-11 07:00:24 +0000444 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor5476205b2011-06-23 00:49:38 +0000445 PT->getPointeeType()->isRecordType())) {
446 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gayd9f244af2012-04-21 01:12:48 +0000447 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +0000448 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000449 return ExprError();
450 }
451 }
452
453 assert(BaseType->isDependentType() ||
454 NameInfo.getName().isDependentName() ||
455 isDependentScopeSpecifier(SS));
456
457 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
458 // must have pointer type, and the accessed type is the pointee.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000459 return CXXDependentScopeMemberExpr::Create(
460 Context, BaseExpr, BaseType, IsArrow, OpLoc,
461 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
462 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000463}
464
465/// We know that the given qualified member reference points only to
466/// declarations which do not belong to the static type of the base
467/// expression. Diagnose the problem.
468static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
469 Expr *BaseExpr,
470 QualType BaseType,
471 const CXXScopeSpec &SS,
472 NamedDecl *rep,
473 const DeclarationNameInfo &nameInfo) {
474 // If this is an implicit member access, use a different set of
475 // diagnostics.
476 if (!BaseExpr)
Richard Smithfa0a1f52012-04-05 01:13:04 +0000477 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000478
479 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
480 << SS.getRange() << rep << BaseType;
481}
482
483// Check whether the declarations we found through a nested-name
484// specifier in a member expression are actually members of the base
485// type. The restriction here is:
486//
487// C++ [expr.ref]p2:
488// ... In these cases, the id-expression shall name a
489// member of the class or of one of its base classes.
490//
491// So it's perfectly legitimate for the nested-name specifier to name
492// an unrelated class, and for us to find an overload set including
493// decls from classes which are not superclasses, as long as the decl
494// we actually pick through overload resolution is from a superclass.
495bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
496 QualType BaseType,
497 const CXXScopeSpec &SS,
498 const LookupResult &R) {
Richard Smithd80b2d52012-11-22 00:24:47 +0000499 CXXRecordDecl *BaseRecord =
500 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
501 if (!BaseRecord) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000502 // We can't check this yet because the base type is still
503 // dependent.
504 assert(BaseType->isDependentType());
505 return false;
506 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000507
508 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
509 // If this is an implicit member reference and we find a
510 // non-instance member, it's not an error.
511 if (!BaseExpr && !(*I)->isCXXInstanceMember())
512 return false;
513
514 // Note that we use the DC of the decl, not the underlying decl.
515 DeclContext *DC = (*I)->getDeclContext();
516 while (DC->isTransparentContext())
517 DC = DC->getParent();
518
519 if (!DC->isRecord())
520 continue;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000521
Richard Smithd80b2d52012-11-22 00:24:47 +0000522 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
523 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
524 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000525 return false;
526 }
527
528 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
529 R.getRepresentativeDecl(),
530 R.getLookupNameInfo());
531 return true;
532}
533
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000534namespace {
535
536// Callback to only accept typo corrections that are either a ValueDecl or a
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000537// FunctionTemplateDecl and are declared in the current record or, for a C++
538// classes, one of its base classes.
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000539class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000540public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000541 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
Kaelyn Takatae9e4ecf2014-11-11 23:00:40 +0000542 : Record(RTy->getDecl()) {
543 // Don't add bare keywords to the consumer since they will always fail
544 // validation by virtue of not being associated with any decls.
545 WantTypeSpecifiers = false;
546 WantExpressionKeywords = false;
547 WantCXXNamedCasts = false;
548 WantFunctionLikeCasts = false;
549 WantRemainingKeywords = false;
550 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000551
Craig Toppere14c0f82014-03-12 04:55:44 +0000552 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000553 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000554 // Don't accept candidates that cannot be member functions, constants,
555 // variables, or templates.
556 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
557 return false;
558
559 // Accept candidates that occur in the current record.
560 if (Record->containsDecl(ND))
561 return true;
562
563 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
564 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000565 for (const auto &BS : RD->bases()) {
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000566 if (const RecordType *BSTy =
567 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000568 if (BSTy->getDecl()->containsDecl(ND))
569 return true;
570 }
571 }
572 }
573
574 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000575 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000576
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000577private:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000578 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000579};
580
581}
582
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000583static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000584 Expr *BaseExpr,
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000585 const RecordType *RTy,
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000586 SourceLocation OpLoc, bool IsArrow,
587 CXXScopeSpec &SS, bool HasTemplateArgs,
588 TypoExpr **TE = nullptr) {
589 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000590 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000591 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
592 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000593 diag::err_typecheck_incomplete_tag,
594 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000595 return true;
596
597 if (HasTemplateArgs) {
598 // LookupTemplateName doesn't expect these both to exist simultaneously.
599 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
600
601 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000602 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000603 return false;
604 }
605
606 DeclContext *DC = RDecl;
607 if (SS.isSet()) {
608 // If the member name was a qualified-id, look into the
609 // nested-name-specifier.
610 DC = SemaRef.computeDeclContext(SS, false);
611
612 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
613 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000614 << SS.getRange() << DC;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000615 return true;
616 }
617
618 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
619
620 if (!isa<TypeDecl>(DC)) {
621 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000622 << DC << SS.getRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000623 return true;
624 }
625 }
626
627 // The record definition is complete, now look up the member.
628 SemaRef.LookupQualifiedName(R, DC);
629
630 if (!R.empty())
631 return false;
632
Kaelyn Takatafe408a72014-10-27 18:07:46 +0000633 if (TE && SemaRef.getLangOpts().CPlusPlus) {
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000634 DeclarationName Typo = R.getLookupName();
635 SourceLocation TypoLoc = R.getNameLoc();
Kaelyn Takatafe408a72014-10-27 18:07:46 +0000636 // TODO: C cannot handle TypoExpr nodes because the C code paths do not know
637 // what to do with dependent types e.g. on the LHS of an assigment.
638 *TE = SemaRef.CorrectTypoDelayed(
639 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
640 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000641 [=, &SemaRef](const TypoCorrection &TC) {
642 if (TC) {
643 assert(!TC.isKeyword() &&
644 "Got a keyword as a correction for a member!");
645 bool DroppedSpecifier =
646 TC.WillReplaceSpecifier() &&
647 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
648 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
649 << Typo << DC << DroppedSpecifier
650 << SS.getRange());
651 } else {
652 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC
653 << BaseRange;
654 }
655 },
656 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
657 R.clear(); // Ensure there's no decls lingering in the shared state.
658 R.suppressDiagnostics();
659 R.setLookupName(TC.getCorrection());
660 for (NamedDecl *ND : TC)
661 R.addDecl(ND);
662 R.resolveKind();
663 return SemaRef.BuildMemberReferenceExpr(
664 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS,
665 SourceLocation(), nullptr, R, nullptr);
666 },
667 Sema::CTK_ErrorRecovery, DC);
Kaelyn Takatafe408a72014-10-27 18:07:46 +0000668 R.clear();
669 return false;
670 }
671
Douglas Gregor5476205b2011-06-23 00:49:38 +0000672 // We didn't find anything with the given name, so try to correct
673 // for typos.
674 DeclarationName Name = R.getLookupName();
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000675 TypoCorrection Corrected = SemaRef.CorrectTypo(
676 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
677 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
678 Sema::CTK_ErrorRecovery, DC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000679 R.clear();
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000680 if (Corrected.isResolved() && !Corrected.isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000681 R.setLookupName(Corrected.getCorrection());
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000682 for (TypoCorrection::decl_iterator DI = Corrected.begin(),
683 DIEnd = Corrected.end();
684 DI != DIEnd; ++DI) {
685 R.addDecl(*DI);
686 }
687 R.resolveKind();
688
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000689 // If we're typo-correcting to an overloaded name, we don't yet have enough
690 // information to do overload resolution, so we don't know which previous
691 // declaration to point to.
Richard Smithf9b15102013-08-17 00:46:16 +0000692 if (Corrected.isOverloaded())
Craig Topperc3ec1492014-05-26 06:22:03 +0000693 Corrected.setCorrectionDecl(nullptr);
Richard Smithf9b15102013-08-17 00:46:16 +0000694 bool DroppedSpecifier =
695 Corrected.WillReplaceSpecifier() &&
696 Name.getAsString() == Corrected.getAsString(SemaRef.getLangOpts());
Kaelyn Takatadb99de22014-11-11 23:00:38 +0000697 SemaRef.diagnoseTypo(Corrected, SemaRef.PDiag(diag::err_no_member_suggest)
698 << Name << DC << DroppedSpecifier
699 << SS.getRange());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000700 }
701
702 return false;
703}
704
Richard Smitha0edd302014-05-31 00:18:32 +0000705static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
706 ExprResult &BaseExpr, bool &IsArrow,
707 SourceLocation OpLoc, CXXScopeSpec &SS,
708 Decl *ObjCImpDecl, bool HasTemplateArgs);
709
Douglas Gregor5476205b2011-06-23 00:49:38 +0000710ExprResult
711Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
712 SourceLocation OpLoc, bool IsArrow,
713 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000714 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000715 NamedDecl *FirstQualifierInScope,
716 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000717 const TemplateArgumentListInfo *TemplateArgs,
718 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000719 if (BaseType->isDependentType() ||
720 (SS.isSet() && isDependentScopeSpecifier(SS)))
721 return ActOnDependentMemberExpr(Base, BaseType,
722 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000723 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000724 NameInfo, TemplateArgs);
725
726 LookupResult R(*this, NameInfo, LookupMemberName);
727
728 // Implicit member accesses.
729 if (!Base) {
730 QualType RecordTy = BaseType;
731 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +0000732 if (LookupMemberExprInRecord(*this, R, nullptr,
733 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
734 SS, TemplateArgs != nullptr))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000735 return ExprError();
736
737 // Explicit member accesses.
738 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000739 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000740 ExprResult Result = LookupMemberExpr(
741 *this, R, BaseResult, IsArrow, OpLoc, SS,
742 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
743 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000744
745 if (BaseResult.isInvalid())
746 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000747 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000748
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000749 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000750 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000751
752 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000753 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000754
755 // LookupMemberExpr can modify Base, and thus change BaseType
756 BaseType = Base->getType();
757 }
758
759 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000760 OpLoc, IsArrow, SS, TemplateKWLoc,
Richard Smitha0edd302014-05-31 00:18:32 +0000761 FirstQualifierInScope, R, TemplateArgs,
762 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000763}
764
765static ExprResult
766BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
767 const CXXScopeSpec &SS, FieldDecl *Field,
768 DeclAccessPair FoundDecl,
769 const DeclarationNameInfo &MemberNameInfo);
770
771ExprResult
772Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
773 SourceLocation loc,
774 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000775 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000776 Expr *baseObjectExpr,
777 SourceLocation opLoc) {
778 // First, build the expression that refers to the base object.
779
780 bool baseObjectIsPointer = false;
781 Qualifiers baseQuals;
782
783 // Case 1: the base of the indirect field is not a field.
784 VarDecl *baseVariable = indirectField->getVarDecl();
785 CXXScopeSpec EmptySS;
786 if (baseVariable) {
787 assert(baseVariable->getType()->isRecordType());
788
789 // In principle we could have a member access expression that
790 // accesses an anonymous struct/union that's a static member of
791 // the base object's class. However, under the current standard,
792 // static data members cannot be anonymous structs or unions.
793 // Supporting this is as easy as building a MemberExpr here.
794 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
795
796 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
797
798 ExprResult result
799 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
800 if (result.isInvalid()) return ExprError();
801
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000802 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000803 baseObjectIsPointer = false;
804 baseQuals = baseObjectExpr->getType().getQualifiers();
805
806 // Case 2: the base of the indirect field is a field and the user
807 // wrote a member expression.
808 } else if (baseObjectExpr) {
809 // The caller provided the base object expression. Determine
810 // whether its a pointer and whether it adds any qualifiers to the
811 // anonymous struct/union fields we're looking into.
812 QualType objectType = baseObjectExpr->getType();
813
814 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
815 baseObjectIsPointer = true;
816 objectType = ptr->getPointeeType();
817 } else {
818 baseObjectIsPointer = false;
819 }
820 baseQuals = objectType.getQualifiers();
821
822 // Case 3: the base of the indirect field is a field and we should
823 // build an implicit member access.
824 } else {
825 // We've found a member of an anonymous struct/union that is
826 // inside a non-anonymous struct/union, so in a well-formed
827 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000828 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000829 if (ThisTy.isNull()) {
830 Diag(loc, diag::err_invalid_member_use_in_static_method)
831 << indirectField->getDeclName();
832 return ExprError();
833 }
834
835 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000836 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000837 baseObjectExpr
838 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
839 baseObjectIsPointer = true;
840 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
841 }
842
843 // Build the implicit member references to the field of the
844 // anonymous struct/union.
845 Expr *result = baseObjectExpr;
846 IndirectFieldDecl::chain_iterator
847 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
848
849 // Build the first member access in the chain with full information.
850 if (!baseVariable) {
851 FieldDecl *field = cast<FieldDecl>(*FI);
852
Douglas Gregor5476205b2011-06-23 00:49:38 +0000853 // Make a nameInfo that properly uses the anonymous name.
854 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
855
856 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
857 EmptySS, field, foundDecl,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000858 memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000859 if (!result)
860 return ExprError();
861
Douglas Gregor5476205b2011-06-23 00:49:38 +0000862 // FIXME: check qualified member access
863 }
864
865 // In all cases, we should now skip the first declaration in the chain.
866 ++FI;
867
868 while (FI != FEnd) {
869 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000870
Douglas Gregor5476205b2011-06-23 00:49:38 +0000871 // FIXME: these are somewhat meaningless
872 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000873 DeclAccessPair fakeFoundDecl =
874 DeclAccessPair::make(field, field->getAccess());
875
Douglas Gregor5476205b2011-06-23 00:49:38 +0000876 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Eli Friedmancccd0642013-07-16 00:01:31 +0000877 (FI == FEnd? SS : EmptySS), field,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000878 fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000879 }
880
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000881 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000882}
883
John McCall5e77d762013-04-16 07:28:30 +0000884static ExprResult
885BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
886 const CXXScopeSpec &SS,
887 MSPropertyDecl *PD,
888 const DeclarationNameInfo &NameInfo) {
889 // Property names are always simple identifiers and therefore never
890 // require any interesting additional storage.
891 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
892 S.Context.PseudoObjectTy, VK_LValue,
893 SS.getWithLocInContext(S.Context),
894 NameInfo.getLoc());
895}
896
Douglas Gregor5476205b2011-06-23 00:49:38 +0000897/// \brief Build a MemberExpr AST node.
Craig Topperc3ec1492014-05-26 06:22:03 +0000898static MemberExpr *
899BuildMemberExpr(Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
900 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
901 ValueDecl *Member, DeclAccessPair FoundDecl,
902 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
903 ExprValueKind VK, ExprObjectKind OK,
904 const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000905 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedmanfa0df832012-02-02 03:46:19 +0000906 MemberExpr *E =
907 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
908 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
909 TemplateArgs, Ty, VK, OK);
910 SemaRef.MarkMemberReferenced(E);
911 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000912}
913
914ExprResult
915Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
916 SourceLocation OpLoc, bool IsArrow,
917 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000918 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000919 NamedDecl *FirstQualifierInScope,
920 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000921 const TemplateArgumentListInfo *TemplateArgs,
922 bool SuppressQualifierCheck,
923 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000924 QualType BaseType = BaseExprType;
925 if (IsArrow) {
926 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000927 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000928 }
929 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000930
931 LambdaScopeInfo *const CurLSI = getCurLambda();
932 // If this is an implicit member reference and the overloaded
933 // name refers to both static and non-static member functions
934 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
935 // check if we should/can capture 'this'...
936 // Keep this example in mind:
937 // struct X {
938 // void f(int) { }
939 // static void f(double) { }
940 //
941 // int g() {
942 // auto L = [=](auto a) {
943 // return [](int i) {
944 // return [=](auto b) {
945 // f(b);
946 // //f(decltype(a){});
947 // };
948 // };
949 // };
950 // auto M = L(0.0);
951 // auto N = M(3);
952 // N(5.32); // OK, must not error.
953 // return 0;
954 // }
955 // };
956 //
957 if (!BaseExpr && CurLSI) {
958 SourceLocation Loc = R.getNameLoc();
959 if (SS.getRange().isValid())
960 Loc = SS.getRange().getBegin();
961 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
962 // If the enclosing function is not dependent, then this lambda is
963 // capture ready, so if we can capture this, do so.
964 if (!EnclosingFunctionCtx->isDependentContext()) {
965 // If the current lambda and all enclosing lambdas can capture 'this' -
966 // then go ahead and capture 'this' (since our unresolved overload set
967 // contains both static and non-static member functions).
968 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
969 CheckCXXThisCapture(Loc);
970 } else if (CurContext->isDependentContext()) {
971 // ... since this is an implicit member reference, that might potentially
972 // involve a 'this' capture, mark 'this' for potential capture in
973 // enclosing lambdas.
974 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
975 CurLSI->addPotentialThisCapture(Loc);
976 }
977 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000978 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
979 DeclarationName MemberName = MemberNameInfo.getName();
980 SourceLocation MemberLoc = MemberNameInfo.getLoc();
981
982 if (R.isAmbiguous())
983 return ExprError();
984
985 if (R.empty()) {
986 // Rederive where we looked up.
987 DeclContext *DC = (SS.isSet()
988 ? computeDeclContext(SS, false)
989 : BaseType->getAs<RecordType>()->getDecl());
990
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000991 if (ExtraArgs) {
992 ExprResult RetryExpr;
993 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000994 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000995 ParsedType ObjectType;
996 bool MayBePseudoDestructor = false;
997 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
998 OpLoc, tok::arrow, ObjectType,
999 MayBePseudoDestructor);
1000 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1001 CXXScopeSpec TempSS(SS);
1002 RetryExpr = ActOnMemberAccessExpr(
1003 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
1004 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
1005 ExtraArgs->HasTrailingLParen);
1006 }
1007 if (Trap.hasErrorOccurred())
1008 RetryExpr = ExprError();
1009 }
1010 if (RetryExpr.isUsable()) {
1011 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1012 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1013 return RetryExpr;
1014 }
1015 }
1016
Douglas Gregor5476205b2011-06-23 00:49:38 +00001017 Diag(R.getNameLoc(), diag::err_no_member)
1018 << MemberName << DC
1019 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1020 return ExprError();
1021 }
1022
1023 // Diagnose lookups that find only declarations from a non-base
1024 // type. This is possible for either qualified lookups (which may
1025 // have been qualified with an unrelated type) or implicit member
1026 // expressions (which were found with unqualified lookup and thus
1027 // may have come from an enclosing scope). Note that it's okay for
1028 // lookup to find declarations from a non-base type as long as those
1029 // aren't the ones picked by overload resolution.
1030 if ((SS.isSet() || !BaseExpr ||
1031 (isa<CXXThisExpr>(BaseExpr) &&
1032 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1033 !SuppressQualifierCheck &&
1034 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1035 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001036
Douglas Gregor5476205b2011-06-23 00:49:38 +00001037 // Construct an unresolved result if we in fact got an unresolved
1038 // result.
1039 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1040 // Suppress any lookup-related diagnostics; we'll do these when we
1041 // pick a member.
1042 R.suppressDiagnostics();
1043
1044 UnresolvedMemberExpr *MemExpr
1045 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1046 BaseExpr, BaseExprType,
1047 IsArrow, OpLoc,
1048 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001049 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001050 TemplateArgs, R.begin(), R.end());
1051
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001052 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001053 }
1054
1055 assert(R.isSingleResult());
1056 DeclAccessPair FoundDecl = R.begin().getPair();
1057 NamedDecl *MemberDecl = R.getFoundDecl();
1058
1059 // FIXME: diagnose the presence of template arguments now.
1060
1061 // If the decl being referenced had an error, return an error for this
1062 // sub-expr without emitting another error, in order to avoid cascading
1063 // error cases.
1064 if (MemberDecl->isInvalidDecl())
1065 return ExprError();
1066
1067 // Handle the implicit-member-access case.
1068 if (!BaseExpr) {
1069 // If this is not an instance member, convert to a non-member access.
1070 if (!MemberDecl->isCXXInstanceMember())
1071 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1072
1073 SourceLocation Loc = R.getNameLoc();
1074 if (SS.getRange().isValid())
1075 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001076 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001077 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1078 }
1079
1080 bool ShouldCheckUse = true;
1081 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1082 // Don't diagnose the use of a virtual member function unless it's
1083 // explicitly qualified.
1084 if (MD->isVirtual() && !SS.isSet())
1085 ShouldCheckUse = false;
1086 }
1087
1088 // Check the use of this member.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001089 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001090 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001091
Douglas Gregor5476205b2011-06-23 00:49:38 +00001092 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1093 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
1094 SS, FD, FoundDecl, MemberNameInfo);
1095
John McCall5e77d762013-04-16 07:28:30 +00001096 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1097 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1098 MemberNameInfo);
1099
Douglas Gregor5476205b2011-06-23 00:49:38 +00001100 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1101 // We may have found a field within an anonymous union or struct
1102 // (C++ [class.union]).
1103 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001104 FoundDecl, BaseExpr,
1105 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001106
1107 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001108 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1109 Var, FoundDecl, MemberNameInfo,
1110 Var->getType().getNonReferenceType(), VK_LValue,
1111 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001112 }
1113
1114 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1115 ExprValueKind valueKind;
1116 QualType type;
1117 if (MemberFn->isInstance()) {
1118 valueKind = VK_RValue;
1119 type = Context.BoundMemberTy;
1120 } else {
1121 valueKind = VK_LValue;
1122 type = MemberFn->getType();
1123 }
1124
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001125 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1126 MemberFn, FoundDecl, MemberNameInfo, type, valueKind,
1127 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001128 }
1129 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1130
1131 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001132 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1133 Enum, FoundDecl, MemberNameInfo, Enum->getType(),
1134 VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001135 }
1136
Douglas Gregor5476205b2011-06-23 00:49:38 +00001137 // We found something that we didn't expect. Complain.
1138 if (isa<TypeDecl>(MemberDecl))
1139 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1140 << MemberName << BaseType << int(IsArrow);
1141 else
1142 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1143 << MemberName << BaseType << int(IsArrow);
1144
1145 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1146 << MemberName;
1147 R.suppressDiagnostics();
1148 return ExprError();
1149}
1150
1151/// Given that normal member access failed on the given expression,
1152/// and given that the expression's type involves builtin-id or
1153/// builtin-Class, decide whether substituting in the redefinition
1154/// types would be profitable. The redefinition type is whatever
1155/// this translation unit tried to typedef to id/Class; we store
1156/// it to the side and then re-use it in places like this.
1157static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1158 const ObjCObjectPointerType *opty
1159 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1160 if (!opty) return false;
1161
1162 const ObjCObjectType *ty = opty->getObjectType();
1163
1164 QualType redef;
1165 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001166 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001167 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001168 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001169 } else {
1170 return false;
1171 }
1172
1173 // Do the substitution as long as the redefinition type isn't just a
1174 // possibly-qualified pointer to builtin-id or builtin-Class again.
1175 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001176 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001177 return false;
1178
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001179 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001180 return true;
1181}
1182
John McCall50a2c2c2011-10-11 23:14:30 +00001183static bool isRecordType(QualType T) {
1184 return T->isRecordType();
1185}
1186static bool isPointerToRecordType(QualType T) {
1187 if (const PointerType *PT = T->getAs<PointerType>())
1188 return PT->getPointeeType()->isRecordType();
1189 return false;
1190}
1191
Richard Smithcab9a7d2011-10-26 19:06:56 +00001192/// Perform conversions on the LHS of a member access expression.
1193ExprResult
1194Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001195 if (IsArrow && !Base->getType()->isFunctionType())
1196 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001197
Eli Friedman9a766c42012-01-13 02:20:01 +00001198 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001199}
1200
Douglas Gregor5476205b2011-06-23 00:49:38 +00001201/// Look up the given member of the given non-type-dependent
1202/// expression. This can return in one of two ways:
1203/// * If it returns a sentinel null-but-valid result, the caller will
1204/// assume that lookup was performed and the results written into
1205/// the provided structure. It will take over from there.
1206/// * Otherwise, the returned expression will be produced in place of
1207/// an ordinary member expression.
1208///
1209/// The ObjCImpDecl bit is a gross hack that will need to be properly
1210/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001211static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1212 ExprResult &BaseExpr, bool &IsArrow,
1213 SourceLocation OpLoc, CXXScopeSpec &SS,
1214 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001215 assert(BaseExpr.get() && "no base expression");
1216
1217 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001218 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001219 if (BaseExpr.isInvalid())
1220 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001221
Douglas Gregor5476205b2011-06-23 00:49:38 +00001222 QualType BaseType = BaseExpr.get()->getType();
1223 assert(!BaseType->isDependentType());
1224
1225 DeclarationName MemberName = R.getLookupName();
1226 SourceLocation MemberLoc = R.getNameLoc();
1227
1228 // For later type-checking purposes, turn arrow accesses into dot
1229 // accesses. The only access type we support that doesn't follow
1230 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1231 // and those never use arrows, so this is unaffected.
1232 if (IsArrow) {
1233 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1234 BaseType = Ptr->getPointeeType();
1235 else if (const ObjCObjectPointerType *Ptr
1236 = BaseType->getAs<ObjCObjectPointerType>())
1237 BaseType = Ptr->getPointeeType();
1238 else if (BaseType->isRecordType()) {
1239 // Recover from arrow accesses to records, e.g.:
1240 // struct MyRecord foo;
1241 // foo->bar
1242 // This is actually well-formed in C++ if MyRecord has an
1243 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001244 // by now--or a diagnostic message already issued if a problem
1245 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001246 if (!S.getLangOpts().CPlusPlus) {
1247 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001248 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1249 << FixItHint::CreateReplacement(OpLoc, ".");
1250 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001251 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001252 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001253 goto fail;
1254 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001255 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001256 << BaseType << BaseExpr.get()->getSourceRange();
1257 return ExprError();
1258 }
1259 }
1260
1261 // Handle field access to simple records.
1262 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001263 TypoExpr *TE = nullptr;
Kaelyn Takata5c3dc4b2014-11-11 23:26:54 +00001264 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
1265 OpLoc, IsArrow, SS, HasTemplateArgs, &TE))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001266 return ExprError();
1267
1268 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001269 // the lookup result was filled in. If typo correction was attempted and
1270 // failed, the lookup result will have been cleared--that combined with the
1271 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1272 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001273 }
1274
1275 // Handle ivar access to Objective-C objects.
1276 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001277 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001278 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001279 << 1 << SS.getScopeRep()
1280 << FixItHint::CreateRemoval(SS.getRange());
1281 SS.clear();
1282 }
Richard Smitha0edd302014-05-31 00:18:32 +00001283
Douglas Gregor5476205b2011-06-23 00:49:38 +00001284 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1285
1286 // There are three cases for the base type:
1287 // - builtin id (qualified or unqualified)
1288 // - builtin Class (qualified or unqualified)
1289 // - an interface
1290 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1291 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001292 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001293 (OTy->isObjCId() || OTy->isObjCClass()))
1294 goto fail;
1295 // There's an implicit 'isa' ivar on all objects.
1296 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001297 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001298 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001299 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1300 OpLoc, S.Context.getObjCClassType());
1301 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1302 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001303 ObjCImpDecl, HasTemplateArgs);
1304 goto fail;
1305 }
Richard Smitha0edd302014-05-31 00:18:32 +00001306
1307 if (S.RequireCompleteType(OpLoc, BaseType,
1308 diag::err_typecheck_incomplete_tag,
1309 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001310 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001311
1312 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001313 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1314
1315 if (!IV) {
1316 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001317 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1318 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001319 if (TypoCorrection Corrected = S.CorrectTypo(
1320 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001321 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001322 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001323 S.diagnoseTypo(
1324 Corrected,
1325 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1326 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001327
Ted Kremenek679b4782012-03-17 00:53:39 +00001328 // Figure out the class that declares the ivar.
1329 assert(!ClassDeclared);
1330 Decl *D = cast<Decl>(IV->getDeclContext());
1331 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1332 D = CAT->getClassInterface();
1333 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001334 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001335 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001336 S.Diag(MemberLoc, diag::err_property_found_suggest)
1337 << Member << BaseExpr.get()->getType()
1338 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001339 return ExprError();
1340 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001341
Richard Smitha0edd302014-05-31 00:18:32 +00001342 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1343 << IDecl->getDeclName() << MemberName
1344 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001345 return ExprError();
1346 }
1347 }
Richard Smitha0edd302014-05-31 00:18:32 +00001348
Ted Kremenek679b4782012-03-17 00:53:39 +00001349 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001350
1351 // If the decl being referenced had an error, return an error for this
1352 // sub-expr without emitting another error, in order to avoid cascading
1353 // error cases.
1354 if (IV->isInvalidDecl())
1355 return ExprError();
1356
1357 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001358 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001359 return ExprError();
1360 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1361 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001362 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001363 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001364 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001365 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001366 // Case of a c-function declared inside an objc implementation.
1367 // FIXME: For a c-style function nested inside an objc implementation
1368 // class, there is no implementation context available, so we pass
1369 // down the context as argument to this routine. Ideally, this context
1370 // need be passed down in the AST node and somehow calculated from the
1371 // AST for a function decl.
1372 if (ObjCImplementationDecl *IMPD =
1373 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1374 ClassOfMethodDecl = IMPD->getClassInterface();
1375 else if (ObjCCategoryImplDecl* CatImplClass =
1376 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1377 ClassOfMethodDecl = CatImplClass->getClassInterface();
1378 }
Richard Smitha0edd302014-05-31 00:18:32 +00001379 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001380 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1381 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1382 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001383 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001384 << IV->getDeclName();
1385 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1386 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001387 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1388 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001389 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001390 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001391 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001392 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001393 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1394 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1395 if (UO->getOpcode() == UO_Deref)
1396 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1397
1398 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001399 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001400 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001401 warn = false;
1402 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001403 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001404 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001405 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001406 ObjCMethodFamily MF = MD->getMethodFamily();
1407 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001408 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001409 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001410 }
1411 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001412 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001413 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001414
Richard Smitha0edd302014-05-31 00:18:32 +00001415 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1416 IV, IV->getType(), MemberLoc, OpLoc, BaseExpr.get(), IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001417
Richard Smitha0edd302014-05-31 00:18:32 +00001418 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001419 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001420 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001421 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001422 }
1423 }
1424
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001425 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001426 }
1427
1428 // Objective-C property access.
1429 const ObjCObjectPointerType *OPT;
1430 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001431 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001432 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1433 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001434 SS.clear();
1435 }
1436
Douglas Gregor5476205b2011-06-23 00:49:38 +00001437 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001438 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001439 if (BaseExpr.isInvalid())
1440 return ExprError();
1441
Richard Smitha0edd302014-05-31 00:18:32 +00001442 assert(S.Context.hasSameUnqualifiedType(BaseType,
1443 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001444
1445 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1446
1447 const ObjCObjectType *OT = OPT->getObjectType();
1448
1449 // id, with and without qualifiers.
1450 if (OT->isObjCId()) {
1451 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001452 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1453 if (Decl *PMDecl =
1454 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001455 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1456 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001457 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001458 return ExprError();
1459
Richard Smitha0edd302014-05-31 00:18:32 +00001460 return new (S.Context)
1461 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001462 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001463 }
1464
1465 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1466 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001467 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001468 return ExprError();
1469 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001470 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1471 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001472 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001473 ObjCMethodDecl *SMD = nullptr;
1474 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001475 /*Property id*/ nullptr,
1476 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001477 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001478
1479 return new (S.Context)
1480 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001481 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001482 }
1483 }
1484 // Use of id.member can only be for a property reference. Do not
1485 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001486 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1487 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001488 ObjCImpDecl, HasTemplateArgs);
1489
Richard Smitha0edd302014-05-31 00:18:32 +00001490 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001491 << MemberName << BaseType);
1492 }
1493
1494 // 'Class', unqualified only.
1495 if (OT->isObjCClass()) {
1496 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001497 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001498 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001499 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1500 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001501 ObjCImpDecl, HasTemplateArgs);
1502
1503 goto fail;
1504 }
1505
1506 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001507 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001508 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1509 ObjCMethodDecl *Getter;
1510 if ((Getter = IFace->lookupClassMethod(Sel))) {
1511 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001512 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001513 return ExprError();
1514 } else
1515 Getter = IFace->lookupPrivateMethod(Sel, false);
1516 // If we found a getter then this may be a valid dot-reference, we
1517 // will look for the matching setter, in case it is needed.
1518 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001519 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1520 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001521 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001522 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1523 if (!Setter) {
1524 // If this reference is in an @implementation, also check for 'private'
1525 // methods.
1526 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1527 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001528
Richard Smitha0edd302014-05-31 00:18:32 +00001529 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001530 return ExprError();
1531
1532 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001533 return new (S.Context) ObjCPropertyRefExpr(
1534 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1535 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001536 }
1537
Richard Smitha0edd302014-05-31 00:18:32 +00001538 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1539 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001540 ObjCImpDecl, HasTemplateArgs);
1541
Richard Smitha0edd302014-05-31 00:18:32 +00001542 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001543 << MemberName << BaseType);
1544 }
1545
1546 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001547 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1548 MemberLoc, SourceLocation(), QualType(),
1549 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001550 }
1551
1552 // Handle 'field access' to vectors, such as 'V.xx'.
1553 if (BaseType->isExtVectorType()) {
1554 // FIXME: this expr should store IsArrow.
1555 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1556 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
Richard Smitha0edd302014-05-31 00:18:32 +00001557 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001558 Member, MemberLoc);
1559 if (ret.isNull())
1560 return ExprError();
1561
Richard Smitha0edd302014-05-31 00:18:32 +00001562 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001563 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001564 }
1565
1566 // Adjust builtin-sel to the appropriate redefinition type if that's
1567 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001568 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1569 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1570 BaseExpr = S.ImpCastExprToType(
1571 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1572 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001573 ObjCImpDecl, HasTemplateArgs);
1574 }
1575
1576 // Failure cases.
1577 fail:
1578
1579 // Recover from dot accesses to pointers, e.g.:
1580 // type *foo;
1581 // foo.bar
1582 // This is actually well-formed in two cases:
1583 // - 'type' is an Objective C type
1584 // - 'bar' is a pseudo-destructor name which happens to refer to
1585 // the appropriate pointer type
1586 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1587 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1588 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001589 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1590 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001591 << FixItHint::CreateReplacement(OpLoc, "->");
1592
1593 // Recurse as an -> access.
1594 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001595 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001596 ObjCImpDecl, HasTemplateArgs);
1597 }
1598 }
1599
1600 // If the user is trying to apply -> or . to a function name, it's probably
1601 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001602 if (S.tryToRecoverWithCall(
1603 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1604 /*complain*/ false,
1605 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001606 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001607 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001608 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1609 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001610 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001611 }
1612
Richard Smitha0edd302014-05-31 00:18:32 +00001613 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001614 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001615
1616 return ExprError();
1617}
1618
1619/// The main callback when the parser finds something like
1620/// expression . [nested-name-specifier] identifier
1621/// expression -> [nested-name-specifier] identifier
1622/// where 'identifier' encompasses a fairly broad spectrum of
1623/// possibilities, including destructor and operator references.
1624///
1625/// \param OpKind either tok::arrow or tok::period
1626/// \param HasTrailingLParen whether the next token is '(', which
1627/// is used to diagnose mis-uses of special members that can
1628/// only be called
James Dennett2a4d13c2012-06-15 07:13:21 +00001629/// \param ObjCImpDecl the current Objective-C \@implementation
1630/// decl; this is an ugly hack around the fact that Objective-C
1631/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001632ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1633 SourceLocation OpLoc,
1634 tok::TokenKind OpKind,
1635 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001636 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001637 UnqualifiedId &Id,
1638 Decl *ObjCImpDecl,
1639 bool HasTrailingLParen) {
1640 if (SS.isSet() && SS.isInvalid())
1641 return ExprError();
1642
Richard Smitha0edd302014-05-31 00:18:32 +00001643 // The only way a reference to a destructor can be used is to
1644 // immediately call it. If the next token is not a '(', produce
1645 // a diagnostic and build the call now.
1646 if (!HasTrailingLParen &&
1647 Id.getKind() == UnqualifiedId::IK_DestructorName) {
1648 ExprResult DtorAccess =
1649 ActOnMemberAccessExpr(S, Base, OpLoc, OpKind, SS, TemplateKWLoc, Id,
1650 ObjCImpDecl, /*HasTrailingLParen*/true);
1651 if (DtorAccess.isInvalid())
1652 return DtorAccess;
1653 return DiagnoseDtorReference(Id.getLocStart(), DtorAccess.get());
1654 }
1655
Douglas Gregor5476205b2011-06-23 00:49:38 +00001656 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001657 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001658 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1659 Diag(Id.getSourceRange().getBegin(),
1660 diag::ext_ms_explicit_constructor_call);
1661
1662 TemplateArgumentListInfo TemplateArgsBuffer;
1663
1664 // Decompose the name into its component parts.
1665 DeclarationNameInfo NameInfo;
1666 const TemplateArgumentListInfo *TemplateArgs;
1667 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1668 NameInfo, TemplateArgs);
1669
1670 DeclarationName Name = NameInfo.getName();
1671 bool IsArrow = (OpKind == tok::arrow);
1672
1673 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001674 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001675
1676 // This is a postfix expression, so get rid of ParenListExprs.
1677 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1678 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001679 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001680
1681 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1682 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001683 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1684 TemplateKWLoc, FirstQualifierInScope,
1685 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001686 }
1687
Richard Smitha0edd302014-05-31 00:18:32 +00001688 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl,
1689 HasTrailingLParen};
1690 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1691 TemplateKWLoc, FirstQualifierInScope,
1692 NameInfo, TemplateArgs, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001693}
1694
1695static ExprResult
1696BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1697 const CXXScopeSpec &SS, FieldDecl *Field,
1698 DeclAccessPair FoundDecl,
1699 const DeclarationNameInfo &MemberNameInfo) {
1700 // x.a is an l-value if 'a' has a reference type. Otherwise:
1701 // x.a is an l-value/x-value/pr-value if the base is (and note
1702 // that *x is always an l-value), except that if the base isn't
1703 // an ordinary object then we must have an rvalue.
1704 ExprValueKind VK = VK_LValue;
1705 ExprObjectKind OK = OK_Ordinary;
1706 if (!IsArrow) {
1707 if (BaseExpr->getObjectKind() == OK_Ordinary)
1708 VK = BaseExpr->getValueKind();
1709 else
1710 VK = VK_RValue;
1711 }
1712 if (VK != VK_RValue && Field->isBitField())
1713 OK = OK_BitField;
1714
1715 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1716 QualType MemberType = Field->getType();
1717 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1718 MemberType = Ref->getPointeeType();
1719 VK = VK_LValue;
1720 } else {
1721 QualType BaseType = BaseExpr->getType();
1722 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001723
Douglas Gregor5476205b2011-06-23 00:49:38 +00001724 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001725
Douglas Gregor5476205b2011-06-23 00:49:38 +00001726 // GC attributes are never picked up by members.
1727 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001728
Douglas Gregor5476205b2011-06-23 00:49:38 +00001729 // CVR attributes from the base are picked up by members,
1730 // except that 'mutable' members don't pick up 'const'.
1731 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001732
Douglas Gregor5476205b2011-06-23 00:49:38 +00001733 Qualifiers MemberQuals
1734 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001735
Douglas Gregor5476205b2011-06-23 00:49:38 +00001736 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001737
1738
Douglas Gregor5476205b2011-06-23 00:49:38 +00001739 Qualifiers Combined = BaseQuals + MemberQuals;
1740 if (Combined != MemberQuals)
1741 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1742 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001743
Daniel Jasper0baec5492012-06-06 08:32:04 +00001744 S.UnusedPrivateFields.remove(Field);
1745
Douglas Gregor5476205b2011-06-23 00:49:38 +00001746 ExprResult Base =
1747 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1748 FoundDecl, Field);
1749 if (Base.isInvalid())
1750 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001751 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, SS,
1752 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1753 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001754}
1755
1756/// Builds an implicit member access expression. The current context
1757/// is known to be an instance method, and the given unqualified lookup
1758/// set is known to contain only instance members, at least one of which
1759/// is from an appropriate type.
1760ExprResult
1761Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001762 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001763 LookupResult &R,
1764 const TemplateArgumentListInfo *TemplateArgs,
1765 bool IsKnownInstance) {
1766 assert(!R.empty() && !R.isAmbiguous());
1767
1768 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001769
Douglas Gregor5476205b2011-06-23 00:49:38 +00001770 // If this is known to be an instance access, go ahead and build an
1771 // implicit 'this' expression now.
1772 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001773 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001774 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001775
1776 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001777 if (IsKnownInstance) {
1778 SourceLocation Loc = R.getNameLoc();
1779 if (SS.getRange().isValid())
1780 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001781 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001782 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1783 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001784
Douglas Gregor5476205b2011-06-23 00:49:38 +00001785 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1786 /*OpLoc*/ SourceLocation(),
1787 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001788 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001789 /*FirstQualifierInScope*/ nullptr,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001790 R, TemplateArgs);
1791}