blob: f1f810402026961e69ab12e8e83ff58fdf74d0b6 [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 Jahanian556b1d02012-01-18 19:08:56 +00001133 if (OTy->isObjCId() && Member->isStr("isa")) {
1134 Diag(MemberLoc, diag::warn_objc_isa_use);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001135 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1136 Context.getObjCClassType()));
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001137 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001138
1139 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1140 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1141 ObjCImpDecl, HasTemplateArgs);
1142 goto fail;
1143 }
Fariborz Jahanian09100592012-06-21 21:35:15 +00001144 else if (Member && Member->isStr("isa")) {
1145 // If an ivar is (1) the first ivar in a root class and (2) named `isa`,
1146 // then issue the same deprecated warning that id->isa gets.
1147 ObjCInterfaceDecl *ClassDeclared = 0;
1148 if (ObjCIvarDecl *IV =
1149 IDecl->lookupInstanceVariable(Member, ClassDeclared)) {
1150 if (!ClassDeclared->getSuperClass()
1151 && (*ClassDeclared->ivar_begin()) == IV) {
1152 Diag(MemberLoc, diag::warn_objc_isa_use);
1153 Diag(IV->getLocation(), diag::note_ivar_decl);
1154 }
1155 }
1156 }
1157
Douglas Gregord10099e2012-05-04 16:32:21 +00001158 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1159 BaseExpr.get()))
Douglas Gregord07cc362012-01-02 17:18:37 +00001160 return ExprError();
1161
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001162 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001163 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1164
1165 if (!IV) {
1166 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001167 DeclFilterCCC<ObjCIvarDecl> Validator;
1168 Validator.IsObjCIvarLookup = IsArrow;
1169 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1170 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001171 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001172 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001173 Diag(R.getNameLoc(),
1174 diag::err_typecheck_member_reference_ivar_suggest)
1175 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1176 << FixItHint::CreateReplacement(R.getNameLoc(),
1177 IV->getNameAsString());
1178 Diag(IV->getLocation(), diag::note_previous_decl)
1179 << IV->getDeclName();
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001180
1181 // Figure out the class that declares the ivar.
1182 assert(!ClassDeclared);
1183 Decl *D = cast<Decl>(IV->getDeclContext());
1184 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1185 D = CAT->getClassInterface();
1186 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001187 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001188 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1189 Diag(MemberLoc,
1190 diag::err_property_found_suggest)
1191 << Member << BaseExpr.get()->getType()
1192 << FixItHint::CreateReplacement(OpLoc, ".");
1193 return ExprError();
1194 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001195
1196 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1197 << IDecl->getDeclName() << MemberName
1198 << BaseExpr.get()->getSourceRange();
1199 return ExprError();
1200 }
1201 }
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001202
1203 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001204
1205 // If the decl being referenced had an error, return an error for this
1206 // sub-expr without emitting another error, in order to avoid cascading
1207 // error cases.
1208 if (IV->isInvalidDecl())
1209 return ExprError();
1210
1211 // Check whether we can reference this field.
1212 if (DiagnoseUseOfDecl(IV, MemberLoc))
1213 return ExprError();
1214 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1215 IV->getAccessControl() != ObjCIvarDecl::Package) {
1216 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1217 if (ObjCMethodDecl *MD = getCurMethodDecl())
1218 ClassOfMethodDecl = MD->getClassInterface();
1219 else if (ObjCImpDecl && getCurFunctionDecl()) {
1220 // Case of a c-function declared inside an objc implementation.
1221 // FIXME: For a c-style function nested inside an objc implementation
1222 // class, there is no implementation context available, so we pass
1223 // down the context as argument to this routine. Ideally, this context
1224 // need be passed down in the AST node and somehow calculated from the
1225 // AST for a function decl.
1226 if (ObjCImplementationDecl *IMPD =
1227 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1228 ClassOfMethodDecl = IMPD->getClassInterface();
1229 else if (ObjCCategoryImplDecl* CatImplClass =
1230 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1231 ClassOfMethodDecl = CatImplClass->getClassInterface();
1232 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001233 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001234 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1235 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1236 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1237 Diag(MemberLoc, diag::error_private_ivar_access)
1238 << IV->getDeclName();
1239 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1240 // @protected
1241 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001242 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001243 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001244 }
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001245 bool warn = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00001246 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001247 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1248 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1249 if (UO->getOpcode() == UO_Deref)
1250 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1251
1252 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001253 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001254 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001255 warn = false;
1256 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001257 }
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001258 if (warn) {
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001259 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1260 ObjCMethodFamily MF = MD->getMethodFamily();
1261 warn = (MF != OMF_init && MF != OMF_dealloc &&
1262 MF != OMF_finalize);
1263 }
1264 if (warn)
1265 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1266 }
Jordan Rose7a270482012-09-28 22:21:35 +00001267
1268 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1269 MemberLoc,
1270 BaseExpr.take(),
1271 IsArrow);
1272
1273 if (getLangOpts().ObjCAutoRefCount) {
1274 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1275 DiagnosticsEngine::Level Level =
1276 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1277 MemberLoc);
1278 if (Level != DiagnosticsEngine::Ignored)
1279 getCurFunction()->recordUseOfWeak(Result);
1280 }
1281 }
1282
1283 return Owned(Result);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001284 }
1285
1286 // Objective-C property access.
1287 const ObjCObjectPointerType *OPT;
1288 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001289 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001290 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1291 << 0 << SS.getScopeRep()
1292 << FixItHint::CreateRemoval(SS.getRange());
1293 SS.clear();
1294 }
1295
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001296 // This actually uses the base as an r-value.
1297 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1298 if (BaseExpr.isInvalid())
1299 return ExprError();
1300
1301 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1302
1303 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1304
1305 const ObjCObjectType *OT = OPT->getObjectType();
1306
1307 // id, with and without qualifiers.
1308 if (OT->isObjCId()) {
1309 // Check protocols on qualified interfaces.
1310 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1311 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1312 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1313 // Check the use of this declaration
1314 if (DiagnoseUseOfDecl(PD, MemberLoc))
1315 return ExprError();
1316
John McCall3c3b7f92011-10-25 17:37:35 +00001317 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1318 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001319 VK_LValue,
1320 OK_ObjCProperty,
1321 MemberLoc,
1322 BaseExpr.take()));
1323 }
1324
1325 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1326 // Check the use of this method.
1327 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1328 return ExprError();
1329 Selector SetterSel =
1330 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1331 PP.getSelectorTable(), Member);
1332 ObjCMethodDecl *SMD = 0;
1333 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1334 SetterSel, Context))
1335 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001336
John McCall3c3b7f92011-10-25 17:37:35 +00001337 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1338 Context.PseudoObjectTy,
1339 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001340 MemberLoc, BaseExpr.take()));
1341 }
1342 }
1343 // Use of id.member can only be for a property reference. Do not
1344 // use the 'id' redefinition in this case.
1345 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1346 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1347 ObjCImpDecl, HasTemplateArgs);
1348
1349 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1350 << MemberName << BaseType);
1351 }
1352
1353 // 'Class', unqualified only.
1354 if (OT->isObjCClass()) {
1355 // Only works in a method declaration (??!).
1356 ObjCMethodDecl *MD = getCurMethodDecl();
1357 if (!MD) {
1358 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1359 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1360 ObjCImpDecl, HasTemplateArgs);
1361
1362 goto fail;
1363 }
1364
1365 // Also must look for a getter name which uses property syntax.
1366 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1367 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1368 ObjCMethodDecl *Getter;
1369 if ((Getter = IFace->lookupClassMethod(Sel))) {
1370 // Check the use of this method.
1371 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1372 return ExprError();
1373 } else
1374 Getter = IFace->lookupPrivateMethod(Sel, false);
1375 // If we found a getter then this may be a valid dot-reference, we
1376 // will look for the matching setter, in case it is needed.
1377 Selector SetterSel =
1378 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1379 PP.getSelectorTable(), Member);
1380 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1381 if (!Setter) {
1382 // If this reference is in an @implementation, also check for 'private'
1383 // methods.
1384 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1385 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001386
1387 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1388 return ExprError();
1389
1390 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001391 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001392 Context.PseudoObjectTy,
1393 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001394 MemberLoc, BaseExpr.take()));
1395 }
1396
1397 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1398 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1399 ObjCImpDecl, HasTemplateArgs);
1400
1401 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1402 << MemberName << BaseType);
1403 }
1404
1405 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001406 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1407 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001408 SourceLocation(), QualType(), false);
1409 }
1410
1411 // Handle 'field access' to vectors, such as 'V.xx'.
1412 if (BaseType->isExtVectorType()) {
1413 // FIXME: this expr should store IsArrow.
1414 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1415 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1416 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1417 Member, MemberLoc);
1418 if (ret.isNull())
1419 return ExprError();
1420
1421 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1422 *Member, MemberLoc));
1423 }
1424
1425 // Adjust builtin-sel to the appropriate redefinition type if that's
1426 // not just a pointer to builtin-sel again.
1427 if (IsArrow &&
1428 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001429 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1430 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1431 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001432 CK_BitCast);
1433 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1434 ObjCImpDecl, HasTemplateArgs);
1435 }
1436
1437 // Failure cases.
1438 fail:
1439
1440 // Recover from dot accesses to pointers, e.g.:
1441 // type *foo;
1442 // foo.bar
1443 // This is actually well-formed in two cases:
1444 // - 'type' is an Objective C type
1445 // - 'bar' is a pseudo-destructor name which happens to refer to
1446 // the appropriate pointer type
1447 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1448 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1449 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1450 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1451 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1452 << FixItHint::CreateReplacement(OpLoc, "->");
1453
1454 // Recurse as an -> access.
1455 IsArrow = true;
1456 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1457 ObjCImpDecl, HasTemplateArgs);
1458 }
1459 }
1460
1461 // If the user is trying to apply -> or . to a function name, it's probably
1462 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001463 if (tryToRecoverWithCall(BaseExpr,
1464 PDiag(diag::err_member_reference_needs_call),
1465 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001466 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001467 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001468 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001469 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1470 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1471 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001472 }
1473
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +00001474 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +00001475 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001476
1477 return ExprError();
1478}
1479
1480/// The main callback when the parser finds something like
1481/// expression . [nested-name-specifier] identifier
1482/// expression -> [nested-name-specifier] identifier
1483/// where 'identifier' encompasses a fairly broad spectrum of
1484/// possibilities, including destructor and operator references.
1485///
1486/// \param OpKind either tok::arrow or tok::period
1487/// \param HasTrailingLParen whether the next token is '(', which
1488/// is used to diagnose mis-uses of special members that can
1489/// only be called
James Dennett699c9042012-06-15 07:13:21 +00001490/// \param ObjCImpDecl the current Objective-C \@implementation
1491/// decl; this is an ugly hack around the fact that Objective-C
1492/// \@implementations aren't properly put in the context chain
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001493ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1494 SourceLocation OpLoc,
1495 tok::TokenKind OpKind,
1496 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001497 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001498 UnqualifiedId &Id,
1499 Decl *ObjCImpDecl,
1500 bool HasTrailingLParen) {
1501 if (SS.isSet() && SS.isInvalid())
1502 return ExprError();
1503
1504 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001505 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001506 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1507 Diag(Id.getSourceRange().getBegin(),
1508 diag::ext_ms_explicit_constructor_call);
1509
1510 TemplateArgumentListInfo TemplateArgsBuffer;
1511
1512 // Decompose the name into its component parts.
1513 DeclarationNameInfo NameInfo;
1514 const TemplateArgumentListInfo *TemplateArgs;
1515 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1516 NameInfo, TemplateArgs);
1517
1518 DeclarationName Name = NameInfo.getName();
1519 bool IsArrow = (OpKind == tok::arrow);
1520
1521 NamedDecl *FirstQualifierInScope
1522 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1523 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1524
1525 // This is a postfix expression, so get rid of ParenListExprs.
1526 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1527 if (Result.isInvalid()) return ExprError();
1528 Base = Result.take();
1529
1530 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1531 isDependentScopeSpecifier(SS)) {
1532 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1533 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001534 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001535 NameInfo, TemplateArgs);
1536 } else {
1537 LookupResult R(*this, NameInfo, LookupMemberName);
1538 ExprResult BaseResult = Owned(Base);
1539 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1540 SS, ObjCImpDecl, TemplateArgs != 0);
1541 if (BaseResult.isInvalid())
1542 return ExprError();
1543 Base = BaseResult.take();
1544
1545 if (Result.isInvalid()) {
1546 Owned(Base);
1547 return ExprError();
1548 }
1549
1550 if (Result.get()) {
1551 // The only way a reference to a destructor can be used is to
1552 // immediately call it, which falls into this case. If the
1553 // next token is not a '(', produce a diagnostic and build the
1554 // call now.
1555 if (!HasTrailingLParen &&
1556 Id.getKind() == UnqualifiedId::IK_DestructorName)
1557 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1558
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001559 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001560 }
1561
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001562 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001563 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001564 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001565 FirstQualifierInScope, R, TemplateArgs,
1566 false, &ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001567 }
1568
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001569 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001570}
1571
1572static ExprResult
1573BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1574 const CXXScopeSpec &SS, FieldDecl *Field,
1575 DeclAccessPair FoundDecl,
1576 const DeclarationNameInfo &MemberNameInfo) {
1577 // x.a is an l-value if 'a' has a reference type. Otherwise:
1578 // x.a is an l-value/x-value/pr-value if the base is (and note
1579 // that *x is always an l-value), except that if the base isn't
1580 // an ordinary object then we must have an rvalue.
1581 ExprValueKind VK = VK_LValue;
1582 ExprObjectKind OK = OK_Ordinary;
1583 if (!IsArrow) {
1584 if (BaseExpr->getObjectKind() == OK_Ordinary)
1585 VK = BaseExpr->getValueKind();
1586 else
1587 VK = VK_RValue;
1588 }
1589 if (VK != VK_RValue && Field->isBitField())
1590 OK = OK_BitField;
1591
1592 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1593 QualType MemberType = Field->getType();
1594 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1595 MemberType = Ref->getPointeeType();
1596 VK = VK_LValue;
1597 } else {
1598 QualType BaseType = BaseExpr->getType();
1599 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1600
1601 Qualifiers BaseQuals = BaseType.getQualifiers();
1602
1603 // GC attributes are never picked up by members.
1604 BaseQuals.removeObjCGCAttr();
1605
1606 // CVR attributes from the base are picked up by members,
1607 // except that 'mutable' members don't pick up 'const'.
1608 if (Field->isMutable()) BaseQuals.removeConst();
1609
1610 Qualifiers MemberQuals
1611 = S.Context.getCanonicalType(MemberType).getQualifiers();
1612
1613 // TR 18037 does not allow fields to be declared with address spaces.
1614 assert(!MemberQuals.hasAddressSpace());
1615
1616 Qualifiers Combined = BaseQuals + MemberQuals;
1617 if (Combined != MemberQuals)
1618 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1619 }
1620
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001621 S.UnusedPrivateFields.remove(Field);
1622
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001623 ExprResult Base =
1624 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1625 FoundDecl, Field);
1626 if (Base.isInvalid())
1627 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001628 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001629 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001630 Field, FoundDecl, MemberNameInfo,
1631 MemberType, VK, OK));
1632}
1633
1634/// Builds an implicit member access expression. The current context
1635/// is known to be an instance method, and the given unqualified lookup
1636/// set is known to contain only instance members, at least one of which
1637/// is from an appropriate type.
1638ExprResult
1639Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001640 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001641 LookupResult &R,
1642 const TemplateArgumentListInfo *TemplateArgs,
1643 bool IsKnownInstance) {
1644 assert(!R.empty() && !R.isAmbiguous());
1645
1646 SourceLocation loc = R.getNameLoc();
1647
1648 // We may have found a field within an anonymous union or struct
1649 // (C++ [class.union]).
1650 // FIXME: template-ids inside anonymous structs?
1651 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1652 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1653
1654 // If this is known to be an instance access, go ahead and build an
1655 // implicit 'this' expression now.
1656 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001657 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001658 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1659
1660 Expr *baseExpr = 0; // null signifies implicit access
1661 if (IsKnownInstance) {
1662 SourceLocation Loc = R.getNameLoc();
1663 if (SS.getRange().isValid())
1664 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001665 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001666 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1667 }
1668
1669 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1670 /*OpLoc*/ SourceLocation(),
1671 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001672 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001673 /*FirstQualifierInScope*/ 0,
1674 R, TemplateArgs);
1675}