blob: e41a2e9145e04c9d341f8106203070ea810e8a5e [file] [log] [blame]
Douglas Gregor2b1ad8b2011-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//===----------------------------------------------------------------------===//
13#include "clang/Sema/SemaInternal.h"
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000014#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclObjC.h"
16#include "clang/AST/DeclTemplate.h"
17#include "clang/AST/ExprCXX.h"
18#include "clang/AST/ExprObjC.h"
19#include "clang/Lex/Preprocessor.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000020#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000023
24using namespace clang;
25using namespace sema;
26
Richard Smithf62c6902012-11-22 00:24:47 +000027typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
28static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
29 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
30 return !Bases.count(Base->getCanonicalDecl());
31}
32
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000033/// Determines if the given class is provably not derived from all of
34/// the prospective base classes.
Richard Smithf62c6902012-11-22 00:24:47 +000035static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
36 const BaseSet &Bases) {
37 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
38 return BaseIsNotInSet(Record, BasesPtr) &&
39 Record->forallBases(BaseIsNotInSet, BasesPtr);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000040}
41
42enum IMAKind {
43 /// The reference is definitely not an instance member access.
44 IMA_Static,
45
46 /// The reference may be an implicit instance member access.
47 IMA_Mixed,
48
Eli Friedman9bc291d2012-01-18 03:53:45 +000049 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000050 /// so, because the context is not an instance method.
51 IMA_Mixed_StaticContext,
52
53 /// The reference may be to an instance member, but it is invalid if
54 /// so, because the context is from an unrelated class.
55 IMA_Mixed_Unrelated,
56
57 /// The reference is definitely an implicit instance member access.
58 IMA_Instance,
59
60 /// The reference may be to an unresolved using declaration.
61 IMA_Unresolved,
62
63 /// The reference may be to an unresolved using declaration and the
64 /// context is not an instance method.
65 IMA_Unresolved_StaticContext,
66
Eli Friedmanef331b72012-01-20 01:26:23 +000067 // The reference refers to a field which is not a member of the containing
68 // class, which is allowed because we're in C++11 mode and the context is
69 // unevaluated.
70 IMA_Field_Uneval_Context,
Eli Friedman9bc291d2012-01-18 03:53:45 +000071
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000072 /// All possible referrents are instance members and the current
73 /// context is not an instance method.
74 IMA_Error_StaticContext,
75
76 /// All possible referrents are instance members of an unrelated
77 /// class.
78 IMA_Error_Unrelated
79};
80
81/// The given lookup names class member(s) and is not being used for
82/// an address-of-member expression. Classify the type of access
83/// according to whether it's possible that this reference names an
Eli Friedman9bc291d2012-01-18 03:53:45 +000084/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000085/// conservatively answer "yes", in which case some errors will simply
86/// not be caught until template-instantiation.
87static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
88 Scope *CurScope,
89 const LookupResult &R) {
90 assert(!R.empty() && (*R.begin())->isCXXClassMember());
91
92 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
93
Douglas Gregorcefc3af2012-04-16 07:05:22 +000094 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
95 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000096
97 if (R.isUnresolvableResult())
98 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
99
100 // Collect all the declaring classes of instance members we find.
101 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000102 bool isField = false;
Richard Smithf62c6902012-11-22 00:24:47 +0000103 BaseSet Classes;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000104 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
105 NamedDecl *D = *I;
106
107 if (D->isCXXInstanceMember()) {
Aaron Ballman1dfc4ba2012-06-01 00:02:08 +0000108 if (dyn_cast<FieldDecl>(D) || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000109 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000110
111 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
112 Classes.insert(R->getCanonicalDecl());
113 }
114 else
115 hasNonInstance = true;
116 }
117
118 // If we didn't find any instance members, it can't be an implicit
119 // member reference.
120 if (Classes.empty())
121 return IMA_Static;
122
Richard Smithd390de92012-02-25 10:20:59 +0000123 bool IsCXX11UnevaluatedField = false;
Richard Smith80ad52f2013-01-02 11:42:31 +0000124 if (SemaRef.getLangOpts().CPlusPlus11 && isField) {
Richard Smith2c8aee42012-02-25 10:04:07 +0000125 // C++11 [expr.prim.general]p12:
126 // An id-expression that denotes a non-static data member or non-static
127 // member function of a class can only be used:
128 // (...)
129 // - if that id-expression denotes a non-static data member and it
130 // appears in an unevaluated operand.
131 const Sema::ExpressionEvaluationContextRecord& record
132 = SemaRef.ExprEvalContexts.back();
133 if (record.Context == Sema::Unevaluated)
Richard Smithd390de92012-02-25 10:20:59 +0000134 IsCXX11UnevaluatedField = true;
Richard Smith2c8aee42012-02-25 10:04:07 +0000135 }
136
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000137 // If the current context is not an instance method, it can't be
138 // an implicit member reference.
139 if (isStaticContext) {
140 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000141 return IMA_Mixed_StaticContext;
142
Richard Smithd390de92012-02-25 10:20:59 +0000143 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
144 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000145 }
146
147 CXXRecordDecl *contextClass;
148 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
149 contextClass = MD->getParent()->getCanonicalDecl();
150 else
151 contextClass = cast<CXXRecordDecl>(DC);
152
153 // [class.mfct.non-static]p3:
154 // ...is used in the body of a non-static member function of class X,
155 // if name lookup (3.4.1) resolves the name in the id-expression to a
156 // non-static non-type member of some class C [...]
157 // ...if C is not X or a base class of X, the class member access expression
158 // is ill-formed.
159 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000160 contextClass->getCanonicalDecl() !=
Richard Smithf62c6902012-11-22 00:24:47 +0000161 R.getNamingClass()->getCanonicalDecl()) {
162 // If the naming class is not the current context, this was a qualified
163 // member name lookup, and it's sufficient to check that we have the naming
164 // class as a base class.
165 Classes.clear();
Richard Smith746619a2012-11-22 00:40:54 +0000166 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithf62c6902012-11-22 00:24:47 +0000167 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000168
169 // If we can prove that the current context is unrelated to all the
170 // declaring classes, it can't be an implicit member reference (in
171 // which case it's an error if any of those members are selected).
Richard Smithf62c6902012-11-22 00:24:47 +0000172 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smithd390de92012-02-25 10:20:59 +0000173 return hasNonInstance ? IMA_Mixed_Unrelated :
174 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
175 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000176
177 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
178}
179
180/// Diagnose a reference to a field with no object available.
Richard Smitha85cf392012-04-05 01:13:04 +0000181static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000182 const CXXScopeSpec &SS,
Richard Smitha85cf392012-04-05 01:13:04 +0000183 NamedDecl *Rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000184 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000185 SourceLocation Loc = nameInfo.getLoc();
186 SourceRange Range(Loc);
187 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman9bc291d2012-01-18 03:53:45 +0000188
Richard Smitha85cf392012-04-05 01:13:04 +0000189 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
190 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
191 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
192 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
193
194 bool InStaticMethod = Method && Method->isStatic();
195 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
196
197 if (IsField && InStaticMethod)
198 // "invalid use of member 'x' in static member function"
199 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
200 << Range << nameInfo.getName();
201 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
202 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
203 // Unqualified lookup in a non-static member function found a member of an
204 // enclosing class.
205 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
206 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
207 else if (IsField)
Eli Friedmanef331b72012-01-20 01:26:23 +0000208 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smitha85cf392012-04-05 01:13:04 +0000209 << nameInfo.getName() << Range;
210 else
211 SemaRef.Diag(Loc, diag::err_member_call_without_object)
212 << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000213}
214
215/// Builds an expression which might be an implicit member expression.
216ExprResult
217Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000218 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000219 LookupResult &R,
220 const TemplateArgumentListInfo *TemplateArgs) {
221 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
222 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000223 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000224
225 case IMA_Mixed:
226 case IMA_Mixed_Unrelated:
227 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000228 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000229
Richard Smithd390de92012-02-25 10:20:59 +0000230 case IMA_Field_Uneval_Context:
231 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
232 << R.getLookupNameInfo().getName();
233 // Fall through.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000234 case IMA_Static:
235 case IMA_Mixed_StaticContext:
236 case IMA_Unresolved_StaticContext:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000237 if (TemplateArgs || TemplateKWLoc.isValid())
238 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000239 return BuildDeclarationNameExpr(SS, R, false);
240
241 case IMA_Error_StaticContext:
242 case IMA_Error_Unrelated:
Richard Smitha85cf392012-04-05 01:13:04 +0000243 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000244 R.getLookupNameInfo());
245 return ExprError();
246 }
247
248 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000249}
250
251/// Check an ext-vector component access expression.
252///
253/// VK should be set in advance to the value kind of the base
254/// expression.
255static QualType
256CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
257 SourceLocation OpLoc, const IdentifierInfo *CompName,
258 SourceLocation CompLoc) {
259 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
260 // see FIXME there.
261 //
262 // FIXME: This logic can be greatly simplified by splitting it along
263 // halving/not halving and reworking the component checking.
264 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
265
266 // The vector accessor can't exceed the number of elements.
267 const char *compStr = CompName->getNameStart();
268
269 // This flag determines whether or not the component is one of the four
270 // special names that indicate a subset of exactly half the elements are
271 // to be selected.
272 bool HalvingSwizzle = false;
273
274 // This flag determines whether or not CompName has an 's' char prefix,
275 // indicating that it is a string of hex values to be used as vector indices.
276 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
277
278 bool HasRepeated = false;
279 bool HasIndex[16] = {};
280
281 int Idx;
282
283 // Check that we've found one of the special components, or that the component
284 // names must come from the same set.
285 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
286 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
287 HalvingSwizzle = true;
288 } else if (!HexSwizzle &&
289 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
290 do {
291 if (HasIndex[Idx]) HasRepeated = true;
292 HasIndex[Idx] = true;
293 compStr++;
294 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
295 } else {
296 if (HexSwizzle) compStr++;
297 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
298 if (HasIndex[Idx]) HasRepeated = true;
299 HasIndex[Idx] = true;
300 compStr++;
301 }
302 }
303
304 if (!HalvingSwizzle && *compStr) {
305 // We didn't get to the end of the string. This means the component names
306 // didn't come from the same set *or* we encountered an illegal name.
307 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000308 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000309 return QualType();
310 }
311
312 // Ensure no component accessor exceeds the width of the vector type it
313 // operates on.
314 if (!HalvingSwizzle) {
315 compStr = CompName->getNameStart();
316
317 if (HexSwizzle)
318 compStr++;
319
320 while (*compStr) {
321 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
322 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
323 << baseType << SourceRange(CompLoc);
324 return QualType();
325 }
326 }
327 }
328
329 // The component accessor looks fine - now we need to compute the actual type.
330 // The vector type is implied by the component accessor. For example,
331 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
332 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
333 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
334 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
335 : CompName->getLength();
336 if (HexSwizzle)
337 CompSize--;
338
339 if (CompSize == 1)
340 return vecType->getElementType();
341
342 if (HasRepeated) VK = VK_RValue;
343
344 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
345 // Now look up the TypeDefDecl from the vector type. Without this,
346 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000347 for (Sema::ExtVectorDeclsType::iterator
Axel Naumann0ec56b72012-10-18 19:05:02 +0000348 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregord58a0a52011-07-28 00:39:29 +0000349 E = S.ExtVectorDecls.end();
350 I != E; ++I) {
351 if ((*I)->getUnderlyingType() == VT)
352 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000353 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000354
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000355 return VT; // should never get here (a typedef type should always be found).
356}
357
358static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
359 IdentifierInfo *Member,
360 const Selector &Sel,
361 ASTContext &Context) {
362 if (Member)
363 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
364 return PD;
365 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
366 return OMD;
367
368 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
369 E = PDecl->protocol_end(); I != E; ++I) {
370 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
371 Context))
372 return D;
373 }
374 return 0;
375}
376
377static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
378 IdentifierInfo *Member,
379 const Selector &Sel,
380 ASTContext &Context) {
381 // Check protocols on qualified interfaces.
382 Decl *GDecl = 0;
383 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
384 E = QIdTy->qual_end(); I != E; ++I) {
385 if (Member)
386 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
387 GDecl = PD;
388 break;
389 }
390 // Also must look for a getter or setter name which uses property syntax.
391 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
392 GDecl = OMD;
393 break;
394 }
395 }
396 if (!GDecl) {
397 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
398 E = QIdTy->qual_end(); I != E; ++I) {
399 // Search in the protocol-qualifier list of current protocol.
400 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
401 Context);
402 if (GDecl)
403 return GDecl;
404 }
405 }
406 return GDecl;
407}
408
409ExprResult
410Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
411 bool IsArrow, SourceLocation OpLoc,
412 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000413 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000414 NamedDecl *FirstQualifierInScope,
415 const DeclarationNameInfo &NameInfo,
416 const TemplateArgumentListInfo *TemplateArgs) {
417 // Even in dependent contexts, try to diagnose base expressions with
418 // obviously wrong types, e.g.:
419 //
420 // T* t;
421 // t.f;
422 //
423 // In Obj-C++, however, the above expression is valid, since it could be
424 // accessing the 'f' property if T is an Obj-C interface. The extra check
425 // allows this, while still reporting an error if T is a struct pointer.
426 if (!IsArrow) {
427 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikie4e4d0842012-03-11 07:00:24 +0000428 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000429 PT->getPointeeType()->isRecordType())) {
430 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +0000431 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +0000432 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000433 return ExprError();
434 }
435 }
436
437 assert(BaseType->isDependentType() ||
438 NameInfo.getName().isDependentName() ||
439 isDependentScopeSpecifier(SS));
440
441 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
442 // must have pointer type, and the accessed type is the pointee.
443 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
444 IsArrow, OpLoc,
445 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000446 TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000447 FirstQualifierInScope,
448 NameInfo, TemplateArgs));
449}
450
451/// We know that the given qualified member reference points only to
452/// declarations which do not belong to the static type of the base
453/// expression. Diagnose the problem.
454static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
455 Expr *BaseExpr,
456 QualType BaseType,
457 const CXXScopeSpec &SS,
458 NamedDecl *rep,
459 const DeclarationNameInfo &nameInfo) {
460 // If this is an implicit member access, use a different set of
461 // diagnostics.
462 if (!BaseExpr)
Richard Smitha85cf392012-04-05 01:13:04 +0000463 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000464
465 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
466 << SS.getRange() << rep << BaseType;
467}
468
469// Check whether the declarations we found through a nested-name
470// specifier in a member expression are actually members of the base
471// type. The restriction here is:
472//
473// C++ [expr.ref]p2:
474// ... In these cases, the id-expression shall name a
475// member of the class or of one of its base classes.
476//
477// So it's perfectly legitimate for the nested-name specifier to name
478// an unrelated class, and for us to find an overload set including
479// decls from classes which are not superclasses, as long as the decl
480// we actually pick through overload resolution is from a superclass.
481bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
482 QualType BaseType,
483 const CXXScopeSpec &SS,
484 const LookupResult &R) {
Richard Smithf62c6902012-11-22 00:24:47 +0000485 CXXRecordDecl *BaseRecord =
486 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
487 if (!BaseRecord) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000488 // We can't check this yet because the base type is still
489 // dependent.
490 assert(BaseType->isDependentType());
491 return false;
492 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000493
494 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
495 // If this is an implicit member reference and we find a
496 // non-instance member, it's not an error.
497 if (!BaseExpr && !(*I)->isCXXInstanceMember())
498 return false;
499
500 // Note that we use the DC of the decl, not the underlying decl.
501 DeclContext *DC = (*I)->getDeclContext();
502 while (DC->isTransparentContext())
503 DC = DC->getParent();
504
505 if (!DC->isRecord())
506 continue;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000507
Richard Smithf62c6902012-11-22 00:24:47 +0000508 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
509 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
510 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000511 return false;
512 }
513
514 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
515 R.getRepresentativeDecl(),
516 R.getLookupNameInfo());
517 return true;
518}
519
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000520namespace {
521
522// Callback to only accept typo corrections that are either a ValueDecl or a
523// FunctionTemplateDecl.
524class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
525 public:
526 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
527 NamedDecl *ND = candidate.getCorrectionDecl();
528 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
529 }
530};
531
532}
533
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000534static bool
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000535LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000536 SourceRange BaseRange, const RecordType *RTy,
537 SourceLocation OpLoc, CXXScopeSpec &SS,
538 bool HasTemplateArgs) {
539 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000540 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
541 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregord10099e2012-05-04 16:32:21 +0000542 diag::err_typecheck_incomplete_tag,
543 BaseRange))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000544 return true;
545
546 if (HasTemplateArgs) {
547 // LookupTemplateName doesn't expect these both to exist simultaneously.
548 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
549
550 bool MOUS;
551 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
552 return false;
553 }
554
555 DeclContext *DC = RDecl;
556 if (SS.isSet()) {
557 // If the member name was a qualified-id, look into the
558 // nested-name-specifier.
559 DC = SemaRef.computeDeclContext(SS, false);
560
561 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
562 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
563 << SS.getRange() << DC;
564 return true;
565 }
566
567 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
568
569 if (!isa<TypeDecl>(DC)) {
570 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
571 << DC << SS.getRange();
572 return true;
573 }
574 }
575
576 // The record definition is complete, now look up the member.
577 SemaRef.LookupQualifiedName(R, DC);
578
579 if (!R.empty())
580 return false;
581
582 // We didn't find anything with the given name, so try to correct
583 // for typos.
584 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000585 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000586 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
587 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000588 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000589 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000590 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000591 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000592 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000593 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000594 Corrected.getQuoted(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000595 R.setLookupName(Corrected.getCorrection());
596 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000597 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000598 << Name << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +0000599 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
600 CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000601 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
602 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000603 }
604
605 return false;
606}
607
608ExprResult
609Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
610 SourceLocation OpLoc, bool IsArrow,
611 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000612 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000613 NamedDecl *FirstQualifierInScope,
614 const DeclarationNameInfo &NameInfo,
615 const TemplateArgumentListInfo *TemplateArgs) {
616 if (BaseType->isDependentType() ||
617 (SS.isSet() && isDependentScopeSpecifier(SS)))
618 return ActOnDependentMemberExpr(Base, BaseType,
619 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000620 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000621 NameInfo, TemplateArgs);
622
623 LookupResult R(*this, NameInfo, LookupMemberName);
624
625 // Implicit member accesses.
626 if (!Base) {
627 QualType RecordTy = BaseType;
628 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
629 if (LookupMemberExprInRecord(*this, R, SourceRange(),
630 RecordTy->getAs<RecordType>(),
631 OpLoc, SS, TemplateArgs != 0))
632 return ExprError();
633
634 // Explicit member accesses.
635 } else {
636 ExprResult BaseResult = Owned(Base);
637 ExprResult Result =
638 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
639 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
640
641 if (BaseResult.isInvalid())
642 return ExprError();
643 Base = BaseResult.take();
644
645 if (Result.isInvalid()) {
646 Owned(Base);
647 return ExprError();
648 }
649
650 if (Result.get())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000651 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000652
653 // LookupMemberExpr can modify Base, and thus change BaseType
654 BaseType = Base->getType();
655 }
656
657 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000658 OpLoc, IsArrow, SS, TemplateKWLoc,
659 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000660}
661
662static ExprResult
663BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
664 const CXXScopeSpec &SS, FieldDecl *Field,
665 DeclAccessPair FoundDecl,
666 const DeclarationNameInfo &MemberNameInfo);
667
668ExprResult
669Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
670 SourceLocation loc,
671 IndirectFieldDecl *indirectField,
672 Expr *baseObjectExpr,
673 SourceLocation opLoc) {
674 // First, build the expression that refers to the base object.
675
676 bool baseObjectIsPointer = false;
677 Qualifiers baseQuals;
678
679 // Case 1: the base of the indirect field is not a field.
680 VarDecl *baseVariable = indirectField->getVarDecl();
681 CXXScopeSpec EmptySS;
682 if (baseVariable) {
683 assert(baseVariable->getType()->isRecordType());
684
685 // In principle we could have a member access expression that
686 // accesses an anonymous struct/union that's a static member of
687 // the base object's class. However, under the current standard,
688 // static data members cannot be anonymous structs or unions.
689 // Supporting this is as easy as building a MemberExpr here.
690 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
691
692 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
693
694 ExprResult result
695 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
696 if (result.isInvalid()) return ExprError();
697
698 baseObjectExpr = result.take();
699 baseObjectIsPointer = false;
700 baseQuals = baseObjectExpr->getType().getQualifiers();
701
702 // Case 2: the base of the indirect field is a field and the user
703 // wrote a member expression.
704 } else if (baseObjectExpr) {
705 // The caller provided the base object expression. Determine
706 // whether its a pointer and whether it adds any qualifiers to the
707 // anonymous struct/union fields we're looking into.
708 QualType objectType = baseObjectExpr->getType();
709
710 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
711 baseObjectIsPointer = true;
712 objectType = ptr->getPointeeType();
713 } else {
714 baseObjectIsPointer = false;
715 }
716 baseQuals = objectType.getQualifiers();
717
718 // Case 3: the base of the indirect field is a field and we should
719 // build an implicit member access.
720 } else {
721 // We've found a member of an anonymous struct/union that is
722 // inside a non-anonymous struct/union, so in a well-formed
723 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000724 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000725 if (ThisTy.isNull()) {
726 Diag(loc, diag::err_invalid_member_use_in_static_method)
727 << indirectField->getDeclName();
728 return ExprError();
729 }
730
731 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000732 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000733 baseObjectExpr
734 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
735 baseObjectIsPointer = true;
736 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
737 }
738
739 // Build the implicit member references to the field of the
740 // anonymous struct/union.
741 Expr *result = baseObjectExpr;
742 IndirectFieldDecl::chain_iterator
743 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
744
745 // Build the first member access in the chain with full information.
746 if (!baseVariable) {
747 FieldDecl *field = cast<FieldDecl>(*FI);
748
749 // FIXME: use the real found-decl info!
750 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
751
752 // Make a nameInfo that properly uses the anonymous name.
753 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
754
755 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
756 EmptySS, field, foundDecl,
757 memberNameInfo).take();
758 baseObjectIsPointer = false;
759
760 // FIXME: check qualified member access
761 }
762
763 // In all cases, we should now skip the first declaration in the chain.
764 ++FI;
765
766 while (FI != FEnd) {
767 FieldDecl *field = cast<FieldDecl>(*FI++);
768
769 // FIXME: these are somewhat meaningless
770 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
771 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
772
773 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
774 (FI == FEnd? SS : EmptySS), field,
775 foundDecl, memberNameInfo).take();
776 }
777
778 return Owned(result);
779}
780
781/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000782static MemberExpr *BuildMemberExpr(Sema &SemaRef,
783 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000784 const CXXScopeSpec &SS,
785 SourceLocation TemplateKWLoc,
786 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000787 DeclAccessPair FoundDecl,
788 const DeclarationNameInfo &MemberNameInfo,
789 QualType Ty,
790 ExprValueKind VK, ExprObjectKind OK,
791 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000792 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000793 MemberExpr *E =
794 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
795 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
796 TemplateArgs, Ty, VK, OK);
797 SemaRef.MarkMemberReferenced(E);
798 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000799}
800
801ExprResult
802Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
803 SourceLocation OpLoc, bool IsArrow,
804 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000805 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000806 NamedDecl *FirstQualifierInScope,
807 LookupResult &R,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000808 const TemplateArgumentListInfo *TemplateArgs,
809 bool SuppressQualifierCheck,
810 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000811 QualType BaseType = BaseExprType;
812 if (IsArrow) {
813 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000814 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000815 }
816 R.setBaseObjectType(BaseType);
817
818 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
819 DeclarationName MemberName = MemberNameInfo.getName();
820 SourceLocation MemberLoc = MemberNameInfo.getLoc();
821
822 if (R.isAmbiguous())
823 return ExprError();
824
825 if (R.empty()) {
826 // Rederive where we looked up.
827 DeclContext *DC = (SS.isSet()
828 ? computeDeclContext(SS, false)
829 : BaseType->getAs<RecordType>()->getDecl());
830
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000831 if (ExtraArgs) {
832 ExprResult RetryExpr;
833 if (!IsArrow && BaseExpr) {
Kaelyn Uhrain111263c2012-05-01 01:17:53 +0000834 SFINAETrap Trap(*this, true);
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000835 ParsedType ObjectType;
836 bool MayBePseudoDestructor = false;
837 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
838 OpLoc, tok::arrow, ObjectType,
839 MayBePseudoDestructor);
840 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
841 CXXScopeSpec TempSS(SS);
842 RetryExpr = ActOnMemberAccessExpr(
843 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
844 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
845 ExtraArgs->HasTrailingLParen);
846 }
847 if (Trap.hasErrorOccurred())
848 RetryExpr = ExprError();
849 }
850 if (RetryExpr.isUsable()) {
851 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
852 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
853 return RetryExpr;
854 }
855 }
856
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000857 Diag(R.getNameLoc(), diag::err_no_member)
858 << MemberName << DC
859 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
860 return ExprError();
861 }
862
863 // Diagnose lookups that find only declarations from a non-base
864 // type. This is possible for either qualified lookups (which may
865 // have been qualified with an unrelated type) or implicit member
866 // expressions (which were found with unqualified lookup and thus
867 // may have come from an enclosing scope). Note that it's okay for
868 // lookup to find declarations from a non-base type as long as those
869 // aren't the ones picked by overload resolution.
870 if ((SS.isSet() || !BaseExpr ||
871 (isa<CXXThisExpr>(BaseExpr) &&
872 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
873 !SuppressQualifierCheck &&
874 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
875 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000876
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000877 // Construct an unresolved result if we in fact got an unresolved
878 // result.
879 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
880 // Suppress any lookup-related diagnostics; we'll do these when we
881 // pick a member.
882 R.suppressDiagnostics();
883
884 UnresolvedMemberExpr *MemExpr
885 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
886 BaseExpr, BaseExprType,
887 IsArrow, OpLoc,
888 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000889 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000890 TemplateArgs, R.begin(), R.end());
891
892 return Owned(MemExpr);
893 }
894
895 assert(R.isSingleResult());
896 DeclAccessPair FoundDecl = R.begin().getPair();
897 NamedDecl *MemberDecl = R.getFoundDecl();
898
899 // FIXME: diagnose the presence of template arguments now.
900
901 // If the decl being referenced had an error, return an error for this
902 // sub-expr without emitting another error, in order to avoid cascading
903 // error cases.
904 if (MemberDecl->isInvalidDecl())
905 return ExprError();
906
907 // Handle the implicit-member-access case.
908 if (!BaseExpr) {
909 // If this is not an instance member, convert to a non-member access.
910 if (!MemberDecl->isCXXInstanceMember())
911 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
912
913 SourceLocation Loc = R.getNameLoc();
914 if (SS.getRange().isValid())
915 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000916 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000917 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
918 }
919
920 bool ShouldCheckUse = true;
921 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
922 // Don't diagnose the use of a virtual member function unless it's
923 // explicitly qualified.
924 if (MD->isVirtual() && !SS.isSet())
925 ShouldCheckUse = false;
926 }
927
928 // Check the use of this member.
929 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
930 Owned(BaseExpr);
931 return ExprError();
932 }
933
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000934 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
935 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
936 SS, FD, FoundDecl, MemberNameInfo);
937
938 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
939 // We may have found a field within an anonymous union or struct
940 // (C++ [class.union]).
941 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
942 BaseExpr, OpLoc);
943
944 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000945 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
946 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000947 Var->getType().getNonReferenceType(),
948 VK_LValue, OK_Ordinary));
949 }
950
951 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
952 ExprValueKind valueKind;
953 QualType type;
954 if (MemberFn->isInstance()) {
955 valueKind = VK_RValue;
956 type = Context.BoundMemberTy;
957 } else {
958 valueKind = VK_LValue;
959 type = MemberFn->getType();
960 }
961
Eli Friedman5f2987c2012-02-02 03:46:19 +0000962 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
963 TemplateKWLoc, MemberFn, FoundDecl,
964 MemberNameInfo, type, valueKind,
965 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000966 }
967 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
968
969 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000970 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
971 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000972 Enum->getType(), VK_RValue, OK_Ordinary));
973 }
974
975 Owned(BaseExpr);
976
977 // We found something that we didn't expect. Complain.
978 if (isa<TypeDecl>(MemberDecl))
979 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
980 << MemberName << BaseType << int(IsArrow);
981 else
982 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
983 << MemberName << BaseType << int(IsArrow);
984
985 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
986 << MemberName;
987 R.suppressDiagnostics();
988 return ExprError();
989}
990
991/// Given that normal member access failed on the given expression,
992/// and given that the expression's type involves builtin-id or
993/// builtin-Class, decide whether substituting in the redefinition
994/// types would be profitable. The redefinition type is whatever
995/// this translation unit tried to typedef to id/Class; we store
996/// it to the side and then re-use it in places like this.
997static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
998 const ObjCObjectPointerType *opty
999 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1000 if (!opty) return false;
1001
1002 const ObjCObjectType *ty = opty->getObjectType();
1003
1004 QualType redef;
1005 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001006 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001007 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001008 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001009 } else {
1010 return false;
1011 }
1012
1013 // Do the substitution as long as the redefinition type isn't just a
1014 // possibly-qualified pointer to builtin-id or builtin-Class again.
1015 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieu47fcbba2012-10-12 17:48:40 +00001016 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001017 return false;
1018
1019 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1020 return true;
1021}
1022
John McCall6dbba4f2011-10-11 23:14:30 +00001023static bool isRecordType(QualType T) {
1024 return T->isRecordType();
1025}
1026static bool isPointerToRecordType(QualType T) {
1027 if (const PointerType *PT = T->getAs<PointerType>())
1028 return PT->getPointeeType()->isRecordType();
1029 return false;
1030}
1031
Richard Smith9138b4e2011-10-26 19:06:56 +00001032/// Perform conversions on the LHS of a member access expression.
1033ExprResult
1034Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001035 if (IsArrow && !Base->getType()->isFunctionType())
1036 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001037
Eli Friedman059d5782012-01-13 02:20:01 +00001038 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001039}
1040
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001041/// Look up the given member of the given non-type-dependent
1042/// expression. This can return in one of two ways:
1043/// * If it returns a sentinel null-but-valid result, the caller will
1044/// assume that lookup was performed and the results written into
1045/// the provided structure. It will take over from there.
1046/// * Otherwise, the returned expression will be produced in place of
1047/// an ordinary member expression.
1048///
1049/// The ObjCImpDecl bit is a gross hack that will need to be properly
1050/// fixed for ObjC++.
1051ExprResult
1052Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1053 bool &IsArrow, SourceLocation OpLoc,
1054 CXXScopeSpec &SS,
1055 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1056 assert(BaseExpr.get() && "no base expression");
1057
1058 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001059 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001060 if (BaseExpr.isInvalid())
1061 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001062
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001063 QualType BaseType = BaseExpr.get()->getType();
1064 assert(!BaseType->isDependentType());
1065
1066 DeclarationName MemberName = R.getLookupName();
1067 SourceLocation MemberLoc = R.getNameLoc();
1068
1069 // For later type-checking purposes, turn arrow accesses into dot
1070 // accesses. The only access type we support that doesn't follow
1071 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1072 // and those never use arrows, so this is unaffected.
1073 if (IsArrow) {
1074 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1075 BaseType = Ptr->getPointeeType();
1076 else if (const ObjCObjectPointerType *Ptr
1077 = BaseType->getAs<ObjCObjectPointerType>())
1078 BaseType = Ptr->getPointeeType();
1079 else if (BaseType->isRecordType()) {
1080 // Recover from arrow accesses to records, e.g.:
1081 // struct MyRecord foo;
1082 // foo->bar
1083 // This is actually well-formed in C++ if MyRecord has an
1084 // overloaded operator->, but that should have been dealt with
1085 // by now.
1086 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1087 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1088 << FixItHint::CreateReplacement(OpLoc, ".");
1089 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001090 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001091 goto fail;
1092 } else {
1093 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1094 << BaseType << BaseExpr.get()->getSourceRange();
1095 return ExprError();
1096 }
1097 }
1098
1099 // Handle field access to simple records.
1100 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1101 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1102 RTy, OpLoc, SS, HasTemplateArgs))
1103 return ExprError();
1104
1105 // Returning valid-but-null is how we indicate to the caller that
1106 // the lookup result was filled in.
1107 return Owned((Expr*) 0);
1108 }
1109
1110 // Handle ivar access to Objective-C objects.
1111 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001112 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001113 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1114 << 1 << SS.getScopeRep()
1115 << FixItHint::CreateRemoval(SS.getRange());
1116 SS.clear();
1117 }
1118
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001119 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1120
1121 // There are three cases for the base type:
1122 // - builtin id (qualified or unqualified)
1123 // - builtin Class (qualified or unqualified)
1124 // - an interface
1125 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1126 if (!IDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001127 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001128 (OTy->isObjCId() || OTy->isObjCClass()))
1129 goto fail;
1130 // There's an implicit 'isa' ivar on all objects.
1131 // But we only actually find it this way on objects of type 'id',
Eric Christopher2502ec82012-08-16 23:50:37 +00001132 // apparently.
Fariborz Jahanian7e352742013-03-27 21:19:25 +00001133 if (OTy->isObjCId() && Member->isStr("isa"))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001134 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1135 Context.getObjCClassType()));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001136 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1137 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1138 ObjCImpDecl, HasTemplateArgs);
1139 goto fail;
1140 }
Fariborz Jahanian09100592012-06-21 21:35:15 +00001141 else if (Member && Member->isStr("isa")) {
1142 // If an ivar is (1) the first ivar in a root class and (2) named `isa`,
1143 // then issue the same deprecated warning that id->isa gets.
1144 ObjCInterfaceDecl *ClassDeclared = 0;
1145 if (ObjCIvarDecl *IV =
1146 IDecl->lookupInstanceVariable(Member, ClassDeclared)) {
1147 if (!ClassDeclared->getSuperClass()
1148 && (*ClassDeclared->ivar_begin()) == IV) {
1149 Diag(MemberLoc, diag::warn_objc_isa_use);
1150 Diag(IV->getLocation(), diag::note_ivar_decl);
1151 }
1152 }
1153 }
1154
Douglas Gregord10099e2012-05-04 16:32:21 +00001155 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1156 BaseExpr.get()))
Douglas Gregord07cc362012-01-02 17:18:37 +00001157 return ExprError();
1158
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001159 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001160 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1161
1162 if (!IV) {
1163 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001164 DeclFilterCCC<ObjCIvarDecl> Validator;
1165 Validator.IsObjCIvarLookup = IsArrow;
1166 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1167 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001168 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001169 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001170 Diag(R.getNameLoc(),
1171 diag::err_typecheck_member_reference_ivar_suggest)
1172 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1173 << FixItHint::CreateReplacement(R.getNameLoc(),
1174 IV->getNameAsString());
1175 Diag(IV->getLocation(), diag::note_previous_decl)
1176 << IV->getDeclName();
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001177
1178 // Figure out the class that declares the ivar.
1179 assert(!ClassDeclared);
1180 Decl *D = cast<Decl>(IV->getDeclContext());
1181 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1182 D = CAT->getClassInterface();
1183 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001184 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001185 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1186 Diag(MemberLoc,
1187 diag::err_property_found_suggest)
1188 << Member << BaseExpr.get()->getType()
1189 << FixItHint::CreateReplacement(OpLoc, ".");
1190 return ExprError();
1191 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001192
1193 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1194 << IDecl->getDeclName() << MemberName
1195 << BaseExpr.get()->getSourceRange();
1196 return ExprError();
1197 }
1198 }
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001199
1200 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001201
1202 // If the decl being referenced had an error, return an error for this
1203 // sub-expr without emitting another error, in order to avoid cascading
1204 // error cases.
1205 if (IV->isInvalidDecl())
1206 return ExprError();
1207
1208 // Check whether we can reference this field.
1209 if (DiagnoseUseOfDecl(IV, MemberLoc))
1210 return ExprError();
1211 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1212 IV->getAccessControl() != ObjCIvarDecl::Package) {
1213 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1214 if (ObjCMethodDecl *MD = getCurMethodDecl())
1215 ClassOfMethodDecl = MD->getClassInterface();
1216 else if (ObjCImpDecl && getCurFunctionDecl()) {
1217 // Case of a c-function declared inside an objc implementation.
1218 // FIXME: For a c-style function nested inside an objc implementation
1219 // class, there is no implementation context available, so we pass
1220 // down the context as argument to this routine. Ideally, this context
1221 // need be passed down in the AST node and somehow calculated from the
1222 // AST for a function decl.
1223 if (ObjCImplementationDecl *IMPD =
1224 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1225 ClassOfMethodDecl = IMPD->getClassInterface();
1226 else if (ObjCCategoryImplDecl* CatImplClass =
1227 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1228 ClassOfMethodDecl = CatImplClass->getClassInterface();
1229 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001230 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001231 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1232 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1233 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1234 Diag(MemberLoc, diag::error_private_ivar_access)
1235 << IV->getDeclName();
1236 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1237 // @protected
1238 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001239 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001240 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001241 }
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001242 bool warn = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00001243 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001244 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1245 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1246 if (UO->getOpcode() == UO_Deref)
1247 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1248
1249 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001250 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001251 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001252 warn = false;
1253 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001254 }
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001255 if (warn) {
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001256 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1257 ObjCMethodFamily MF = MD->getMethodFamily();
1258 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahanian26202292013-02-14 19:07:19 +00001259 MF != OMF_finalize &&
1260 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001261 }
1262 if (warn)
1263 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1264 }
Jordan Rose7a270482012-09-28 22:21:35 +00001265
1266 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1267 MemberLoc,
1268 BaseExpr.take(),
1269 IsArrow);
1270
1271 if (getLangOpts().ObjCAutoRefCount) {
1272 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1273 DiagnosticsEngine::Level Level =
1274 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1275 MemberLoc);
1276 if (Level != DiagnosticsEngine::Ignored)
1277 getCurFunction()->recordUseOfWeak(Result);
1278 }
1279 }
1280
1281 return Owned(Result);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001282 }
1283
1284 // Objective-C property access.
1285 const ObjCObjectPointerType *OPT;
1286 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001287 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001288 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1289 << 0 << SS.getScopeRep()
1290 << FixItHint::CreateRemoval(SS.getRange());
1291 SS.clear();
1292 }
1293
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001294 // This actually uses the base as an r-value.
1295 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1296 if (BaseExpr.isInvalid())
1297 return ExprError();
1298
1299 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1300
1301 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1302
1303 const ObjCObjectType *OT = OPT->getObjectType();
1304
1305 // id, with and without qualifiers.
1306 if (OT->isObjCId()) {
1307 // Check protocols on qualified interfaces.
1308 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1309 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1310 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1311 // Check the use of this declaration
1312 if (DiagnoseUseOfDecl(PD, MemberLoc))
1313 return ExprError();
1314
John McCall3c3b7f92011-10-25 17:37:35 +00001315 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1316 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001317 VK_LValue,
1318 OK_ObjCProperty,
1319 MemberLoc,
1320 BaseExpr.take()));
1321 }
1322
1323 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1324 // Check the use of this method.
1325 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1326 return ExprError();
1327 Selector SetterSel =
1328 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1329 PP.getSelectorTable(), Member);
1330 ObjCMethodDecl *SMD = 0;
1331 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1332 SetterSel, Context))
1333 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001334
John McCall3c3b7f92011-10-25 17:37:35 +00001335 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1336 Context.PseudoObjectTy,
1337 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001338 MemberLoc, BaseExpr.take()));
1339 }
1340 }
1341 // Use of id.member can only be for a property reference. Do not
1342 // use the 'id' redefinition in this case.
1343 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1344 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1345 ObjCImpDecl, HasTemplateArgs);
1346
1347 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1348 << MemberName << BaseType);
1349 }
1350
1351 // 'Class', unqualified only.
1352 if (OT->isObjCClass()) {
1353 // Only works in a method declaration (??!).
1354 ObjCMethodDecl *MD = getCurMethodDecl();
1355 if (!MD) {
1356 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1357 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1358 ObjCImpDecl, HasTemplateArgs);
1359
1360 goto fail;
1361 }
1362
1363 // Also must look for a getter name which uses property syntax.
1364 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1365 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1366 ObjCMethodDecl *Getter;
1367 if ((Getter = IFace->lookupClassMethod(Sel))) {
1368 // Check the use of this method.
1369 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1370 return ExprError();
1371 } else
1372 Getter = IFace->lookupPrivateMethod(Sel, false);
1373 // If we found a getter then this may be a valid dot-reference, we
1374 // will look for the matching setter, in case it is needed.
1375 Selector SetterSel =
1376 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1377 PP.getSelectorTable(), Member);
1378 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1379 if (!Setter) {
1380 // If this reference is in an @implementation, also check for 'private'
1381 // methods.
1382 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1383 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001384
1385 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1386 return ExprError();
1387
1388 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001389 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001390 Context.PseudoObjectTy,
1391 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001392 MemberLoc, BaseExpr.take()));
1393 }
1394
1395 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1396 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1397 ObjCImpDecl, HasTemplateArgs);
1398
1399 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1400 << MemberName << BaseType);
1401 }
1402
1403 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001404 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1405 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001406 SourceLocation(), QualType(), false);
1407 }
1408
1409 // Handle 'field access' to vectors, such as 'V.xx'.
1410 if (BaseType->isExtVectorType()) {
1411 // FIXME: this expr should store IsArrow.
1412 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1413 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1414 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1415 Member, MemberLoc);
1416 if (ret.isNull())
1417 return ExprError();
1418
1419 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1420 *Member, MemberLoc));
1421 }
1422
1423 // Adjust builtin-sel to the appropriate redefinition type if that's
1424 // not just a pointer to builtin-sel again.
1425 if (IsArrow &&
1426 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001427 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1428 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1429 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001430 CK_BitCast);
1431 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1432 ObjCImpDecl, HasTemplateArgs);
1433 }
1434
1435 // Failure cases.
1436 fail:
1437
1438 // Recover from dot accesses to pointers, e.g.:
1439 // type *foo;
1440 // foo.bar
1441 // This is actually well-formed in two cases:
1442 // - 'type' is an Objective C type
1443 // - 'bar' is a pseudo-destructor name which happens to refer to
1444 // the appropriate pointer type
1445 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1446 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1447 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1448 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1449 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1450 << FixItHint::CreateReplacement(OpLoc, "->");
1451
1452 // Recurse as an -> access.
1453 IsArrow = true;
1454 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1455 ObjCImpDecl, HasTemplateArgs);
1456 }
1457 }
1458
1459 // If the user is trying to apply -> or . to a function name, it's probably
1460 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001461 if (tryToRecoverWithCall(BaseExpr,
1462 PDiag(diag::err_member_reference_needs_call),
1463 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001464 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001465 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001466 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001467 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1468 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1469 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001470 }
1471
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +00001472 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +00001473 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001474
1475 return ExprError();
1476}
1477
1478/// The main callback when the parser finds something like
1479/// expression . [nested-name-specifier] identifier
1480/// expression -> [nested-name-specifier] identifier
1481/// where 'identifier' encompasses a fairly broad spectrum of
1482/// possibilities, including destructor and operator references.
1483///
1484/// \param OpKind either tok::arrow or tok::period
1485/// \param HasTrailingLParen whether the next token is '(', which
1486/// is used to diagnose mis-uses of special members that can
1487/// only be called
James Dennett699c9042012-06-15 07:13:21 +00001488/// \param ObjCImpDecl the current Objective-C \@implementation
1489/// decl; this is an ugly hack around the fact that Objective-C
1490/// \@implementations aren't properly put in the context chain
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001491ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1492 SourceLocation OpLoc,
1493 tok::TokenKind OpKind,
1494 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001495 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001496 UnqualifiedId &Id,
1497 Decl *ObjCImpDecl,
1498 bool HasTrailingLParen) {
1499 if (SS.isSet() && SS.isInvalid())
1500 return ExprError();
1501
1502 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001503 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001504 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1505 Diag(Id.getSourceRange().getBegin(),
1506 diag::ext_ms_explicit_constructor_call);
1507
1508 TemplateArgumentListInfo TemplateArgsBuffer;
1509
1510 // Decompose the name into its component parts.
1511 DeclarationNameInfo NameInfo;
1512 const TemplateArgumentListInfo *TemplateArgs;
1513 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1514 NameInfo, TemplateArgs);
1515
1516 DeclarationName Name = NameInfo.getName();
1517 bool IsArrow = (OpKind == tok::arrow);
1518
1519 NamedDecl *FirstQualifierInScope
1520 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1521 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1522
1523 // This is a postfix expression, so get rid of ParenListExprs.
1524 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1525 if (Result.isInvalid()) return ExprError();
1526 Base = Result.take();
1527
1528 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1529 isDependentScopeSpecifier(SS)) {
1530 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1531 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001532 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001533 NameInfo, TemplateArgs);
1534 } else {
1535 LookupResult R(*this, NameInfo, LookupMemberName);
1536 ExprResult BaseResult = Owned(Base);
1537 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1538 SS, ObjCImpDecl, TemplateArgs != 0);
1539 if (BaseResult.isInvalid())
1540 return ExprError();
1541 Base = BaseResult.take();
1542
1543 if (Result.isInvalid()) {
1544 Owned(Base);
1545 return ExprError();
1546 }
1547
1548 if (Result.get()) {
1549 // The only way a reference to a destructor can be used is to
1550 // immediately call it, which falls into this case. If the
1551 // next token is not a '(', produce a diagnostic and build the
1552 // call now.
1553 if (!HasTrailingLParen &&
1554 Id.getKind() == UnqualifiedId::IK_DestructorName)
1555 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1556
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001557 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001558 }
1559
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001560 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001561 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001562 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001563 FirstQualifierInScope, R, TemplateArgs,
1564 false, &ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001565 }
1566
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001567 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001568}
1569
1570static ExprResult
1571BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1572 const CXXScopeSpec &SS, FieldDecl *Field,
1573 DeclAccessPair FoundDecl,
1574 const DeclarationNameInfo &MemberNameInfo) {
1575 // x.a is an l-value if 'a' has a reference type. Otherwise:
1576 // x.a is an l-value/x-value/pr-value if the base is (and note
1577 // that *x is always an l-value), except that if the base isn't
1578 // an ordinary object then we must have an rvalue.
1579 ExprValueKind VK = VK_LValue;
1580 ExprObjectKind OK = OK_Ordinary;
1581 if (!IsArrow) {
1582 if (BaseExpr->getObjectKind() == OK_Ordinary)
1583 VK = BaseExpr->getValueKind();
1584 else
1585 VK = VK_RValue;
1586 }
1587 if (VK != VK_RValue && Field->isBitField())
1588 OK = OK_BitField;
1589
1590 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1591 QualType MemberType = Field->getType();
1592 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1593 MemberType = Ref->getPointeeType();
1594 VK = VK_LValue;
1595 } else {
1596 QualType BaseType = BaseExpr->getType();
1597 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001598
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001599 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001600
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001601 // GC attributes are never picked up by members.
1602 BaseQuals.removeObjCGCAttr();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001603
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001604 // CVR attributes from the base are picked up by members,
1605 // except that 'mutable' members don't pick up 'const'.
1606 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001607
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001608 Qualifiers MemberQuals
1609 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001610
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001611 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001612
1613
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001614 Qualifiers Combined = BaseQuals + MemberQuals;
1615 if (Combined != MemberQuals)
1616 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1617 }
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001618
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001619 S.UnusedPrivateFields.remove(Field);
1620
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001621 ExprResult Base =
1622 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1623 FoundDecl, Field);
1624 if (Base.isInvalid())
1625 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001626 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001627 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001628 Field, FoundDecl, MemberNameInfo,
1629 MemberType, VK, OK));
1630}
1631
1632/// Builds an implicit member access expression. The current context
1633/// is known to be an instance method, and the given unqualified lookup
1634/// set is known to contain only instance members, at least one of which
1635/// is from an appropriate type.
1636ExprResult
1637Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001638 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001639 LookupResult &R,
1640 const TemplateArgumentListInfo *TemplateArgs,
1641 bool IsKnownInstance) {
1642 assert(!R.empty() && !R.isAmbiguous());
1643
1644 SourceLocation loc = R.getNameLoc();
1645
1646 // We may have found a field within an anonymous union or struct
1647 // (C++ [class.union]).
1648 // FIXME: template-ids inside anonymous structs?
1649 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1650 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1651
1652 // If this is known to be an instance access, go ahead and build an
1653 // implicit 'this' expression now.
1654 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001655 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001656 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1657
1658 Expr *baseExpr = 0; // null signifies implicit access
1659 if (IsKnownInstance) {
1660 SourceLocation Loc = R.getNameLoc();
1661 if (SS.getRange().isValid())
1662 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001663 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001664 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1665 }
1666
1667 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1668 /*OpLoc*/ SourceLocation(),
1669 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001670 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001671 /*FirstQualifierInScope*/ 0,
1672 R, TemplateArgs);
1673}