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