blob: c3642f56ce257ed4e646e0a7356d6db49cc90117 [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()) {
John McCall76da55d2013-04-16 07:28:30 +0000108 if (dyn_cast<FieldDecl>(D) || dyn_cast<MSPropertyDecl>(D)
109 || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000110 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000111
112 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
113 Classes.insert(R->getCanonicalDecl());
114 }
115 else
116 hasNonInstance = true;
117 }
118
119 // If we didn't find any instance members, it can't be an implicit
120 // member reference.
121 if (Classes.empty())
122 return IMA_Static;
123
Richard Smithd390de92012-02-25 10:20:59 +0000124 bool IsCXX11UnevaluatedField = false;
Richard Smith80ad52f2013-01-02 11:42:31 +0000125 if (SemaRef.getLangOpts().CPlusPlus11 && isField) {
Richard Smith2c8aee42012-02-25 10:04:07 +0000126 // C++11 [expr.prim.general]p12:
127 // An id-expression that denotes a non-static data member or non-static
128 // member function of a class can only be used:
129 // (...)
130 // - if that id-expression denotes a non-static data member and it
131 // appears in an unevaluated operand.
132 const Sema::ExpressionEvaluationContextRecord& record
133 = SemaRef.ExprEvalContexts.back();
134 if (record.Context == Sema::Unevaluated)
Richard Smithd390de92012-02-25 10:20:59 +0000135 IsCXX11UnevaluatedField = true;
Richard Smith2c8aee42012-02-25 10:04:07 +0000136 }
137
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000138 // If the current context is not an instance method, it can't be
139 // an implicit member reference.
140 if (isStaticContext) {
141 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000142 return IMA_Mixed_StaticContext;
143
Richard Smithd390de92012-02-25 10:20:59 +0000144 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
145 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000146 }
147
148 CXXRecordDecl *contextClass;
149 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
150 contextClass = MD->getParent()->getCanonicalDecl();
151 else
152 contextClass = cast<CXXRecordDecl>(DC);
153
154 // [class.mfct.non-static]p3:
155 // ...is used in the body of a non-static member function of class X,
156 // if name lookup (3.4.1) resolves the name in the id-expression to a
157 // non-static non-type member of some class C [...]
158 // ...if C is not X or a base class of X, the class member access expression
159 // is ill-formed.
160 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000161 contextClass->getCanonicalDecl() !=
Richard Smithf62c6902012-11-22 00:24:47 +0000162 R.getNamingClass()->getCanonicalDecl()) {
163 // If the naming class is not the current context, this was a qualified
164 // member name lookup, and it's sufficient to check that we have the naming
165 // class as a base class.
166 Classes.clear();
Richard Smith746619a2012-11-22 00:40:54 +0000167 Classes.insert(R.getNamingClass()->getCanonicalDecl());
Richard Smithf62c6902012-11-22 00:24:47 +0000168 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000169
170 // If we can prove that the current context is unrelated to all the
171 // declaring classes, it can't be an implicit member reference (in
172 // which case it's an error if any of those members are selected).
Richard Smithf62c6902012-11-22 00:24:47 +0000173 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smithd390de92012-02-25 10:20:59 +0000174 return hasNonInstance ? IMA_Mixed_Unrelated :
175 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
176 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000177
178 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
179}
180
181/// Diagnose a reference to a field with no object available.
Richard Smitha85cf392012-04-05 01:13:04 +0000182static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000183 const CXXScopeSpec &SS,
Richard Smitha85cf392012-04-05 01:13:04 +0000184 NamedDecl *Rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000185 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000186 SourceLocation Loc = nameInfo.getLoc();
187 SourceRange Range(Loc);
188 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman9bc291d2012-01-18 03:53:45 +0000189
Richard Smitha85cf392012-04-05 01:13:04 +0000190 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
191 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
192 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
193 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
194
195 bool InStaticMethod = Method && Method->isStatic();
196 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
197
198 if (IsField && InStaticMethod)
199 // "invalid use of member 'x' in static member function"
200 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
201 << Range << nameInfo.getName();
202 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
203 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
204 // Unqualified lookup in a non-static member function found a member of an
205 // enclosing class.
206 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
207 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
208 else if (IsField)
Eli Friedmanef331b72012-01-20 01:26:23 +0000209 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smitha85cf392012-04-05 01:13:04 +0000210 << nameInfo.getName() << Range;
211 else
212 SemaRef.Diag(Loc, diag::err_member_call_without_object)
213 << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000214}
215
216/// Builds an expression which might be an implicit member expression.
217ExprResult
218Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000219 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000220 LookupResult &R,
221 const TemplateArgumentListInfo *TemplateArgs) {
222 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
223 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000224 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000225
226 case IMA_Mixed:
227 case IMA_Mixed_Unrelated:
228 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000229 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000230
Richard Smithd390de92012-02-25 10:20:59 +0000231 case IMA_Field_Uneval_Context:
232 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
233 << R.getLookupNameInfo().getName();
234 // Fall through.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000235 case IMA_Static:
236 case IMA_Mixed_StaticContext:
237 case IMA_Unresolved_StaticContext:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000238 if (TemplateArgs || TemplateKWLoc.isValid())
239 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000240 return BuildDeclarationNameExpr(SS, R, false);
241
242 case IMA_Error_StaticContext:
243 case IMA_Error_Unrelated:
Richard Smitha85cf392012-04-05 01:13:04 +0000244 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000245 R.getLookupNameInfo());
246 return ExprError();
247 }
248
249 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000250}
251
252/// Check an ext-vector component access expression.
253///
254/// VK should be set in advance to the value kind of the base
255/// expression.
256static QualType
257CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
258 SourceLocation OpLoc, const IdentifierInfo *CompName,
259 SourceLocation CompLoc) {
260 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
261 // see FIXME there.
262 //
263 // FIXME: This logic can be greatly simplified by splitting it along
264 // halving/not halving and reworking the component checking.
265 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
266
267 // The vector accessor can't exceed the number of elements.
268 const char *compStr = CompName->getNameStart();
269
270 // This flag determines whether or not the component is one of the four
271 // special names that indicate a subset of exactly half the elements are
272 // to be selected.
273 bool HalvingSwizzle = false;
274
275 // This flag determines whether or not CompName has an 's' char prefix,
276 // indicating that it is a string of hex values to be used as vector indices.
277 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
278
279 bool HasRepeated = false;
280 bool HasIndex[16] = {};
281
282 int Idx;
283
284 // Check that we've found one of the special components, or that the component
285 // names must come from the same set.
286 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
287 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
288 HalvingSwizzle = true;
289 } else if (!HexSwizzle &&
290 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
291 do {
292 if (HasIndex[Idx]) HasRepeated = true;
293 HasIndex[Idx] = true;
294 compStr++;
295 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
296 } else {
297 if (HexSwizzle) compStr++;
298 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
299 if (HasIndex[Idx]) HasRepeated = true;
300 HasIndex[Idx] = true;
301 compStr++;
302 }
303 }
304
305 if (!HalvingSwizzle && *compStr) {
306 // We didn't get to the end of the string. This means the component names
307 // didn't come from the same set *or* we encountered an illegal name.
308 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000309 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000310 return QualType();
311 }
312
313 // Ensure no component accessor exceeds the width of the vector type it
314 // operates on.
315 if (!HalvingSwizzle) {
316 compStr = CompName->getNameStart();
317
318 if (HexSwizzle)
319 compStr++;
320
321 while (*compStr) {
322 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
323 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
324 << baseType << SourceRange(CompLoc);
325 return QualType();
326 }
327 }
328 }
329
330 // The component accessor looks fine - now we need to compute the actual type.
331 // The vector type is implied by the component accessor. For example,
332 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
333 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
334 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
335 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
336 : CompName->getLength();
337 if (HexSwizzle)
338 CompSize--;
339
340 if (CompSize == 1)
341 return vecType->getElementType();
342
343 if (HasRepeated) VK = VK_RValue;
344
345 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
346 // Now look up the TypeDefDecl from the vector type. Without this,
347 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000348 for (Sema::ExtVectorDeclsType::iterator
Axel Naumann0ec56b72012-10-18 19:05:02 +0000349 I = S.ExtVectorDecls.begin(S.getExternalSource()),
Douglas Gregord58a0a52011-07-28 00:39:29 +0000350 E = S.ExtVectorDecls.end();
351 I != E; ++I) {
352 if ((*I)->getUnderlyingType() == VT)
353 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000354 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000355
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000356 return VT; // should never get here (a typedef type should always be found).
357}
358
359static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
360 IdentifierInfo *Member,
361 const Selector &Sel,
362 ASTContext &Context) {
363 if (Member)
364 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
365 return PD;
366 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
367 return OMD;
368
369 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
370 E = PDecl->protocol_end(); I != E; ++I) {
371 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
372 Context))
373 return D;
374 }
375 return 0;
376}
377
378static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
379 IdentifierInfo *Member,
380 const Selector &Sel,
381 ASTContext &Context) {
382 // Check protocols on qualified interfaces.
383 Decl *GDecl = 0;
384 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
385 E = QIdTy->qual_end(); I != E; ++I) {
386 if (Member)
387 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
388 GDecl = PD;
389 break;
390 }
391 // Also must look for a getter or setter name which uses property syntax.
392 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
393 GDecl = OMD;
394 break;
395 }
396 }
397 if (!GDecl) {
398 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
399 E = QIdTy->qual_end(); I != E; ++I) {
400 // Search in the protocol-qualifier list of current protocol.
401 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
402 Context);
403 if (GDecl)
404 return GDecl;
405 }
406 }
407 return GDecl;
408}
409
410ExprResult
411Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
412 bool IsArrow, SourceLocation OpLoc,
413 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000414 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000415 NamedDecl *FirstQualifierInScope,
416 const DeclarationNameInfo &NameInfo,
417 const TemplateArgumentListInfo *TemplateArgs) {
418 // Even in dependent contexts, try to diagnose base expressions with
419 // obviously wrong types, e.g.:
420 //
421 // T* t;
422 // t.f;
423 //
424 // In Obj-C++, however, the above expression is valid, since it could be
425 // accessing the 'f' property if T is an Obj-C interface. The extra check
426 // allows this, while still reporting an error if T is a struct pointer.
427 if (!IsArrow) {
428 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikie4e4d0842012-03-11 07:00:24 +0000429 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000430 PT->getPointeeType()->isRecordType())) {
431 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +0000432 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +0000433 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000434 return ExprError();
435 }
436 }
437
438 assert(BaseType->isDependentType() ||
439 NameInfo.getName().isDependentName() ||
440 isDependentScopeSpecifier(SS));
441
442 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
443 // must have pointer type, and the accessed type is the pointee.
444 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
445 IsArrow, OpLoc,
446 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000447 TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000448 FirstQualifierInScope,
449 NameInfo, TemplateArgs));
450}
451
452/// We know that the given qualified member reference points only to
453/// declarations which do not belong to the static type of the base
454/// expression. Diagnose the problem.
455static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
456 Expr *BaseExpr,
457 QualType BaseType,
458 const CXXScopeSpec &SS,
459 NamedDecl *rep,
460 const DeclarationNameInfo &nameInfo) {
461 // If this is an implicit member access, use a different set of
462 // diagnostics.
463 if (!BaseExpr)
Richard Smitha85cf392012-04-05 01:13:04 +0000464 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000465
466 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
467 << SS.getRange() << rep << BaseType;
468}
469
470// Check whether the declarations we found through a nested-name
471// specifier in a member expression are actually members of the base
472// type. The restriction here is:
473//
474// C++ [expr.ref]p2:
475// ... In these cases, the id-expression shall name a
476// member of the class or of one of its base classes.
477//
478// So it's perfectly legitimate for the nested-name specifier to name
479// an unrelated class, and for us to find an overload set including
480// decls from classes which are not superclasses, as long as the decl
481// we actually pick through overload resolution is from a superclass.
482bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
483 QualType BaseType,
484 const CXXScopeSpec &SS,
485 const LookupResult &R) {
Richard Smithf62c6902012-11-22 00:24:47 +0000486 CXXRecordDecl *BaseRecord =
487 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
488 if (!BaseRecord) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000489 // We can't check this yet because the base type is still
490 // dependent.
491 assert(BaseType->isDependentType());
492 return false;
493 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000494
495 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
496 // If this is an implicit member reference and we find a
497 // non-instance member, it's not an error.
498 if (!BaseExpr && !(*I)->isCXXInstanceMember())
499 return false;
500
501 // Note that we use the DC of the decl, not the underlying decl.
502 DeclContext *DC = (*I)->getDeclContext();
503 while (DC->isTransparentContext())
504 DC = DC->getParent();
505
506 if (!DC->isRecord())
507 continue;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000508
Richard Smithf62c6902012-11-22 00:24:47 +0000509 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
510 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
511 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000512 return false;
513 }
514
515 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
516 R.getRepresentativeDecl(),
517 R.getLookupNameInfo());
518 return true;
519}
520
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000521namespace {
522
523// Callback to only accept typo corrections that are either a ValueDecl or a
524// FunctionTemplateDecl.
525class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
526 public:
527 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
528 NamedDecl *ND = candidate.getCorrectionDecl();
529 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
530 }
531};
532
533}
534
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000535static bool
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000536LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000537 SourceRange BaseRange, const RecordType *RTy,
538 SourceLocation OpLoc, CXXScopeSpec &SS,
539 bool HasTemplateArgs) {
540 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000541 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
542 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregord10099e2012-05-04 16:32:21 +0000543 diag::err_typecheck_incomplete_tag,
544 BaseRange))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000545 return true;
546
547 if (HasTemplateArgs) {
548 // LookupTemplateName doesn't expect these both to exist simultaneously.
549 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
550
551 bool MOUS;
552 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
553 return false;
554 }
555
556 DeclContext *DC = RDecl;
557 if (SS.isSet()) {
558 // If the member name was a qualified-id, look into the
559 // nested-name-specifier.
560 DC = SemaRef.computeDeclContext(SS, false);
561
562 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
563 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
564 << SS.getRange() << DC;
565 return true;
566 }
567
568 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
569
570 if (!isa<TypeDecl>(DC)) {
571 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
572 << DC << SS.getRange();
573 return true;
574 }
575 }
576
577 // The record definition is complete, now look up the member.
578 SemaRef.LookupQualifiedName(R, DC);
579
580 if (!R.empty())
581 return false;
582
583 // We didn't find anything with the given name, so try to correct
584 // for typos.
585 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000586 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000587 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
588 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000589 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000590 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000591 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000592 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000593 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000594 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000595 Corrected.getQuoted(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000596 R.setLookupName(Corrected.getCorrection());
597 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000598 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000599 << Name << DC << CorrectedQuotedStr << SS.getRange()
David Blaikie6952c012012-10-12 20:00:44 +0000600 << FixItHint::CreateReplacement(Corrected.getCorrectionRange(),
601 CorrectedStr);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000602 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
603 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000604 }
605
606 return false;
607}
608
609ExprResult
610Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
611 SourceLocation OpLoc, bool IsArrow,
612 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000613 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000614 NamedDecl *FirstQualifierInScope,
615 const DeclarationNameInfo &NameInfo,
616 const TemplateArgumentListInfo *TemplateArgs) {
617 if (BaseType->isDependentType() ||
618 (SS.isSet() && isDependentScopeSpecifier(SS)))
619 return ActOnDependentMemberExpr(Base, BaseType,
620 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000621 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000622 NameInfo, TemplateArgs);
623
624 LookupResult R(*this, NameInfo, LookupMemberName);
625
626 // Implicit member accesses.
627 if (!Base) {
628 QualType RecordTy = BaseType;
629 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
630 if (LookupMemberExprInRecord(*this, R, SourceRange(),
631 RecordTy->getAs<RecordType>(),
632 OpLoc, SS, TemplateArgs != 0))
633 return ExprError();
634
635 // Explicit member accesses.
636 } else {
637 ExprResult BaseResult = Owned(Base);
638 ExprResult Result =
639 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
640 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
641
642 if (BaseResult.isInvalid())
643 return ExprError();
644 Base = BaseResult.take();
645
646 if (Result.isInvalid()) {
647 Owned(Base);
648 return ExprError();
649 }
650
651 if (Result.get())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000652 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000653
654 // LookupMemberExpr can modify Base, and thus change BaseType
655 BaseType = Base->getType();
656 }
657
658 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000659 OpLoc, IsArrow, SS, TemplateKWLoc,
660 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000661}
662
663static ExprResult
664BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
665 const CXXScopeSpec &SS, FieldDecl *Field,
666 DeclAccessPair FoundDecl,
667 const DeclarationNameInfo &MemberNameInfo);
668
669ExprResult
670Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
671 SourceLocation loc,
672 IndirectFieldDecl *indirectField,
673 Expr *baseObjectExpr,
674 SourceLocation opLoc) {
675 // First, build the expression that refers to the base object.
676
677 bool baseObjectIsPointer = false;
678 Qualifiers baseQuals;
679
680 // Case 1: the base of the indirect field is not a field.
681 VarDecl *baseVariable = indirectField->getVarDecl();
682 CXXScopeSpec EmptySS;
683 if (baseVariable) {
684 assert(baseVariable->getType()->isRecordType());
685
686 // In principle we could have a member access expression that
687 // accesses an anonymous struct/union that's a static member of
688 // the base object's class. However, under the current standard,
689 // static data members cannot be anonymous structs or unions.
690 // Supporting this is as easy as building a MemberExpr here.
691 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
692
693 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
694
695 ExprResult result
696 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
697 if (result.isInvalid()) return ExprError();
698
699 baseObjectExpr = result.take();
700 baseObjectIsPointer = false;
701 baseQuals = baseObjectExpr->getType().getQualifiers();
702
703 // Case 2: the base of the indirect field is a field and the user
704 // wrote a member expression.
705 } else if (baseObjectExpr) {
706 // The caller provided the base object expression. Determine
707 // whether its a pointer and whether it adds any qualifiers to the
708 // anonymous struct/union fields we're looking into.
709 QualType objectType = baseObjectExpr->getType();
710
711 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
712 baseObjectIsPointer = true;
713 objectType = ptr->getPointeeType();
714 } else {
715 baseObjectIsPointer = false;
716 }
717 baseQuals = objectType.getQualifiers();
718
719 // Case 3: the base of the indirect field is a field and we should
720 // build an implicit member access.
721 } else {
722 // We've found a member of an anonymous struct/union that is
723 // inside a non-anonymous struct/union, so in a well-formed
724 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000725 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000726 if (ThisTy.isNull()) {
727 Diag(loc, diag::err_invalid_member_use_in_static_method)
728 << indirectField->getDeclName();
729 return ExprError();
730 }
731
732 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000733 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000734 baseObjectExpr
735 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
736 baseObjectIsPointer = true;
737 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
738 }
739
740 // Build the implicit member references to the field of the
741 // anonymous struct/union.
742 Expr *result = baseObjectExpr;
743 IndirectFieldDecl::chain_iterator
744 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
745
746 // Build the first member access in the chain with full information.
747 if (!baseVariable) {
748 FieldDecl *field = cast<FieldDecl>(*FI);
749
750 // FIXME: use the real found-decl info!
751 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
752
753 // Make a nameInfo that properly uses the anonymous name.
754 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
755
756 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
757 EmptySS, field, foundDecl,
758 memberNameInfo).take();
759 baseObjectIsPointer = false;
760
761 // FIXME: check qualified member access
762 }
763
764 // In all cases, we should now skip the first declaration in the chain.
765 ++FI;
766
767 while (FI != FEnd) {
768 FieldDecl *field = cast<FieldDecl>(*FI++);
769
770 // FIXME: these are somewhat meaningless
771 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
772 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
773
774 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
775 (FI == FEnd? SS : EmptySS), field,
776 foundDecl, memberNameInfo).take();
777 }
778
779 return Owned(result);
780}
781
John McCall76da55d2013-04-16 07:28:30 +0000782static ExprResult
783BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
784 const CXXScopeSpec &SS,
785 MSPropertyDecl *PD,
786 const DeclarationNameInfo &NameInfo) {
787 // Property names are always simple identifiers and therefore never
788 // require any interesting additional storage.
789 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
790 S.Context.PseudoObjectTy, VK_LValue,
791 SS.getWithLocInContext(S.Context),
792 NameInfo.getLoc());
793}
794
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000795/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000796static MemberExpr *BuildMemberExpr(Sema &SemaRef,
797 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000798 const CXXScopeSpec &SS,
799 SourceLocation TemplateKWLoc,
800 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000801 DeclAccessPair FoundDecl,
802 const DeclarationNameInfo &MemberNameInfo,
803 QualType Ty,
804 ExprValueKind VK, ExprObjectKind OK,
805 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000806 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000807 MemberExpr *E =
808 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
809 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
810 TemplateArgs, Ty, VK, OK);
811 SemaRef.MarkMemberReferenced(E);
812 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000813}
814
815ExprResult
816Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
817 SourceLocation OpLoc, bool IsArrow,
818 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000819 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000820 NamedDecl *FirstQualifierInScope,
821 LookupResult &R,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000822 const TemplateArgumentListInfo *TemplateArgs,
823 bool SuppressQualifierCheck,
824 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000825 QualType BaseType = BaseExprType;
826 if (IsArrow) {
827 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000828 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000829 }
830 R.setBaseObjectType(BaseType);
831
832 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
833 DeclarationName MemberName = MemberNameInfo.getName();
834 SourceLocation MemberLoc = MemberNameInfo.getLoc();
835
836 if (R.isAmbiguous())
837 return ExprError();
838
839 if (R.empty()) {
840 // Rederive where we looked up.
841 DeclContext *DC = (SS.isSet()
842 ? computeDeclContext(SS, false)
843 : BaseType->getAs<RecordType>()->getDecl());
844
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000845 if (ExtraArgs) {
846 ExprResult RetryExpr;
847 if (!IsArrow && BaseExpr) {
Kaelyn Uhrain111263c2012-05-01 01:17:53 +0000848 SFINAETrap Trap(*this, true);
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000849 ParsedType ObjectType;
850 bool MayBePseudoDestructor = false;
851 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
852 OpLoc, tok::arrow, ObjectType,
853 MayBePseudoDestructor);
854 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
855 CXXScopeSpec TempSS(SS);
856 RetryExpr = ActOnMemberAccessExpr(
857 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
858 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
859 ExtraArgs->HasTrailingLParen);
860 }
861 if (Trap.hasErrorOccurred())
862 RetryExpr = ExprError();
863 }
864 if (RetryExpr.isUsable()) {
865 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
866 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
867 return RetryExpr;
868 }
869 }
870
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000871 Diag(R.getNameLoc(), diag::err_no_member)
872 << MemberName << DC
873 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
874 return ExprError();
875 }
876
877 // Diagnose lookups that find only declarations from a non-base
878 // type. This is possible for either qualified lookups (which may
879 // have been qualified with an unrelated type) or implicit member
880 // expressions (which were found with unqualified lookup and thus
881 // may have come from an enclosing scope). Note that it's okay for
882 // lookup to find declarations from a non-base type as long as those
883 // aren't the ones picked by overload resolution.
884 if ((SS.isSet() || !BaseExpr ||
885 (isa<CXXThisExpr>(BaseExpr) &&
886 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
887 !SuppressQualifierCheck &&
888 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
889 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000890
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000891 // Construct an unresolved result if we in fact got an unresolved
892 // result.
893 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
894 // Suppress any lookup-related diagnostics; we'll do these when we
895 // pick a member.
896 R.suppressDiagnostics();
897
898 UnresolvedMemberExpr *MemExpr
899 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
900 BaseExpr, BaseExprType,
901 IsArrow, OpLoc,
902 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000903 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000904 TemplateArgs, R.begin(), R.end());
905
906 return Owned(MemExpr);
907 }
908
909 assert(R.isSingleResult());
910 DeclAccessPair FoundDecl = R.begin().getPair();
911 NamedDecl *MemberDecl = R.getFoundDecl();
912
913 // FIXME: diagnose the presence of template arguments now.
914
915 // If the decl being referenced had an error, return an error for this
916 // sub-expr without emitting another error, in order to avoid cascading
917 // error cases.
918 if (MemberDecl->isInvalidDecl())
919 return ExprError();
920
921 // Handle the implicit-member-access case.
922 if (!BaseExpr) {
923 // If this is not an instance member, convert to a non-member access.
924 if (!MemberDecl->isCXXInstanceMember())
925 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
926
927 SourceLocation Loc = R.getNameLoc();
928 if (SS.getRange().isValid())
929 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000930 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000931 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
932 }
933
934 bool ShouldCheckUse = true;
935 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
936 // Don't diagnose the use of a virtual member function unless it's
937 // explicitly qualified.
938 if (MD->isVirtual() && !SS.isSet())
939 ShouldCheckUse = false;
940 }
941
942 // Check the use of this member.
943 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
944 Owned(BaseExpr);
945 return ExprError();
946 }
947
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000948 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
949 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
950 SS, FD, FoundDecl, MemberNameInfo);
951
John McCall76da55d2013-04-16 07:28:30 +0000952 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
953 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
954 MemberNameInfo);
955
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000956 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
957 // We may have found a field within an anonymous union or struct
958 // (C++ [class.union]).
959 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
960 BaseExpr, OpLoc);
961
962 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000963 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
964 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000965 Var->getType().getNonReferenceType(),
966 VK_LValue, OK_Ordinary));
967 }
968
969 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
970 ExprValueKind valueKind;
971 QualType type;
972 if (MemberFn->isInstance()) {
973 valueKind = VK_RValue;
974 type = Context.BoundMemberTy;
975 } else {
976 valueKind = VK_LValue;
977 type = MemberFn->getType();
978 }
979
Eli Friedman5f2987c2012-02-02 03:46:19 +0000980 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
981 TemplateKWLoc, MemberFn, FoundDecl,
982 MemberNameInfo, type, valueKind,
983 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000984 }
985 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
986
987 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000988 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
989 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000990 Enum->getType(), VK_RValue, OK_Ordinary));
991 }
992
993 Owned(BaseExpr);
994
995 // We found something that we didn't expect. Complain.
996 if (isa<TypeDecl>(MemberDecl))
997 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
998 << MemberName << BaseType << int(IsArrow);
999 else
1000 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1001 << MemberName << BaseType << int(IsArrow);
1002
1003 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1004 << MemberName;
1005 R.suppressDiagnostics();
1006 return ExprError();
1007}
1008
1009/// Given that normal member access failed on the given expression,
1010/// and given that the expression's type involves builtin-id or
1011/// builtin-Class, decide whether substituting in the redefinition
1012/// types would be profitable. The redefinition type is whatever
1013/// this translation unit tried to typedef to id/Class; we store
1014/// it to the side and then re-use it in places like this.
1015static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1016 const ObjCObjectPointerType *opty
1017 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1018 if (!opty) return false;
1019
1020 const ObjCObjectType *ty = opty->getObjectType();
1021
1022 QualType redef;
1023 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001024 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001025 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001026 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001027 } else {
1028 return false;
1029 }
1030
1031 // Do the substitution as long as the redefinition type isn't just a
1032 // possibly-qualified pointer to builtin-id or builtin-Class again.
1033 opty = redef->getAs<ObjCObjectPointerType>();
Richard Trieu47fcbba2012-10-12 17:48:40 +00001034 if (opty && !opty->getObjectType()->getInterface())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001035 return false;
1036
1037 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1038 return true;
1039}
1040
John McCall6dbba4f2011-10-11 23:14:30 +00001041static bool isRecordType(QualType T) {
1042 return T->isRecordType();
1043}
1044static bool isPointerToRecordType(QualType T) {
1045 if (const PointerType *PT = T->getAs<PointerType>())
1046 return PT->getPointeeType()->isRecordType();
1047 return false;
1048}
1049
Richard Smith9138b4e2011-10-26 19:06:56 +00001050/// Perform conversions on the LHS of a member access expression.
1051ExprResult
1052Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001053 if (IsArrow && !Base->getType()->isFunctionType())
1054 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001055
Eli Friedman059d5782012-01-13 02:20:01 +00001056 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001057}
1058
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001059/// Look up the given member of the given non-type-dependent
1060/// expression. This can return in one of two ways:
1061/// * If it returns a sentinel null-but-valid result, the caller will
1062/// assume that lookup was performed and the results written into
1063/// the provided structure. It will take over from there.
1064/// * Otherwise, the returned expression will be produced in place of
1065/// an ordinary member expression.
1066///
1067/// The ObjCImpDecl bit is a gross hack that will need to be properly
1068/// fixed for ObjC++.
1069ExprResult
1070Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1071 bool &IsArrow, SourceLocation OpLoc,
1072 CXXScopeSpec &SS,
1073 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1074 assert(BaseExpr.get() && "no base expression");
1075
1076 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001077 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001078 if (BaseExpr.isInvalid())
1079 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001080
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001081 QualType BaseType = BaseExpr.get()->getType();
1082 assert(!BaseType->isDependentType());
1083
1084 DeclarationName MemberName = R.getLookupName();
1085 SourceLocation MemberLoc = R.getNameLoc();
1086
1087 // For later type-checking purposes, turn arrow accesses into dot
1088 // accesses. The only access type we support that doesn't follow
1089 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1090 // and those never use arrows, so this is unaffected.
1091 if (IsArrow) {
1092 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1093 BaseType = Ptr->getPointeeType();
1094 else if (const ObjCObjectPointerType *Ptr
1095 = BaseType->getAs<ObjCObjectPointerType>())
1096 BaseType = Ptr->getPointeeType();
1097 else if (BaseType->isRecordType()) {
1098 // Recover from arrow accesses to records, e.g.:
1099 // struct MyRecord foo;
1100 // foo->bar
1101 // This is actually well-formed in C++ if MyRecord has an
1102 // overloaded operator->, but that should have been dealt with
1103 // by now.
1104 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1105 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1106 << FixItHint::CreateReplacement(OpLoc, ".");
1107 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001108 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001109 goto fail;
1110 } else {
1111 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1112 << BaseType << BaseExpr.get()->getSourceRange();
1113 return ExprError();
1114 }
1115 }
1116
1117 // Handle field access to simple records.
1118 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1119 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1120 RTy, OpLoc, SS, HasTemplateArgs))
1121 return ExprError();
1122
1123 // Returning valid-but-null is how we indicate to the caller that
1124 // the lookup result was filled in.
1125 return Owned((Expr*) 0);
1126 }
1127
1128 // Handle ivar access to Objective-C objects.
1129 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001130 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001131 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1132 << 1 << SS.getScopeRep()
1133 << FixItHint::CreateRemoval(SS.getRange());
1134 SS.clear();
1135 }
1136
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001137 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1138
1139 // There are three cases for the base type:
1140 // - builtin id (qualified or unqualified)
1141 // - builtin Class (qualified or unqualified)
1142 // - an interface
1143 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1144 if (!IDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001145 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001146 (OTy->isObjCId() || OTy->isObjCClass()))
1147 goto fail;
1148 // There's an implicit 'isa' ivar on all objects.
1149 // But we only actually find it this way on objects of type 'id',
Eric Christopher2502ec82012-08-16 23:50:37 +00001150 // apparently.
Fariborz Jahanian7e352742013-03-27 21:19:25 +00001151 if (OTy->isObjCId() && Member->isStr("isa"))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001152 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
Fariborz Jahanianec8deba2013-03-28 19:50:55 +00001153 OpLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001154 Context.getObjCClassType()));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001155 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1156 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1157 ObjCImpDecl, HasTemplateArgs);
1158 goto fail;
1159 }
Fariborz Jahanian09100592012-06-21 21:35:15 +00001160
Douglas Gregord10099e2012-05-04 16:32:21 +00001161 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1162 BaseExpr.get()))
Douglas Gregord07cc362012-01-02 17:18:37 +00001163 return ExprError();
1164
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001165 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001166 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1167
1168 if (!IV) {
1169 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001170 DeclFilterCCC<ObjCIvarDecl> Validator;
1171 Validator.IsObjCIvarLookup = IsArrow;
1172 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1173 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001174 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001175 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001176 Diag(R.getNameLoc(),
1177 diag::err_typecheck_member_reference_ivar_suggest)
1178 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1179 << FixItHint::CreateReplacement(R.getNameLoc(),
1180 IV->getNameAsString());
1181 Diag(IV->getLocation(), diag::note_previous_decl)
1182 << IV->getDeclName();
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001183
1184 // Figure out the class that declares the ivar.
1185 assert(!ClassDeclared);
1186 Decl *D = cast<Decl>(IV->getDeclContext());
1187 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1188 D = CAT->getClassInterface();
1189 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001190 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001191 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1192 Diag(MemberLoc,
1193 diag::err_property_found_suggest)
1194 << Member << BaseExpr.get()->getType()
1195 << FixItHint::CreateReplacement(OpLoc, ".");
1196 return ExprError();
1197 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001198
1199 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1200 << IDecl->getDeclName() << MemberName
1201 << BaseExpr.get()->getSourceRange();
1202 return ExprError();
1203 }
1204 }
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001205
1206 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001207
1208 // If the decl being referenced had an error, return an error for this
1209 // sub-expr without emitting another error, in order to avoid cascading
1210 // error cases.
1211 if (IV->isInvalidDecl())
1212 return ExprError();
1213
1214 // Check whether we can reference this field.
1215 if (DiagnoseUseOfDecl(IV, MemberLoc))
1216 return ExprError();
1217 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1218 IV->getAccessControl() != ObjCIvarDecl::Package) {
1219 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1220 if (ObjCMethodDecl *MD = getCurMethodDecl())
1221 ClassOfMethodDecl = MD->getClassInterface();
1222 else if (ObjCImpDecl && getCurFunctionDecl()) {
1223 // Case of a c-function declared inside an objc implementation.
1224 // FIXME: For a c-style function nested inside an objc implementation
1225 // class, there is no implementation context available, so we pass
1226 // down the context as argument to this routine. Ideally, this context
1227 // need be passed down in the AST node and somehow calculated from the
1228 // AST for a function decl.
1229 if (ObjCImplementationDecl *IMPD =
1230 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1231 ClassOfMethodDecl = IMPD->getClassInterface();
1232 else if (ObjCCategoryImplDecl* CatImplClass =
1233 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1234 ClassOfMethodDecl = CatImplClass->getClassInterface();
1235 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001236 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001237 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1238 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1239 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1240 Diag(MemberLoc, diag::error_private_ivar_access)
1241 << IV->getDeclName();
1242 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1243 // @protected
1244 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001245 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001246 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001247 }
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001248 bool warn = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00001249 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001250 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1251 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1252 if (UO->getOpcode() == UO_Deref)
1253 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1254
1255 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001256 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001257 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001258 warn = false;
1259 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001260 }
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001261 if (warn) {
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001262 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1263 ObjCMethodFamily MF = MD->getMethodFamily();
1264 warn = (MF != OMF_init && MF != OMF_dealloc &&
Fariborz Jahanian26202292013-02-14 19:07:19 +00001265 MF != OMF_finalize &&
1266 !IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001267 }
1268 if (warn)
1269 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1270 }
Jordan Rose7a270482012-09-28 22:21:35 +00001271
1272 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
Fariborz Jahanian0c701812013-04-02 18:57:54 +00001273 MemberLoc, OpLoc,
Jordan Rose7a270482012-09-28 22:21:35 +00001274 BaseExpr.take(),
1275 IsArrow);
1276
1277 if (getLangOpts().ObjCAutoRefCount) {
1278 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1279 DiagnosticsEngine::Level Level =
1280 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1281 MemberLoc);
1282 if (Level != DiagnosticsEngine::Ignored)
1283 getCurFunction()->recordUseOfWeak(Result);
1284 }
1285 }
1286
1287 return Owned(Result);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001288 }
1289
1290 // Objective-C property access.
1291 const ObjCObjectPointerType *OPT;
1292 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001293 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001294 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1295 << 0 << SS.getScopeRep()
1296 << FixItHint::CreateRemoval(SS.getRange());
1297 SS.clear();
1298 }
1299
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001300 // This actually uses the base as an r-value.
1301 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1302 if (BaseExpr.isInvalid())
1303 return ExprError();
1304
1305 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1306
1307 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1308
1309 const ObjCObjectType *OT = OPT->getObjectType();
1310
1311 // id, with and without qualifiers.
1312 if (OT->isObjCId()) {
1313 // Check protocols on qualified interfaces.
1314 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1315 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1316 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1317 // Check the use of this declaration
1318 if (DiagnoseUseOfDecl(PD, MemberLoc))
1319 return ExprError();
1320
John McCall3c3b7f92011-10-25 17:37:35 +00001321 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1322 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001323 VK_LValue,
1324 OK_ObjCProperty,
1325 MemberLoc,
1326 BaseExpr.take()));
1327 }
1328
1329 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1330 // Check the use of this method.
1331 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1332 return ExprError();
1333 Selector SetterSel =
1334 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1335 PP.getSelectorTable(), Member);
1336 ObjCMethodDecl *SMD = 0;
1337 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1338 SetterSel, Context))
1339 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001340
John McCall3c3b7f92011-10-25 17:37:35 +00001341 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1342 Context.PseudoObjectTy,
1343 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001344 MemberLoc, BaseExpr.take()));
1345 }
1346 }
1347 // Use of id.member can only be for a property reference. Do not
1348 // use the 'id' redefinition in this case.
1349 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1350 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1351 ObjCImpDecl, HasTemplateArgs);
1352
1353 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1354 << MemberName << BaseType);
1355 }
1356
1357 // 'Class', unqualified only.
1358 if (OT->isObjCClass()) {
1359 // Only works in a method declaration (??!).
1360 ObjCMethodDecl *MD = getCurMethodDecl();
1361 if (!MD) {
1362 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1363 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1364 ObjCImpDecl, HasTemplateArgs);
1365
1366 goto fail;
1367 }
1368
1369 // Also must look for a getter name which uses property syntax.
1370 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1371 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1372 ObjCMethodDecl *Getter;
1373 if ((Getter = IFace->lookupClassMethod(Sel))) {
1374 // Check the use of this method.
1375 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1376 return ExprError();
1377 } else
1378 Getter = IFace->lookupPrivateMethod(Sel, false);
1379 // If we found a getter then this may be a valid dot-reference, we
1380 // will look for the matching setter, in case it is needed.
1381 Selector SetterSel =
1382 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1383 PP.getSelectorTable(), Member);
1384 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1385 if (!Setter) {
1386 // If this reference is in an @implementation, also check for 'private'
1387 // methods.
1388 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1389 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001390
1391 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1392 return ExprError();
1393
1394 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001395 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001396 Context.PseudoObjectTy,
1397 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001398 MemberLoc, BaseExpr.take()));
1399 }
1400
1401 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1402 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1403 ObjCImpDecl, HasTemplateArgs);
1404
1405 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1406 << MemberName << BaseType);
1407 }
1408
1409 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001410 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1411 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001412 SourceLocation(), QualType(), false);
1413 }
1414
1415 // Handle 'field access' to vectors, such as 'V.xx'.
1416 if (BaseType->isExtVectorType()) {
1417 // FIXME: this expr should store IsArrow.
1418 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1419 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1420 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1421 Member, MemberLoc);
1422 if (ret.isNull())
1423 return ExprError();
1424
1425 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1426 *Member, MemberLoc));
1427 }
1428
1429 // Adjust builtin-sel to the appropriate redefinition type if that's
1430 // not just a pointer to builtin-sel again.
1431 if (IsArrow &&
1432 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001433 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1434 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1435 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001436 CK_BitCast);
1437 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1438 ObjCImpDecl, HasTemplateArgs);
1439 }
1440
1441 // Failure cases.
1442 fail:
1443
1444 // Recover from dot accesses to pointers, e.g.:
1445 // type *foo;
1446 // foo.bar
1447 // This is actually well-formed in two cases:
1448 // - 'type' is an Objective C type
1449 // - 'bar' is a pseudo-destructor name which happens to refer to
1450 // the appropriate pointer type
1451 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1452 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1453 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1454 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1455 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1456 << FixItHint::CreateReplacement(OpLoc, "->");
1457
1458 // Recurse as an -> access.
1459 IsArrow = true;
1460 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1461 ObjCImpDecl, HasTemplateArgs);
1462 }
1463 }
1464
1465 // If the user is trying to apply -> or . to a function name, it's probably
1466 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001467 if (tryToRecoverWithCall(BaseExpr,
1468 PDiag(diag::err_member_reference_needs_call),
1469 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001470 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001471 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001472 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001473 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1474 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1475 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001476 }
1477
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +00001478 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +00001479 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001480
1481 return ExprError();
1482}
1483
1484/// The main callback when the parser finds something like
1485/// expression . [nested-name-specifier] identifier
1486/// expression -> [nested-name-specifier] identifier
1487/// where 'identifier' encompasses a fairly broad spectrum of
1488/// possibilities, including destructor and operator references.
1489///
1490/// \param OpKind either tok::arrow or tok::period
1491/// \param HasTrailingLParen whether the next token is '(', which
1492/// is used to diagnose mis-uses of special members that can
1493/// only be called
James Dennett699c9042012-06-15 07:13:21 +00001494/// \param ObjCImpDecl the current Objective-C \@implementation
1495/// decl; this is an ugly hack around the fact that Objective-C
1496/// \@implementations aren't properly put in the context chain
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001497ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1498 SourceLocation OpLoc,
1499 tok::TokenKind OpKind,
1500 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001501 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001502 UnqualifiedId &Id,
1503 Decl *ObjCImpDecl,
1504 bool HasTrailingLParen) {
1505 if (SS.isSet() && SS.isInvalid())
1506 return ExprError();
1507
1508 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001509 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001510 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1511 Diag(Id.getSourceRange().getBegin(),
1512 diag::ext_ms_explicit_constructor_call);
1513
1514 TemplateArgumentListInfo TemplateArgsBuffer;
1515
1516 // Decompose the name into its component parts.
1517 DeclarationNameInfo NameInfo;
1518 const TemplateArgumentListInfo *TemplateArgs;
1519 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1520 NameInfo, TemplateArgs);
1521
1522 DeclarationName Name = NameInfo.getName();
1523 bool IsArrow = (OpKind == tok::arrow);
1524
1525 NamedDecl *FirstQualifierInScope
1526 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1527 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1528
1529 // This is a postfix expression, so get rid of ParenListExprs.
1530 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1531 if (Result.isInvalid()) return ExprError();
1532 Base = Result.take();
1533
1534 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1535 isDependentScopeSpecifier(SS)) {
1536 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1537 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001538 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001539 NameInfo, TemplateArgs);
1540 } else {
1541 LookupResult R(*this, NameInfo, LookupMemberName);
1542 ExprResult BaseResult = Owned(Base);
1543 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1544 SS, ObjCImpDecl, TemplateArgs != 0);
1545 if (BaseResult.isInvalid())
1546 return ExprError();
1547 Base = BaseResult.take();
1548
1549 if (Result.isInvalid()) {
1550 Owned(Base);
1551 return ExprError();
1552 }
1553
1554 if (Result.get()) {
1555 // The only way a reference to a destructor can be used is to
1556 // immediately call it, which falls into this case. If the
1557 // next token is not a '(', produce a diagnostic and build the
1558 // call now.
1559 if (!HasTrailingLParen &&
1560 Id.getKind() == UnqualifiedId::IK_DestructorName)
1561 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1562
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001563 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001564 }
1565
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001566 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001567 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001568 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001569 FirstQualifierInScope, R, TemplateArgs,
1570 false, &ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001571 }
1572
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001573 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001574}
1575
1576static ExprResult
1577BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1578 const CXXScopeSpec &SS, FieldDecl *Field,
1579 DeclAccessPair FoundDecl,
1580 const DeclarationNameInfo &MemberNameInfo) {
1581 // x.a is an l-value if 'a' has a reference type. Otherwise:
1582 // x.a is an l-value/x-value/pr-value if the base is (and note
1583 // that *x is always an l-value), except that if the base isn't
1584 // an ordinary object then we must have an rvalue.
1585 ExprValueKind VK = VK_LValue;
1586 ExprObjectKind OK = OK_Ordinary;
1587 if (!IsArrow) {
1588 if (BaseExpr->getObjectKind() == OK_Ordinary)
1589 VK = BaseExpr->getValueKind();
1590 else
1591 VK = VK_RValue;
1592 }
1593 if (VK != VK_RValue && Field->isBitField())
1594 OK = OK_BitField;
1595
1596 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1597 QualType MemberType = Field->getType();
1598 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1599 MemberType = Ref->getPointeeType();
1600 VK = VK_LValue;
1601 } else {
1602 QualType BaseType = BaseExpr->getType();
1603 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001604
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001605 Qualifiers BaseQuals = BaseType.getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001606
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001607 // GC attributes are never picked up by members.
1608 BaseQuals.removeObjCGCAttr();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001609
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001610 // CVR attributes from the base are picked up by members,
1611 // except that 'mutable' members don't pick up 'const'.
1612 if (Field->isMutable()) BaseQuals.removeConst();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001613
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001614 Qualifiers MemberQuals
1615 = S.Context.getCanonicalType(MemberType).getQualifiers();
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001616
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001617 assert(!MemberQuals.hasAddressSpace());
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001618
1619
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001620 Qualifiers Combined = BaseQuals + MemberQuals;
1621 if (Combined != MemberQuals)
1622 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1623 }
Matt Arsenault34b0adb2013-02-26 21:16:00 +00001624
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001625 S.UnusedPrivateFields.remove(Field);
1626
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001627 ExprResult Base =
1628 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1629 FoundDecl, Field);
1630 if (Base.isInvalid())
1631 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001632 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001633 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001634 Field, FoundDecl, MemberNameInfo,
1635 MemberType, VK, OK));
1636}
1637
1638/// Builds an implicit member access expression. The current context
1639/// is known to be an instance method, and the given unqualified lookup
1640/// set is known to contain only instance members, at least one of which
1641/// is from an appropriate type.
1642ExprResult
1643Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001644 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001645 LookupResult &R,
1646 const TemplateArgumentListInfo *TemplateArgs,
1647 bool IsKnownInstance) {
1648 assert(!R.empty() && !R.isAmbiguous());
1649
1650 SourceLocation loc = R.getNameLoc();
1651
1652 // We may have found a field within an anonymous union or struct
1653 // (C++ [class.union]).
1654 // FIXME: template-ids inside anonymous structs?
1655 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1656 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1657
1658 // If this is known to be an instance access, go ahead and build an
1659 // implicit 'this' expression now.
1660 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001661 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001662 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1663
1664 Expr *baseExpr = 0; // null signifies implicit access
1665 if (IsKnownInstance) {
1666 SourceLocation Loc = R.getNameLoc();
1667 if (SS.getRange().isValid())
1668 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001669 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001670 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1671 }
1672
1673 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1674 /*OpLoc*/ SourceLocation(),
1675 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001676 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001677 /*FirstQualifierInScope*/ 0,
1678 R, TemplateArgs);
1679}