blob: 0d7f3c641d36b007b1cb443b38f258e33f7d8726 [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 {
540 public:
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000541 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
542 : Record(RTy->getDecl()) {}
543
Craig Toppere14c0f82014-03-12 04:55:44 +0000544 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000545 NamedDecl *ND = candidate.getCorrectionDecl();
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000546 // Don't accept candidates that cannot be member functions, constants,
547 // variables, or templates.
548 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
549 return false;
550
551 // Accept candidates that occur in the current record.
552 if (Record->containsDecl(ND))
553 return true;
554
555 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
556 // Accept candidates that occur in any of the current class' base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000557 for (const auto &BS : RD->bases()) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000558 if (const RecordType *BSTy = dyn_cast_or_null<RecordType>(
Aaron Ballman574705e2014-03-13 15:41:46 +0000559 BS.getType().getTypePtrOrNull())) {
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000560 if (BSTy->getDecl()->containsDecl(ND))
561 return true;
562 }
563 }
564 }
565
566 return false;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000567 }
Kaelyn Uhrain8aa8da82013-10-19 00:05:00 +0000568
569 private:
570 const RecordDecl *const Record;
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000571};
572
Kaelyn Takatafe408a72014-10-27 18:07:46 +0000573class MemberTypoDiags {
574 Sema &SemaRef;
575 DeclContext *Ctx;
576 DeclarationName Typo;
577 SourceLocation TypoLoc;
578 SourceRange BaseRange;
579 SourceRange ScopeSpecLoc;
580 unsigned DiagnosticID;
581 unsigned NoSuggestDiagnosticID;
582
583public:
584 MemberTypoDiags(Sema &SemaRef, DeclContext *Ctx, DeclarationName Typo,
585 SourceLocation TypoLoc, SourceRange BaseRange,
586 CXXScopeSpec &SS, unsigned DiagnosticID,
587 unsigned NoSuggestDiagnosticID)
588 : SemaRef(SemaRef), Ctx(Ctx), Typo(Typo), TypoLoc(TypoLoc), BaseRange(BaseRange),
589 ScopeSpecLoc(SS.getRange()), DiagnosticID(DiagnosticID),
590 NoSuggestDiagnosticID(NoSuggestDiagnosticID) {}
591
592 void operator()(const TypoCorrection &TC) {
593 if (TC) {
594 assert(!TC.isKeyword() && "Got a keyword as a correction for a member!");
595 bool DroppedSpecifier =
596 TC.WillReplaceSpecifier() &&
597 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
598 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(DiagnosticID) << Typo << Ctx
599 << DroppedSpecifier
600 << ScopeSpecLoc);
601 } else {
602 SemaRef.Diag(TypoLoc, NoSuggestDiagnosticID) << Typo << Ctx << BaseRange;
603 }
604 }
605};
606
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +0000607}
608
Kaelyn Takatafe408a72014-10-27 18:07:46 +0000609static bool LookupMemberExprInRecord(
610 Sema &SemaRef, LookupResult &R, SourceRange BaseRange,
611 const RecordType *RTy, SourceLocation OpLoc, CXXScopeSpec &SS,
612 bool HasTemplateArgs, TypoExpr **TE = nullptr,
613 Sema::TypoRecoveryCallback TRC = nullptr) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000614 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregor3024f072012-04-16 07:05:22 +0000615 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
616 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +0000617 diag::err_typecheck_incomplete_tag,
618 BaseRange))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000619 return true;
620
621 if (HasTemplateArgs) {
622 // LookupTemplateName doesn't expect these both to exist simultaneously.
623 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
624
625 bool MOUS;
Craig Topperc3ec1492014-05-26 06:22:03 +0000626 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000627 return false;
628 }
629
630 DeclContext *DC = RDecl;
631 if (SS.isSet()) {
632 // If the member name was a qualified-id, look into the
633 // nested-name-specifier.
634 DC = SemaRef.computeDeclContext(SS, false);
635
636 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
637 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
638 << SS.getRange() << DC;
639 return true;
640 }
641
642 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
643
644 if (!isa<TypeDecl>(DC)) {
645 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
646 << DC << SS.getRange();
647 return true;
648 }
649 }
650
651 // The record definition is complete, now look up the member.
652 SemaRef.LookupQualifiedName(R, DC);
653
654 if (!R.empty())
655 return false;
656
Kaelyn Takatafe408a72014-10-27 18:07:46 +0000657 if (TE && SemaRef.getLangOpts().CPlusPlus) {
658 // TODO: C cannot handle TypoExpr nodes because the C code paths do not know
659 // what to do with dependent types e.g. on the LHS of an assigment.
660 *TE = SemaRef.CorrectTypoDelayed(
661 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
662 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
663 MemberTypoDiags(SemaRef, DC, R.getLookupName(), R.getNameLoc(),
664 BaseRange, SS, diag::err_no_member_suggest,
665 diag::err_no_member),
666 TRC, Sema::CTK_ErrorRecovery, DC);
667 R.clear();
668 return false;
669 }
670
Douglas Gregor5476205b2011-06-23 00:49:38 +0000671 // We didn't find anything with the given name, so try to correct
672 // for typos.
673 DeclarationName Name = R.getLookupName();
Kaelyn Takata89c881b2014-10-27 18:07:29 +0000674 TypoCorrection Corrected =
675 SemaRef.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
676 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
677 Sema::CTK_ErrorRecovery, DC);
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000678 R.clear();
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000679 if (Corrected.isResolved() && !Corrected.isKeyword()) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +0000680 R.setLookupName(Corrected.getCorrection());
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000681 for (TypoCorrection::decl_iterator DI = Corrected.begin(),
682 DIEnd = Corrected.end();
683 DI != DIEnd; ++DI) {
684 R.addDecl(*DI);
685 }
686 R.resolveKind();
687
Nick Lewyckyd1b0df42013-05-07 22:14:37 +0000688 // If we're typo-correcting to an overloaded name, we don't yet have enough
689 // information to do overload resolution, so we don't know which previous
690 // declaration to point to.
Richard Smithf9b15102013-08-17 00:46:16 +0000691 if (Corrected.isOverloaded())
Craig Topperc3ec1492014-05-26 06:22:03 +0000692 Corrected.setCorrectionDecl(nullptr);
Richard Smithf9b15102013-08-17 00:46:16 +0000693 bool DroppedSpecifier =
694 Corrected.WillReplaceSpecifier() &&
695 Name.getAsString() == Corrected.getAsString(SemaRef.getLangOpts());
696 SemaRef.diagnoseTypo(Corrected,
697 SemaRef.PDiag(diag::err_no_member_suggest)
698 << Name << DC << DroppedSpecifier << SS.getRange());
Douglas Gregor5476205b2011-06-23 00:49:38 +0000699 }
700
701 return false;
702}
703
Richard Smitha0edd302014-05-31 00:18:32 +0000704static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
705 ExprResult &BaseExpr, bool &IsArrow,
706 SourceLocation OpLoc, CXXScopeSpec &SS,
707 Decl *ObjCImpDecl, bool HasTemplateArgs);
708
Douglas Gregor5476205b2011-06-23 00:49:38 +0000709ExprResult
710Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
711 SourceLocation OpLoc, bool IsArrow,
712 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000713 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000714 NamedDecl *FirstQualifierInScope,
715 const DeclarationNameInfo &NameInfo,
Richard Smitha0edd302014-05-31 00:18:32 +0000716 const TemplateArgumentListInfo *TemplateArgs,
717 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000718 if (BaseType->isDependentType() ||
719 (SS.isSet() && isDependentScopeSpecifier(SS)))
720 return ActOnDependentMemberExpr(Base, BaseType,
721 IsArrow, OpLoc,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000722 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000723 NameInfo, TemplateArgs);
724
725 LookupResult R(*this, NameInfo, LookupMemberName);
726
727 // Implicit member accesses.
728 if (!Base) {
729 QualType RecordTy = BaseType;
730 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
731 if (LookupMemberExprInRecord(*this, R, SourceRange(),
732 RecordTy->getAs<RecordType>(),
Craig Topperc3ec1492014-05-26 06:22:03 +0000733 OpLoc, SS, TemplateArgs != nullptr))
Douglas Gregor5476205b2011-06-23 00:49:38 +0000734 return ExprError();
735
736 // Explicit member accesses.
737 } else {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000738 ExprResult BaseResult = Base;
Richard Smitha0edd302014-05-31 00:18:32 +0000739 ExprResult Result = LookupMemberExpr(
740 *this, R, BaseResult, IsArrow, OpLoc, SS,
741 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
742 TemplateArgs != nullptr);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000743
744 if (BaseResult.isInvalid())
745 return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000746 Base = BaseResult.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000747
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000748 if (Result.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +0000749 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000750
751 if (Result.get())
Benjamin Kramer62b95d82012-08-23 21:35:17 +0000752 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000753
754 // LookupMemberExpr can modify Base, and thus change BaseType
755 BaseType = Base->getType();
756 }
757
758 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000759 OpLoc, IsArrow, SS, TemplateKWLoc,
Richard Smitha0edd302014-05-31 00:18:32 +0000760 FirstQualifierInScope, R, TemplateArgs,
761 false, ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000762}
763
764static ExprResult
765BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
766 const CXXScopeSpec &SS, FieldDecl *Field,
767 DeclAccessPair FoundDecl,
768 const DeclarationNameInfo &MemberNameInfo);
769
770ExprResult
771Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
772 SourceLocation loc,
773 IndirectFieldDecl *indirectField,
Eli Friedmancccd0642013-07-16 00:01:31 +0000774 DeclAccessPair foundDecl,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000775 Expr *baseObjectExpr,
776 SourceLocation opLoc) {
777 // First, build the expression that refers to the base object.
778
779 bool baseObjectIsPointer = false;
780 Qualifiers baseQuals;
781
782 // Case 1: the base of the indirect field is not a field.
783 VarDecl *baseVariable = indirectField->getVarDecl();
784 CXXScopeSpec EmptySS;
785 if (baseVariable) {
786 assert(baseVariable->getType()->isRecordType());
787
788 // In principle we could have a member access expression that
789 // accesses an anonymous struct/union that's a static member of
790 // the base object's class. However, under the current standard,
791 // static data members cannot be anonymous structs or unions.
792 // Supporting this is as easy as building a MemberExpr here.
793 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
794
795 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
796
797 ExprResult result
798 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
799 if (result.isInvalid()) return ExprError();
800
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000801 baseObjectExpr = result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000802 baseObjectIsPointer = false;
803 baseQuals = baseObjectExpr->getType().getQualifiers();
804
805 // Case 2: the base of the indirect field is a field and the user
806 // wrote a member expression.
807 } else if (baseObjectExpr) {
808 // The caller provided the base object expression. Determine
809 // whether its a pointer and whether it adds any qualifiers to the
810 // anonymous struct/union fields we're looking into.
811 QualType objectType = baseObjectExpr->getType();
812
813 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
814 baseObjectIsPointer = true;
815 objectType = ptr->getPointeeType();
816 } else {
817 baseObjectIsPointer = false;
818 }
819 baseQuals = objectType.getQualifiers();
820
821 // Case 3: the base of the indirect field is a field and we should
822 // build an implicit member access.
823 } else {
824 // We've found a member of an anonymous struct/union that is
825 // inside a non-anonymous struct/union, so in a well-formed
826 // program our base object expression is "this".
Douglas Gregor09deffa2011-10-18 16:47:30 +0000827 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000828 if (ThisTy.isNull()) {
829 Diag(loc, diag::err_invalid_member_use_in_static_method)
830 << indirectField->getDeclName();
831 return ExprError();
832 }
833
834 // Our base object expression is "this".
Eli Friedman73a04092012-01-07 04:59:52 +0000835 CheckCXXThisCapture(loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +0000836 baseObjectExpr
837 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
838 baseObjectIsPointer = true;
839 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
840 }
841
842 // Build the implicit member references to the field of the
843 // anonymous struct/union.
844 Expr *result = baseObjectExpr;
845 IndirectFieldDecl::chain_iterator
846 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
847
848 // Build the first member access in the chain with full information.
849 if (!baseVariable) {
850 FieldDecl *field = cast<FieldDecl>(*FI);
851
Douglas Gregor5476205b2011-06-23 00:49:38 +0000852 // Make a nameInfo that properly uses the anonymous name.
853 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
854
855 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
856 EmptySS, field, foundDecl,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000857 memberNameInfo).get();
Eli Friedmancccd0642013-07-16 00:01:31 +0000858 if (!result)
859 return ExprError();
860
Douglas Gregor5476205b2011-06-23 00:49:38 +0000861 // FIXME: check qualified member access
862 }
863
864 // In all cases, we should now skip the first declaration in the chain.
865 ++FI;
866
867 while (FI != FEnd) {
868 FieldDecl *field = cast<FieldDecl>(*FI++);
Eli Friedmancccd0642013-07-16 00:01:31 +0000869
Douglas Gregor5476205b2011-06-23 00:49:38 +0000870 // FIXME: these are somewhat meaningless
871 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
Eli Friedmancccd0642013-07-16 00:01:31 +0000872 DeclAccessPair fakeFoundDecl =
873 DeclAccessPair::make(field, field->getAccess());
874
Douglas Gregor5476205b2011-06-23 00:49:38 +0000875 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
Eli Friedmancccd0642013-07-16 00:01:31 +0000876 (FI == FEnd? SS : EmptySS), field,
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000877 fakeFoundDecl, memberNameInfo).get();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000878 }
879
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000880 return result;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000881}
882
John McCall5e77d762013-04-16 07:28:30 +0000883static ExprResult
884BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
885 const CXXScopeSpec &SS,
886 MSPropertyDecl *PD,
887 const DeclarationNameInfo &NameInfo) {
888 // Property names are always simple identifiers and therefore never
889 // require any interesting additional storage.
890 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
891 S.Context.PseudoObjectTy, VK_LValue,
892 SS.getWithLocInContext(S.Context),
893 NameInfo.getLoc());
894}
895
Douglas Gregor5476205b2011-06-23 00:49:38 +0000896/// \brief Build a MemberExpr AST node.
Craig Topperc3ec1492014-05-26 06:22:03 +0000897static MemberExpr *
898BuildMemberExpr(Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
899 const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
900 ValueDecl *Member, DeclAccessPair FoundDecl,
901 const DeclarationNameInfo &MemberNameInfo, QualType Ty,
902 ExprValueKind VK, ExprObjectKind OK,
903 const TemplateArgumentListInfo *TemplateArgs = nullptr) {
Richard Smith08b12f12011-10-27 22:11:44 +0000904 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedmanfa0df832012-02-02 03:46:19 +0000905 MemberExpr *E =
906 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
907 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
908 TemplateArgs, Ty, VK, OK);
909 SemaRef.MarkMemberReferenced(E);
910 return E;
Douglas Gregor5476205b2011-06-23 00:49:38 +0000911}
912
913ExprResult
914Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
915 SourceLocation OpLoc, bool IsArrow,
916 const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +0000917 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +0000918 NamedDecl *FirstQualifierInScope,
919 LookupResult &R,
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000920 const TemplateArgumentListInfo *TemplateArgs,
921 bool SuppressQualifierCheck,
922 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +0000923 QualType BaseType = BaseExprType;
924 if (IsArrow) {
925 assert(BaseType->isPointerType());
John McCall526ab472011-10-25 17:37:35 +0000926 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor5476205b2011-06-23 00:49:38 +0000927 }
928 R.setBaseObjectType(BaseType);
Faisal Valia17d19f2013-11-07 05:17:06 +0000929
930 LambdaScopeInfo *const CurLSI = getCurLambda();
931 // If this is an implicit member reference and the overloaded
932 // name refers to both static and non-static member functions
933 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
934 // check if we should/can capture 'this'...
935 // Keep this example in mind:
936 // struct X {
937 // void f(int) { }
938 // static void f(double) { }
939 //
940 // int g() {
941 // auto L = [=](auto a) {
942 // return [](int i) {
943 // return [=](auto b) {
944 // f(b);
945 // //f(decltype(a){});
946 // };
947 // };
948 // };
949 // auto M = L(0.0);
950 // auto N = M(3);
951 // N(5.32); // OK, must not error.
952 // return 0;
953 // }
954 // };
955 //
956 if (!BaseExpr && CurLSI) {
957 SourceLocation Loc = R.getNameLoc();
958 if (SS.getRange().isValid())
959 Loc = SS.getRange().getBegin();
960 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
961 // If the enclosing function is not dependent, then this lambda is
962 // capture ready, so if we can capture this, do so.
963 if (!EnclosingFunctionCtx->isDependentContext()) {
964 // If the current lambda and all enclosing lambdas can capture 'this' -
965 // then go ahead and capture 'this' (since our unresolved overload set
966 // contains both static and non-static member functions).
967 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
968 CheckCXXThisCapture(Loc);
969 } else if (CurContext->isDependentContext()) {
970 // ... since this is an implicit member reference, that might potentially
971 // involve a 'this' capture, mark 'this' for potential capture in
972 // enclosing lambdas.
973 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
974 CurLSI->addPotentialThisCapture(Loc);
975 }
976 }
Douglas Gregor5476205b2011-06-23 00:49:38 +0000977 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
978 DeclarationName MemberName = MemberNameInfo.getName();
979 SourceLocation MemberLoc = MemberNameInfo.getLoc();
980
981 if (R.isAmbiguous())
982 return ExprError();
983
984 if (R.empty()) {
985 // Rederive where we looked up.
986 DeclContext *DC = (SS.isSet()
987 ? computeDeclContext(SS, false)
988 : BaseType->getAs<RecordType>()->getDecl());
989
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000990 if (ExtraArgs) {
991 ExprResult RetryExpr;
992 if (!IsArrow && BaseExpr) {
Kaelyn Uhraind4ea98a2012-05-01 01:17:53 +0000993 SFINAETrap Trap(*this, true);
Kaelyn Uhrain76e07342012-04-25 19:49:54 +0000994 ParsedType ObjectType;
995 bool MayBePseudoDestructor = false;
996 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
997 OpLoc, tok::arrow, ObjectType,
998 MayBePseudoDestructor);
999 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
1000 CXXScopeSpec TempSS(SS);
1001 RetryExpr = ActOnMemberAccessExpr(
1002 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
1003 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
1004 ExtraArgs->HasTrailingLParen);
1005 }
1006 if (Trap.hasErrorOccurred())
1007 RetryExpr = ExprError();
1008 }
1009 if (RetryExpr.isUsable()) {
1010 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
1011 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
1012 return RetryExpr;
1013 }
1014 }
1015
Douglas Gregor5476205b2011-06-23 00:49:38 +00001016 Diag(R.getNameLoc(), diag::err_no_member)
1017 << MemberName << DC
1018 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1019 return ExprError();
1020 }
1021
1022 // Diagnose lookups that find only declarations from a non-base
1023 // type. This is possible for either qualified lookups (which may
1024 // have been qualified with an unrelated type) or implicit member
1025 // expressions (which were found with unqualified lookup and thus
1026 // may have come from an enclosing scope). Note that it's okay for
1027 // lookup to find declarations from a non-base type as long as those
1028 // aren't the ones picked by overload resolution.
1029 if ((SS.isSet() || !BaseExpr ||
1030 (isa<CXXThisExpr>(BaseExpr) &&
1031 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1032 !SuppressQualifierCheck &&
1033 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1034 return ExprError();
Fariborz Jahanian502d2ee2011-10-17 21:00:22 +00001035
Douglas Gregor5476205b2011-06-23 00:49:38 +00001036 // Construct an unresolved result if we in fact got an unresolved
1037 // result.
1038 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1039 // Suppress any lookup-related diagnostics; we'll do these when we
1040 // pick a member.
1041 R.suppressDiagnostics();
1042
1043 UnresolvedMemberExpr *MemExpr
1044 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1045 BaseExpr, BaseExprType,
1046 IsArrow, OpLoc,
1047 SS.getWithLocInContext(Context),
Abramo Bagnara7945c982012-01-27 09:46:47 +00001048 TemplateKWLoc, MemberNameInfo,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001049 TemplateArgs, R.begin(), R.end());
1050
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001051 return MemExpr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001052 }
1053
1054 assert(R.isSingleResult());
1055 DeclAccessPair FoundDecl = R.begin().getPair();
1056 NamedDecl *MemberDecl = R.getFoundDecl();
1057
1058 // FIXME: diagnose the presence of template arguments now.
1059
1060 // If the decl being referenced had an error, return an error for this
1061 // sub-expr without emitting another error, in order to avoid cascading
1062 // error cases.
1063 if (MemberDecl->isInvalidDecl())
1064 return ExprError();
1065
1066 // Handle the implicit-member-access case.
1067 if (!BaseExpr) {
1068 // If this is not an instance member, convert to a non-member access.
1069 if (!MemberDecl->isCXXInstanceMember())
1070 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1071
1072 SourceLocation Loc = R.getNameLoc();
1073 if (SS.getRange().isValid())
1074 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001075 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001076 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1077 }
1078
1079 bool ShouldCheckUse = true;
1080 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1081 // Don't diagnose the use of a virtual member function unless it's
1082 // explicitly qualified.
1083 if (MD->isVirtual() && !SS.isSet())
1084 ShouldCheckUse = false;
1085 }
1086
1087 // Check the use of this member.
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001088 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001089 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001090
Douglas Gregor5476205b2011-06-23 00:49:38 +00001091 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1092 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
1093 SS, FD, FoundDecl, MemberNameInfo);
1094
John McCall5e77d762013-04-16 07:28:30 +00001095 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1096 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1097 MemberNameInfo);
1098
Douglas Gregor5476205b2011-06-23 00:49:38 +00001099 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1100 // We may have found a field within an anonymous union or struct
1101 // (C++ [class.union]).
1102 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
Eli Friedmancccd0642013-07-16 00:01:31 +00001103 FoundDecl, BaseExpr,
1104 OpLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001105
1106 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001107 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1108 Var, FoundDecl, MemberNameInfo,
1109 Var->getType().getNonReferenceType(), VK_LValue,
1110 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001111 }
1112
1113 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1114 ExprValueKind valueKind;
1115 QualType type;
1116 if (MemberFn->isInstance()) {
1117 valueKind = VK_RValue;
1118 type = Context.BoundMemberTy;
1119 } else {
1120 valueKind = VK_LValue;
1121 type = MemberFn->getType();
1122 }
1123
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001124 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1125 MemberFn, FoundDecl, MemberNameInfo, type, valueKind,
1126 OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001127 }
1128 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1129
1130 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001131 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS, TemplateKWLoc,
1132 Enum, FoundDecl, MemberNameInfo, Enum->getType(),
1133 VK_RValue, OK_Ordinary);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001134 }
1135
Douglas Gregor5476205b2011-06-23 00:49:38 +00001136 // We found something that we didn't expect. Complain.
1137 if (isa<TypeDecl>(MemberDecl))
1138 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1139 << MemberName << BaseType << int(IsArrow);
1140 else
1141 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1142 << MemberName << BaseType << int(IsArrow);
1143
1144 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1145 << MemberName;
1146 R.suppressDiagnostics();
1147 return ExprError();
1148}
1149
1150/// Given that normal member access failed on the given expression,
1151/// and given that the expression's type involves builtin-id or
1152/// builtin-Class, decide whether substituting in the redefinition
1153/// types would be profitable. The redefinition type is whatever
1154/// this translation unit tried to typedef to id/Class; we store
1155/// it to the side and then re-use it in places like this.
1156static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1157 const ObjCObjectPointerType *opty
1158 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1159 if (!opty) return false;
1160
1161 const ObjCObjectType *ty = opty->getObjectType();
1162
1163 QualType redef;
1164 if (ty->isObjCId()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001165 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001166 } else if (ty->isObjCClass()) {
Douglas Gregor97673472011-08-11 20:58:55 +00001167 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001168 } else {
1169 return false;
1170 }
1171
1172 // Do the substitution as long as the redefinition type isn't just a
1173 // possibly-qualified pointer to builtin-id or builtin-Class again.
1174 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieuf20d9052012-10-12 17:48:40 +00001175 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001176 return false;
1177
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001178 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001179 return true;
1180}
1181
John McCall50a2c2c2011-10-11 23:14:30 +00001182static bool isRecordType(QualType T) {
1183 return T->isRecordType();
1184}
1185static bool isPointerToRecordType(QualType T) {
1186 if (const PointerType *PT = T->getAs<PointerType>())
1187 return PT->getPointeeType()->isRecordType();
1188 return false;
1189}
1190
Richard Smithcab9a7d2011-10-26 19:06:56 +00001191/// Perform conversions on the LHS of a member access expression.
1192ExprResult
1193Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman9a766c42012-01-13 02:20:01 +00001194 if (IsArrow && !Base->getType()->isFunctionType())
1195 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001196
Eli Friedman9a766c42012-01-13 02:20:01 +00001197 return CheckPlaceholderExpr(Base);
Richard Smithcab9a7d2011-10-26 19:06:56 +00001198}
1199
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001200namespace {
1201
1202class MemberExprTypoRecovery {
1203 Expr *BaseExpr;
1204 CXXScopeSpec SS;
1205 SourceLocation OpLoc;
1206 bool IsArrow;
1207
1208public:
1209 MemberExprTypoRecovery(Expr *BE, CXXScopeSpec &SS, SourceLocation OpLoc,
1210 bool IsArrow)
1211 : BaseExpr(BE), SS(SS),
1212 OpLoc(OpLoc), IsArrow(IsArrow) {}
1213
1214 ExprResult operator()(Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) {
1215 if (TC.isKeyword())
1216 return ExprError();
1217
1218 LookupResult R(SemaRef, TC.getCorrection(),
1219 TC.getCorrectionRange().getBegin(),
1220 SemaRef.getTypoExprState(TE)
1221 .Consumer->getLookupResult()
1222 .getLookupKind());
1223 R.suppressDiagnostics();
1224
1225 QualType BaseType;
1226 if (auto *DRE = dyn_cast<DeclRefExpr>(BaseExpr))
1227 BaseType = DRE->getDecl()->getType();
1228 else if (auto *CE = dyn_cast<CallExpr>(BaseExpr))
1229 BaseType = CE->getCallReturnType();
1230
1231 for (NamedDecl *ND : TC)
1232 R.addDecl(ND);
1233 R.resolveKind();
1234 return SemaRef.BuildMemberReferenceExpr(
1235 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
1236 nullptr, R, nullptr);
1237 }
1238};
1239
1240}
1241
Douglas Gregor5476205b2011-06-23 00:49:38 +00001242/// Look up the given member of the given non-type-dependent
1243/// expression. This can return in one of two ways:
1244/// * If it returns a sentinel null-but-valid result, the caller will
1245/// assume that lookup was performed and the results written into
1246/// the provided structure. It will take over from there.
1247/// * Otherwise, the returned expression will be produced in place of
1248/// an ordinary member expression.
1249///
1250/// The ObjCImpDecl bit is a gross hack that will need to be properly
1251/// fixed for ObjC++.
Richard Smitha0edd302014-05-31 00:18:32 +00001252static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1253 ExprResult &BaseExpr, bool &IsArrow,
1254 SourceLocation OpLoc, CXXScopeSpec &SS,
1255 Decl *ObjCImpDecl, bool HasTemplateArgs) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001256 assert(BaseExpr.get() && "no base expression");
1257
1258 // Perform default conversions.
Richard Smitha0edd302014-05-31 00:18:32 +00001259 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
John McCall50a2c2c2011-10-11 23:14:30 +00001260 if (BaseExpr.isInvalid())
1261 return ExprError();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001262
Douglas Gregor5476205b2011-06-23 00:49:38 +00001263 QualType BaseType = BaseExpr.get()->getType();
1264 assert(!BaseType->isDependentType());
1265
1266 DeclarationName MemberName = R.getLookupName();
1267 SourceLocation MemberLoc = R.getNameLoc();
1268
1269 // For later type-checking purposes, turn arrow accesses into dot
1270 // accesses. The only access type we support that doesn't follow
1271 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1272 // and those never use arrows, so this is unaffected.
1273 if (IsArrow) {
1274 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1275 BaseType = Ptr->getPointeeType();
1276 else if (const ObjCObjectPointerType *Ptr
1277 = BaseType->getAs<ObjCObjectPointerType>())
1278 BaseType = Ptr->getPointeeType();
1279 else if (BaseType->isRecordType()) {
1280 // Recover from arrow accesses to records, e.g.:
1281 // struct MyRecord foo;
1282 // foo->bar
1283 // This is actually well-formed in C++ if MyRecord has an
1284 // overloaded operator->, but that should have been dealt with
Kaelyn Uhrain0c51de42013-07-31 17:38:24 +00001285 // by now--or a diagnostic message already issued if a problem
1286 // was encountered while looking for the overloaded operator->.
Richard Smitha0edd302014-05-31 00:18:32 +00001287 if (!S.getLangOpts().CPlusPlus) {
1288 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
Kaelyn Uhrainbd6ddaa2013-10-31 20:32:56 +00001289 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1290 << FixItHint::CreateReplacement(OpLoc, ".");
1291 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001292 IsArrow = false;
Eli Friedman9a766c42012-01-13 02:20:01 +00001293 } else if (BaseType->isFunctionType()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001294 goto fail;
1295 } else {
Richard Smitha0edd302014-05-31 00:18:32 +00001296 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001297 << BaseType << BaseExpr.get()->getSourceRange();
1298 return ExprError();
1299 }
1300 }
1301
1302 // Handle field access to simple records.
1303 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001304 TypoExpr *TE = nullptr;
1305 if (LookupMemberExprInRecord(
1306 S, R, BaseExpr.get()->getSourceRange(), RTy, OpLoc, SS,
1307 HasTemplateArgs, &TE,
1308 MemberExprTypoRecovery(BaseExpr.get(), SS, OpLoc, IsArrow)))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001309 return ExprError();
1310
1311 // Returning valid-but-null is how we indicate to the caller that
Kaelyn Takatafe408a72014-10-27 18:07:46 +00001312 // the lookup result was filled in. If typo correction was attempted and
1313 // failed, the lookup result will have been cleared--that combined with the
1314 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1315 return ExprResult(TE);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001316 }
1317
1318 // Handle ivar access to Objective-C objects.
1319 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001320 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001321 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
Douglas Gregor12340e52011-10-09 23:22:49 +00001322 << 1 << SS.getScopeRep()
1323 << FixItHint::CreateRemoval(SS.getRange());
1324 SS.clear();
1325 }
Richard Smitha0edd302014-05-31 00:18:32 +00001326
Douglas Gregor5476205b2011-06-23 00:49:38 +00001327 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1328
1329 // There are three cases for the base type:
1330 // - builtin id (qualified or unqualified)
1331 // - builtin Class (qualified or unqualified)
1332 // - an interface
1333 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1334 if (!IDecl) {
Richard Smitha0edd302014-05-31 00:18:32 +00001335 if (S.getLangOpts().ObjCAutoRefCount &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001336 (OTy->isObjCId() || OTy->isObjCClass()))
1337 goto fail;
1338 // There's an implicit 'isa' ivar on all objects.
1339 // But we only actually find it this way on objects of type 'id',
Eric Christopherae6b9d22012-08-16 23:50:37 +00001340 // apparently.
Fariborz Jahanian84510742013-03-27 21:19:25 +00001341 if (OTy->isObjCId() && Member->isStr("isa"))
Richard Smitha0edd302014-05-31 00:18:32 +00001342 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1343 OpLoc, S.Context.getObjCClassType());
1344 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1345 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001346 ObjCImpDecl, HasTemplateArgs);
1347 goto fail;
1348 }
Richard Smitha0edd302014-05-31 00:18:32 +00001349
1350 if (S.RequireCompleteType(OpLoc, BaseType,
1351 diag::err_typecheck_incomplete_tag,
1352 BaseExpr.get()))
Douglas Gregor5dbf4eb2012-01-02 17:18:37 +00001353 return ExprError();
Craig Topperc3ec1492014-05-26 06:22:03 +00001354
1355 ObjCInterfaceDecl *ClassDeclared = nullptr;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001356 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1357
1358 if (!IV) {
1359 // Attempt to correct for typos in ivar names.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001360 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1361 Validator->IsObjCIvarLookup = IsArrow;
Richard Smitha0edd302014-05-31 00:18:32 +00001362 if (TypoCorrection Corrected = S.CorrectTypo(
1363 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001364 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
Kaelyn Uhrain3658e6a2012-01-13 21:28:55 +00001365 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Richard Smitha0edd302014-05-31 00:18:32 +00001366 S.diagnoseTypo(
1367 Corrected,
1368 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1369 << IDecl->getDeclName() << MemberName);
Richard Smithf9b15102013-08-17 00:46:16 +00001370
Ted Kremenek679b4782012-03-17 00:53:39 +00001371 // Figure out the class that declares the ivar.
1372 assert(!ClassDeclared);
1373 Decl *D = cast<Decl>(IV->getDeclContext());
1374 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1375 D = CAT->getClassInterface();
1376 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001377 } else {
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001378 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001379 S.Diag(MemberLoc, diag::err_property_found_suggest)
1380 << Member << BaseExpr.get()->getType()
1381 << FixItHint::CreateReplacement(OpLoc, ".");
Fariborz Jahanianc297cd82011-06-28 00:00:52 +00001382 return ExprError();
1383 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001384
Richard Smitha0edd302014-05-31 00:18:32 +00001385 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1386 << IDecl->getDeclName() << MemberName
1387 << BaseExpr.get()->getSourceRange();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001388 return ExprError();
1389 }
1390 }
Richard Smitha0edd302014-05-31 00:18:32 +00001391
Ted Kremenek679b4782012-03-17 00:53:39 +00001392 assert(ClassDeclared);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001393
1394 // If the decl being referenced had an error, return an error for this
1395 // sub-expr without emitting another error, in order to avoid cascading
1396 // error cases.
1397 if (IV->isInvalidDecl())
1398 return ExprError();
1399
1400 // Check whether we can reference this field.
Richard Smitha0edd302014-05-31 00:18:32 +00001401 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001402 return ExprError();
1403 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1404 IV->getAccessControl() != ObjCIvarDecl::Package) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001405 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
Richard Smitha0edd302014-05-31 00:18:32 +00001406 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001407 ClassOfMethodDecl = MD->getClassInterface();
Richard Smitha0edd302014-05-31 00:18:32 +00001408 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001409 // Case of a c-function declared inside an objc implementation.
1410 // FIXME: For a c-style function nested inside an objc implementation
1411 // class, there is no implementation context available, so we pass
1412 // down the context as argument to this routine. Ideally, this context
1413 // need be passed down in the AST node and somehow calculated from the
1414 // AST for a function decl.
1415 if (ObjCImplementationDecl *IMPD =
1416 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1417 ClassOfMethodDecl = IMPD->getClassInterface();
1418 else if (ObjCCategoryImplDecl* CatImplClass =
1419 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1420 ClassOfMethodDecl = CatImplClass->getClassInterface();
1421 }
Richard Smitha0edd302014-05-31 00:18:32 +00001422 if (!S.getLangOpts().DebuggerSupport) {
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001423 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1424 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1425 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Richard Smitha0edd302014-05-31 00:18:32 +00001426 S.Diag(MemberLoc, diag::error_private_ivar_access)
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001427 << IV->getDeclName();
1428 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1429 // @protected
Richard Smitha0edd302014-05-31 00:18:32 +00001430 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1431 << IV->getDeclName();
Fariborz Jahaniand6cb4a82012-03-07 00:58:41 +00001432 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001433 }
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001434 bool warn = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001435 if (S.getLangOpts().ObjCAutoRefCount) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001436 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1437 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1438 if (UO->getOpcode() == UO_Deref)
1439 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1440
1441 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001442 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Richard Smitha0edd302014-05-31 00:18:32 +00001443 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanian285a7cc2012-08-07 23:48:10 +00001444 warn = false;
1445 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001446 }
Fariborz Jahaniana5063a62012-08-08 16:41:04 +00001447 if (warn) {
Richard Smitha0edd302014-05-31 00:18:32 +00001448 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001449 ObjCMethodFamily MF = MD->getMethodFamily();
1450 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahaniana934a022013-02-14 19:07:19 +00001451 MF != OMF_finalize &&
Richard Smitha0edd302014-05-31 00:18:32 +00001452 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001453 }
1454 if (warn)
Richard Smitha0edd302014-05-31 00:18:32 +00001455 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
Fariborz Jahaniana7c9f882012-08-07 16:38:44 +00001456 }
Jordan Rose657b5f42012-09-28 22:21:35 +00001457
Richard Smitha0edd302014-05-31 00:18:32 +00001458 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1459 IV, IV->getType(), MemberLoc, OpLoc, BaseExpr.get(), IsArrow);
Jordan Rose657b5f42012-09-28 22:21:35 +00001460
Richard Smitha0edd302014-05-31 00:18:32 +00001461 if (S.getLangOpts().ObjCAutoRefCount) {
Jordan Rose657b5f42012-09-28 22:21:35 +00001462 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00001463 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
Richard Smitha0edd302014-05-31 00:18:32 +00001464 S.recordUseOfEvaluatedWeak(Result);
Jordan Rose657b5f42012-09-28 22:21:35 +00001465 }
1466 }
1467
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001468 return Result;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001469 }
1470
1471 // Objective-C property access.
1472 const ObjCObjectPointerType *OPT;
1473 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregorbcc95392011-10-10 16:09:49 +00001474 if (!SS.isEmpty() && !SS.isInvalid()) {
Richard Smitha0edd302014-05-31 00:18:32 +00001475 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1476 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
Douglas Gregor12340e52011-10-09 23:22:49 +00001477 SS.clear();
1478 }
1479
Douglas Gregor5476205b2011-06-23 00:49:38 +00001480 // This actually uses the base as an r-value.
Richard Smitha0edd302014-05-31 00:18:32 +00001481 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001482 if (BaseExpr.isInvalid())
1483 return ExprError();
1484
Richard Smitha0edd302014-05-31 00:18:32 +00001485 assert(S.Context.hasSameUnqualifiedType(BaseType,
1486 BaseExpr.get()->getType()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001487
1488 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1489
1490 const ObjCObjectType *OT = OPT->getObjectType();
1491
1492 // id, with and without qualifiers.
1493 if (OT->isObjCId()) {
1494 // Check protocols on qualified interfaces.
Richard Smitha0edd302014-05-31 00:18:32 +00001495 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1496 if (Decl *PMDecl =
1497 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
Douglas Gregor5476205b2011-06-23 00:49:38 +00001498 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1499 // Check the use of this declaration
Richard Smitha0edd302014-05-31 00:18:32 +00001500 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001501 return ExprError();
1502
Richard Smitha0edd302014-05-31 00:18:32 +00001503 return new (S.Context)
1504 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001505 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001506 }
1507
1508 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1509 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001510 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001511 return ExprError();
1512 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001513 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1514 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001515 Member);
Craig Topperc3ec1492014-05-26 06:22:03 +00001516 ObjCMethodDecl *SMD = nullptr;
1517 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
Richard Smitha0edd302014-05-31 00:18:32 +00001518 /*Property id*/ nullptr,
1519 SetterSel, S.Context))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001520 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Richard Smitha0edd302014-05-31 00:18:32 +00001521
1522 return new (S.Context)
1523 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001524 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001525 }
1526 }
1527 // Use of id.member can only be for a property reference. Do not
1528 // use the 'id' redefinition in this case.
Richard Smitha0edd302014-05-31 00:18:32 +00001529 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1530 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001531 ObjCImpDecl, HasTemplateArgs);
1532
Richard Smitha0edd302014-05-31 00:18:32 +00001533 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001534 << MemberName << BaseType);
1535 }
1536
1537 // 'Class', unqualified only.
1538 if (OT->isObjCClass()) {
1539 // Only works in a method declaration (??!).
Richard Smitha0edd302014-05-31 00:18:32 +00001540 ObjCMethodDecl *MD = S.getCurMethodDecl();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001541 if (!MD) {
Richard Smitha0edd302014-05-31 00:18:32 +00001542 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1543 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001544 ObjCImpDecl, HasTemplateArgs);
1545
1546 goto fail;
1547 }
1548
1549 // Also must look for a getter name which uses property syntax.
Richard Smitha0edd302014-05-31 00:18:32 +00001550 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001551 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1552 ObjCMethodDecl *Getter;
1553 if ((Getter = IFace->lookupClassMethod(Sel))) {
1554 // Check the use of this method.
Richard Smitha0edd302014-05-31 00:18:32 +00001555 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001556 return ExprError();
1557 } else
1558 Getter = IFace->lookupPrivateMethod(Sel, false);
1559 // If we found a getter then this may be a valid dot-reference, we
1560 // will look for the matching setter, in case it is needed.
1561 Selector SetterSel =
Richard Smitha0edd302014-05-31 00:18:32 +00001562 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1563 S.PP.getSelectorTable(),
Adrian Prantla4ce9062013-06-07 22:29:12 +00001564 Member);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001565 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1566 if (!Setter) {
1567 // If this reference is in an @implementation, also check for 'private'
1568 // methods.
1569 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1570 }
Douglas Gregor5476205b2011-06-23 00:49:38 +00001571
Richard Smitha0edd302014-05-31 00:18:32 +00001572 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
Douglas Gregor5476205b2011-06-23 00:49:38 +00001573 return ExprError();
1574
1575 if (Getter || Setter) {
Richard Smitha0edd302014-05-31 00:18:32 +00001576 return new (S.Context) ObjCPropertyRefExpr(
1577 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1578 OK_ObjCProperty, MemberLoc, BaseExpr.get());
Douglas Gregor5476205b2011-06-23 00:49:38 +00001579 }
1580
Richard Smitha0edd302014-05-31 00:18:32 +00001581 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1582 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001583 ObjCImpDecl, HasTemplateArgs);
1584
Richard Smitha0edd302014-05-31 00:18:32 +00001585 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
Douglas Gregor5476205b2011-06-23 00:49:38 +00001586 << MemberName << BaseType);
1587 }
1588
1589 // Normal property access.
Richard Smitha0edd302014-05-31 00:18:32 +00001590 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1591 MemberLoc, SourceLocation(), QualType(),
1592 false);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001593 }
1594
1595 // Handle 'field access' to vectors, such as 'V.xx'.
1596 if (BaseType->isExtVectorType()) {
1597 // FIXME: this expr should store IsArrow.
1598 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1599 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
Richard Smitha0edd302014-05-31 00:18:32 +00001600 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001601 Member, MemberLoc);
1602 if (ret.isNull())
1603 return ExprError();
1604
Richard Smitha0edd302014-05-31 00:18:32 +00001605 return new (S.Context)
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001606 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001607 }
1608
1609 // Adjust builtin-sel to the appropriate redefinition type if that's
1610 // not just a pointer to builtin-sel again.
Richard Smitha0edd302014-05-31 00:18:32 +00001611 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1612 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1613 BaseExpr = S.ImpCastExprToType(
1614 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1615 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001616 ObjCImpDecl, HasTemplateArgs);
1617 }
1618
1619 // Failure cases.
1620 fail:
1621
1622 // Recover from dot accesses to pointers, e.g.:
1623 // type *foo;
1624 // foo.bar
1625 // This is actually well-formed in two cases:
1626 // - 'type' is an Objective C type
1627 // - 'bar' is a pseudo-destructor name which happens to refer to
1628 // the appropriate pointer type
1629 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1630 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1631 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
Richard Smitha0edd302014-05-31 00:18:32 +00001632 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1633 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
Douglas Gregor5476205b2011-06-23 00:49:38 +00001634 << FixItHint::CreateReplacement(OpLoc, "->");
1635
1636 // Recurse as an -> access.
1637 IsArrow = true;
Richard Smitha0edd302014-05-31 00:18:32 +00001638 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001639 ObjCImpDecl, HasTemplateArgs);
1640 }
1641 }
1642
1643 // If the user is trying to apply -> or . to a function name, it's probably
1644 // because they forgot parentheses to call that function.
Richard Smitha0edd302014-05-31 00:18:32 +00001645 if (S.tryToRecoverWithCall(
1646 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1647 /*complain*/ false,
1648 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall50a2c2c2011-10-11 23:14:30 +00001649 if (BaseExpr.isInvalid())
Douglas Gregor5476205b2011-06-23 00:49:38 +00001650 return ExprError();
Richard Smitha0edd302014-05-31 00:18:32 +00001651 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1652 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
John McCall50a2c2c2011-10-11 23:14:30 +00001653 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001654 }
1655
Richard Smitha0edd302014-05-31 00:18:32 +00001656 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay025321b2012-04-21 02:13:04 +00001657 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor5476205b2011-06-23 00:49:38 +00001658
1659 return ExprError();
1660}
1661
1662/// The main callback when the parser finds something like
1663/// expression . [nested-name-specifier] identifier
1664/// expression -> [nested-name-specifier] identifier
1665/// where 'identifier' encompasses a fairly broad spectrum of
1666/// possibilities, including destructor and operator references.
1667///
1668/// \param OpKind either tok::arrow or tok::period
1669/// \param HasTrailingLParen whether the next token is '(', which
1670/// is used to diagnose mis-uses of special members that can
1671/// only be called
James Dennett2a4d13c2012-06-15 07:13:21 +00001672/// \param ObjCImpDecl the current Objective-C \@implementation
1673/// decl; this is an ugly hack around the fact that Objective-C
1674/// \@implementations aren't properly put in the context chain
Douglas Gregor5476205b2011-06-23 00:49:38 +00001675ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1676 SourceLocation OpLoc,
1677 tok::TokenKind OpKind,
1678 CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001679 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001680 UnqualifiedId &Id,
1681 Decl *ObjCImpDecl,
1682 bool HasTrailingLParen) {
1683 if (SS.isSet() && SS.isInvalid())
1684 return ExprError();
1685
Richard Smitha0edd302014-05-31 00:18:32 +00001686 // The only way a reference to a destructor can be used is to
1687 // immediately call it. If the next token is not a '(', produce
1688 // a diagnostic and build the call now.
1689 if (!HasTrailingLParen &&
1690 Id.getKind() == UnqualifiedId::IK_DestructorName) {
1691 ExprResult DtorAccess =
1692 ActOnMemberAccessExpr(S, Base, OpLoc, OpKind, SS, TemplateKWLoc, Id,
1693 ObjCImpDecl, /*HasTrailingLParen*/true);
1694 if (DtorAccess.isInvalid())
1695 return DtorAccess;
1696 return DiagnoseDtorReference(Id.getLocStart(), DtorAccess.get());
1697 }
1698
Douglas Gregor5476205b2011-06-23 00:49:38 +00001699 // Warn about the explicit constructor calls Microsoft extension.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001700 if (getLangOpts().MicrosoftExt &&
Douglas Gregor5476205b2011-06-23 00:49:38 +00001701 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1702 Diag(Id.getSourceRange().getBegin(),
1703 diag::ext_ms_explicit_constructor_call);
1704
1705 TemplateArgumentListInfo TemplateArgsBuffer;
1706
1707 // Decompose the name into its component parts.
1708 DeclarationNameInfo NameInfo;
1709 const TemplateArgumentListInfo *TemplateArgs;
1710 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1711 NameInfo, TemplateArgs);
1712
1713 DeclarationName Name = NameInfo.getName();
1714 bool IsArrow = (OpKind == tok::arrow);
1715
1716 NamedDecl *FirstQualifierInScope
Craig Topperc3ec1492014-05-26 06:22:03 +00001717 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
Douglas Gregor5476205b2011-06-23 00:49:38 +00001718
1719 // This is a postfix expression, so get rid of ParenListExprs.
1720 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1721 if (Result.isInvalid()) return ExprError();
Nikola Smiljanic01a75982014-05-29 10:55:11 +00001722 Base = Result.get();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001723
1724 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1725 isDependentScopeSpecifier(SS)) {
Richard Smitha0edd302014-05-31 00:18:32 +00001726 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1727 TemplateKWLoc, FirstQualifierInScope,
1728 NameInfo, TemplateArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001729 }
1730
Richard Smitha0edd302014-05-31 00:18:32 +00001731 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl,
1732 HasTrailingLParen};
1733 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1734 TemplateKWLoc, FirstQualifierInScope,
1735 NameInfo, TemplateArgs, &ExtraArgs);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001736}
1737
1738static ExprResult
1739BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1740 const CXXScopeSpec &SS, FieldDecl *Field,
1741 DeclAccessPair FoundDecl,
1742 const DeclarationNameInfo &MemberNameInfo) {
1743 // x.a is an l-value if 'a' has a reference type. Otherwise:
1744 // x.a is an l-value/x-value/pr-value if the base is (and note
1745 // that *x is always an l-value), except that if the base isn't
1746 // an ordinary object then we must have an rvalue.
1747 ExprValueKind VK = VK_LValue;
1748 ExprObjectKind OK = OK_Ordinary;
1749 if (!IsArrow) {
1750 if (BaseExpr->getObjectKind() == OK_Ordinary)
1751 VK = BaseExpr->getValueKind();
1752 else
1753 VK = VK_RValue;
1754 }
1755 if (VK != VK_RValue && Field->isBitField())
1756 OK = OK_BitField;
1757
1758 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1759 QualType MemberType = Field->getType();
1760 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1761 MemberType = Ref->getPointeeType();
1762 VK = VK_LValue;
1763 } else {
1764 QualType BaseType = BaseExpr->getType();
1765 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault376f7202013-02-26 21:16:00 +00001766
Douglas Gregor5476205b2011-06-23 00:49:38 +00001767 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001768
Douglas Gregor5476205b2011-06-23 00:49:38 +00001769 // GC attributes are never picked up by members.
1770 BaseQuals.removeObjCGCAttr();
Matt Arsenault376f7202013-02-26 21:16:00 +00001771
Douglas Gregor5476205b2011-06-23 00:49:38 +00001772 // CVR attributes from the base are picked up by members,
1773 // except that 'mutable' members don't pick up 'const'.
1774 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault376f7202013-02-26 21:16:00 +00001775
Douglas Gregor5476205b2011-06-23 00:49:38 +00001776 Qualifiers MemberQuals
1777 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault376f7202013-02-26 21:16:00 +00001778
Douglas Gregor5476205b2011-06-23 00:49:38 +00001779 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault376f7202013-02-26 21:16:00 +00001780
1781
Douglas Gregor5476205b2011-06-23 00:49:38 +00001782 Qualifiers Combined = BaseQuals + MemberQuals;
1783 if (Combined != MemberQuals)
1784 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1785 }
Matt Arsenault376f7202013-02-26 21:16:00 +00001786
Daniel Jasper0baec5492012-06-06 08:32:04 +00001787 S.UnusedPrivateFields.remove(Field);
1788
Douglas Gregor5476205b2011-06-23 00:49:38 +00001789 ExprResult Base =
1790 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1791 FoundDecl, Field);
1792 if (Base.isInvalid())
1793 return ExprError();
Nikola Smiljanic03ff2592014-05-29 14:05:12 +00001794 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, SS,
1795 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1796 MemberNameInfo, MemberType, VK, OK);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001797}
1798
1799/// Builds an implicit member access expression. The current context
1800/// is known to be an instance method, and the given unqualified lookup
1801/// set is known to contain only instance members, at least one of which
1802/// is from an appropriate type.
1803ExprResult
1804Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001805 SourceLocation TemplateKWLoc,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001806 LookupResult &R,
1807 const TemplateArgumentListInfo *TemplateArgs,
1808 bool IsKnownInstance) {
1809 assert(!R.empty() && !R.isAmbiguous());
1810
1811 SourceLocation loc = R.getNameLoc();
Richard Smith59d26d22014-01-17 22:29:43 +00001812
Douglas Gregor5476205b2011-06-23 00:49:38 +00001813 // If this is known to be an instance access, go ahead and build an
1814 // implicit 'this' expression now.
1815 // 'this' expression now.
Douglas Gregor09deffa2011-10-18 16:47:30 +00001816 QualType ThisTy = getCurrentThisType();
Douglas Gregor5476205b2011-06-23 00:49:38 +00001817 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
Craig Topperc3ec1492014-05-26 06:22:03 +00001818
1819 Expr *baseExpr = nullptr; // null signifies implicit access
Douglas Gregor5476205b2011-06-23 00:49:38 +00001820 if (IsKnownInstance) {
1821 SourceLocation Loc = R.getNameLoc();
1822 if (SS.getRange().isValid())
1823 Loc = SS.getRange().getBegin();
Eli Friedman73a04092012-01-07 04:59:52 +00001824 CheckCXXThisCapture(Loc);
Douglas Gregor5476205b2011-06-23 00:49:38 +00001825 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1826 }
Craig Topperc3ec1492014-05-26 06:22:03 +00001827
Douglas Gregor5476205b2011-06-23 00:49:38 +00001828 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1829 /*OpLoc*/ SourceLocation(),
1830 /*IsArrow*/ true,
Abramo Bagnara7945c982012-01-27 09:46:47 +00001831 SS, TemplateKWLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001832 /*FirstQualifierInScope*/ nullptr,
Douglas Gregor5476205b2011-06-23 00:49:38 +00001833 R, TemplateArgs);
1834}