blob: ff580697e6dacbb58bae414d70d9079ea8eb24e5 [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"
14#include "clang/Sema/Lookup.h"
15#include "clang/Sema/Scope.h"
Jordan Rose7a270482012-09-28 22:21:35 +000016#include "clang/Sema/ScopeInfo.h"
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000017#include "clang/AST/DeclCXX.h"
18#include "clang/AST/DeclObjC.h"
19#include "clang/AST/DeclTemplate.h"
20#include "clang/AST/ExprCXX.h"
21#include "clang/AST/ExprObjC.h"
22#include "clang/Lex/Preprocessor.h"
23
24using namespace clang;
25using namespace sema;
26
27/// Determines if the given class is provably not derived from all of
28/// the prospective base classes.
29static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
30 CXXRecordDecl *Record,
31 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
32 if (Bases.count(Record->getCanonicalDecl()))
33 return false;
34
35 RecordDecl *RD = Record->getDefinition();
36 if (!RD) return false;
37 Record = cast<CXXRecordDecl>(RD);
38
39 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
40 E = Record->bases_end(); I != E; ++I) {
41 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
42 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
43 if (!BaseRT) return false;
44
45 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
46 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
47 return false;
48 }
49
50 return true;
51}
52
53enum IMAKind {
54 /// The reference is definitely not an instance member access.
55 IMA_Static,
56
57 /// The reference may be an implicit instance member access.
58 IMA_Mixed,
59
Eli Friedman9bc291d2012-01-18 03:53:45 +000060 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000061 /// so, because the context is not an instance method.
62 IMA_Mixed_StaticContext,
63
64 /// The reference may be to an instance member, but it is invalid if
65 /// so, because the context is from an unrelated class.
66 IMA_Mixed_Unrelated,
67
68 /// The reference is definitely an implicit instance member access.
69 IMA_Instance,
70
71 /// The reference may be to an unresolved using declaration.
72 IMA_Unresolved,
73
74 /// The reference may be to an unresolved using declaration and the
75 /// context is not an instance method.
76 IMA_Unresolved_StaticContext,
77
Eli Friedmanef331b72012-01-20 01:26:23 +000078 // The reference refers to a field which is not a member of the containing
79 // class, which is allowed because we're in C++11 mode and the context is
80 // unevaluated.
81 IMA_Field_Uneval_Context,
Eli Friedman9bc291d2012-01-18 03:53:45 +000082
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000083 /// All possible referrents are instance members and the current
84 /// context is not an instance method.
85 IMA_Error_StaticContext,
86
87 /// All possible referrents are instance members of an unrelated
88 /// class.
89 IMA_Error_Unrelated
90};
91
92/// The given lookup names class member(s) and is not being used for
93/// an address-of-member expression. Classify the type of access
94/// according to whether it's possible that this reference names an
Eli Friedman9bc291d2012-01-18 03:53:45 +000095/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000096/// conservatively answer "yes", in which case some errors will simply
97/// not be caught until template-instantiation.
98static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
99 Scope *CurScope,
100 const LookupResult &R) {
101 assert(!R.empty() && (*R.begin())->isCXXClassMember());
102
103 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
104
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000105 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
106 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000107
108 if (R.isUnresolvableResult())
109 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
110
111 // Collect all the declaring classes of instance members we find.
112 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000113 bool isField = false;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000114 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
115 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
116 NamedDecl *D = *I;
117
118 if (D->isCXXInstanceMember()) {
Aaron Ballman1dfc4ba2012-06-01 00:02:08 +0000119 if (dyn_cast<FieldDecl>(D) || dyn_cast<IndirectFieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000120 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000121
122 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
123 Classes.insert(R->getCanonicalDecl());
124 }
125 else
126 hasNonInstance = true;
127 }
128
129 // If we didn't find any instance members, it can't be an implicit
130 // member reference.
131 if (Classes.empty())
132 return IMA_Static;
133
Richard Smithd390de92012-02-25 10:20:59 +0000134 bool IsCXX11UnevaluatedField = false;
David Blaikie4e4d0842012-03-11 07:00:24 +0000135 if (SemaRef.getLangOpts().CPlusPlus0x && isField) {
Richard Smith2c8aee42012-02-25 10:04:07 +0000136 // C++11 [expr.prim.general]p12:
137 // An id-expression that denotes a non-static data member or non-static
138 // member function of a class can only be used:
139 // (...)
140 // - if that id-expression denotes a non-static data member and it
141 // appears in an unevaluated operand.
142 const Sema::ExpressionEvaluationContextRecord& record
143 = SemaRef.ExprEvalContexts.back();
144 if (record.Context == Sema::Unevaluated)
Richard Smithd390de92012-02-25 10:20:59 +0000145 IsCXX11UnevaluatedField = true;
Richard Smith2c8aee42012-02-25 10:04:07 +0000146 }
147
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000148 // If the current context is not an instance method, it can't be
149 // an implicit member reference.
150 if (isStaticContext) {
151 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000152 return IMA_Mixed_StaticContext;
153
Richard Smithd390de92012-02-25 10:20:59 +0000154 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
155 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000156 }
157
158 CXXRecordDecl *contextClass;
159 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
160 contextClass = MD->getParent()->getCanonicalDecl();
161 else
162 contextClass = cast<CXXRecordDecl>(DC);
163
164 // [class.mfct.non-static]p3:
165 // ...is used in the body of a non-static member function of class X,
166 // if name lookup (3.4.1) resolves the name in the id-expression to a
167 // non-static non-type member of some class C [...]
168 // ...if C is not X or a base class of X, the class member access expression
169 // is ill-formed.
170 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000171 contextClass->getCanonicalDecl() !=
172 R.getNamingClass()->getCanonicalDecl() &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000173 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
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 // If we can prove that the current context is unrelated to all the
179 // declaring classes, it can't be an implicit member reference (in
180 // which case it's an error if any of those members are selected).
181 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smithd390de92012-02-25 10:20:59 +0000182 return hasNonInstance ? IMA_Mixed_Unrelated :
183 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
184 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000185
186 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
187}
188
189/// Diagnose a reference to a field with no object available.
Richard Smitha85cf392012-04-05 01:13:04 +0000190static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000191 const CXXScopeSpec &SS,
Richard Smitha85cf392012-04-05 01:13:04 +0000192 NamedDecl *Rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000193 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000194 SourceLocation Loc = nameInfo.getLoc();
195 SourceRange Range(Loc);
196 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman9bc291d2012-01-18 03:53:45 +0000197
Richard Smitha85cf392012-04-05 01:13:04 +0000198 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
199 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
200 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
201 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
202
203 bool InStaticMethod = Method && Method->isStatic();
204 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
205
206 if (IsField && InStaticMethod)
207 // "invalid use of member 'x' in static member function"
208 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
209 << Range << nameInfo.getName();
210 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
211 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
212 // Unqualified lookup in a non-static member function found a member of an
213 // enclosing class.
214 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
215 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
216 else if (IsField)
Eli Friedmanef331b72012-01-20 01:26:23 +0000217 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smitha85cf392012-04-05 01:13:04 +0000218 << nameInfo.getName() << Range;
219 else
220 SemaRef.Diag(Loc, diag::err_member_call_without_object)
221 << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000222}
223
224/// Builds an expression which might be an implicit member expression.
225ExprResult
226Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000227 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000228 LookupResult &R,
229 const TemplateArgumentListInfo *TemplateArgs) {
230 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
231 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000232 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000233
234 case IMA_Mixed:
235 case IMA_Mixed_Unrelated:
236 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000237 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000238
Richard Smithd390de92012-02-25 10:20:59 +0000239 case IMA_Field_Uneval_Context:
240 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
241 << R.getLookupNameInfo().getName();
242 // Fall through.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000243 case IMA_Static:
244 case IMA_Mixed_StaticContext:
245 case IMA_Unresolved_StaticContext:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000246 if (TemplateArgs || TemplateKWLoc.isValid())
247 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000248 return BuildDeclarationNameExpr(SS, R, false);
249
250 case IMA_Error_StaticContext:
251 case IMA_Error_Unrelated:
Richard Smitha85cf392012-04-05 01:13:04 +0000252 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000253 R.getLookupNameInfo());
254 return ExprError();
255 }
256
257 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000258}
259
260/// Check an ext-vector component access expression.
261///
262/// VK should be set in advance to the value kind of the base
263/// expression.
264static QualType
265CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
266 SourceLocation OpLoc, const IdentifierInfo *CompName,
267 SourceLocation CompLoc) {
268 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
269 // see FIXME there.
270 //
271 // FIXME: This logic can be greatly simplified by splitting it along
272 // halving/not halving and reworking the component checking.
273 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
274
275 // The vector accessor can't exceed the number of elements.
276 const char *compStr = CompName->getNameStart();
277
278 // This flag determines whether or not the component is one of the four
279 // special names that indicate a subset of exactly half the elements are
280 // to be selected.
281 bool HalvingSwizzle = false;
282
283 // This flag determines whether or not CompName has an 's' char prefix,
284 // indicating that it is a string of hex values to be used as vector indices.
285 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
286
287 bool HasRepeated = false;
288 bool HasIndex[16] = {};
289
290 int Idx;
291
292 // Check that we've found one of the special components, or that the component
293 // names must come from the same set.
294 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
295 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
296 HalvingSwizzle = true;
297 } else if (!HexSwizzle &&
298 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
299 do {
300 if (HasIndex[Idx]) HasRepeated = true;
301 HasIndex[Idx] = true;
302 compStr++;
303 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
304 } else {
305 if (HexSwizzle) compStr++;
306 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
307 if (HasIndex[Idx]) HasRepeated = true;
308 HasIndex[Idx] = true;
309 compStr++;
310 }
311 }
312
313 if (!HalvingSwizzle && *compStr) {
314 // We didn't get to the end of the string. This means the component names
315 // didn't come from the same set *or* we encountered an illegal name.
316 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000317 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000318 return QualType();
319 }
320
321 // Ensure no component accessor exceeds the width of the vector type it
322 // operates on.
323 if (!HalvingSwizzle) {
324 compStr = CompName->getNameStart();
325
326 if (HexSwizzle)
327 compStr++;
328
329 while (*compStr) {
330 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
331 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
332 << baseType << SourceRange(CompLoc);
333 return QualType();
334 }
335 }
336 }
337
338 // The component accessor looks fine - now we need to compute the actual type.
339 // The vector type is implied by the component accessor. For example,
340 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
341 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
342 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
343 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
344 : CompName->getLength();
345 if (HexSwizzle)
346 CompSize--;
347
348 if (CompSize == 1)
349 return vecType->getElementType();
350
351 if (HasRepeated) VK = VK_RValue;
352
353 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
354 // Now look up the TypeDefDecl from the vector type. Without this,
355 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000356 for (Sema::ExtVectorDeclsType::iterator
357 I = S.ExtVectorDecls.begin(S.ExternalSource),
358 E = S.ExtVectorDecls.end();
359 I != E; ++I) {
360 if ((*I)->getUnderlyingType() == VT)
361 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000362 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000363
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000364 return VT; // should never get here (a typedef type should always be found).
365}
366
367static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
368 IdentifierInfo *Member,
369 const Selector &Sel,
370 ASTContext &Context) {
371 if (Member)
372 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
373 return PD;
374 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
375 return OMD;
376
377 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
378 E = PDecl->protocol_end(); I != E; ++I) {
379 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
380 Context))
381 return D;
382 }
383 return 0;
384}
385
386static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
387 IdentifierInfo *Member,
388 const Selector &Sel,
389 ASTContext &Context) {
390 // Check protocols on qualified interfaces.
391 Decl *GDecl = 0;
392 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
393 E = QIdTy->qual_end(); I != E; ++I) {
394 if (Member)
395 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
396 GDecl = PD;
397 break;
398 }
399 // Also must look for a getter or setter name which uses property syntax.
400 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
401 GDecl = OMD;
402 break;
403 }
404 }
405 if (!GDecl) {
406 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
407 E = QIdTy->qual_end(); I != E; ++I) {
408 // Search in the protocol-qualifier list of current protocol.
409 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
410 Context);
411 if (GDecl)
412 return GDecl;
413 }
414 }
415 return GDecl;
416}
417
418ExprResult
419Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
420 bool IsArrow, SourceLocation OpLoc,
421 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000422 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000423 NamedDecl *FirstQualifierInScope,
424 const DeclarationNameInfo &NameInfo,
425 const TemplateArgumentListInfo *TemplateArgs) {
426 // Even in dependent contexts, try to diagnose base expressions with
427 // obviously wrong types, e.g.:
428 //
429 // T* t;
430 // t.f;
431 //
432 // In Obj-C++, however, the above expression is valid, since it could be
433 // accessing the 'f' property if T is an Obj-C interface. The extra check
434 // allows this, while still reporting an error if T is a struct pointer.
435 if (!IsArrow) {
436 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikie4e4d0842012-03-11 07:00:24 +0000437 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000438 PT->getPointeeType()->isRecordType())) {
439 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +0000440 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +0000441 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000442 return ExprError();
443 }
444 }
445
446 assert(BaseType->isDependentType() ||
447 NameInfo.getName().isDependentName() ||
448 isDependentScopeSpecifier(SS));
449
450 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
451 // must have pointer type, and the accessed type is the pointee.
452 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
453 IsArrow, OpLoc,
454 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000455 TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000456 FirstQualifierInScope,
457 NameInfo, TemplateArgs));
458}
459
460/// We know that the given qualified member reference points only to
461/// declarations which do not belong to the static type of the base
462/// expression. Diagnose the problem.
463static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
464 Expr *BaseExpr,
465 QualType BaseType,
466 const CXXScopeSpec &SS,
467 NamedDecl *rep,
468 const DeclarationNameInfo &nameInfo) {
469 // If this is an implicit member access, use a different set of
470 // diagnostics.
471 if (!BaseExpr)
Richard Smitha85cf392012-04-05 01:13:04 +0000472 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000473
474 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
475 << SS.getRange() << rep << BaseType;
476}
477
478// Check whether the declarations we found through a nested-name
479// specifier in a member expression are actually members of the base
480// type. The restriction here is:
481//
482// C++ [expr.ref]p2:
483// ... In these cases, the id-expression shall name a
484// member of the class or of one of its base classes.
485//
486// So it's perfectly legitimate for the nested-name specifier to name
487// an unrelated class, and for us to find an overload set including
488// decls from classes which are not superclasses, as long as the decl
489// we actually pick through overload resolution is from a superclass.
490bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
491 QualType BaseType,
492 const CXXScopeSpec &SS,
493 const LookupResult &R) {
494 const RecordType *BaseRT = BaseType->getAs<RecordType>();
495 if (!BaseRT) {
496 // We can't check this yet because the base type is still
497 // dependent.
498 assert(BaseType->isDependentType());
499 return false;
500 }
501 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
502
503 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
504 // If this is an implicit member reference and we find a
505 // non-instance member, it's not an error.
506 if (!BaseExpr && !(*I)->isCXXInstanceMember())
507 return false;
508
509 // Note that we use the DC of the decl, not the underlying decl.
510 DeclContext *DC = (*I)->getDeclContext();
511 while (DC->isTransparentContext())
512 DC = DC->getParent();
513
514 if (!DC->isRecord())
515 continue;
516
517 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
518 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
519
520 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
521 return false;
522 }
523
524 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
525 R.getRepresentativeDecl(),
526 R.getLookupNameInfo());
527 return true;
528}
529
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000530namespace {
531
532// Callback to only accept typo corrections that are either a ValueDecl or a
533// FunctionTemplateDecl.
534class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
535 public:
536 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
537 NamedDecl *ND = candidate.getCorrectionDecl();
538 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
539 }
540};
541
542}
543
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000544static bool
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000545LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000546 SourceRange BaseRange, const RecordType *RTy,
547 SourceLocation OpLoc, CXXScopeSpec &SS,
548 bool HasTemplateArgs) {
549 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000550 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
551 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregord10099e2012-05-04 16:32:21 +0000552 diag::err_typecheck_incomplete_tag,
553 BaseRange))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000554 return true;
555
556 if (HasTemplateArgs) {
557 // LookupTemplateName doesn't expect these both to exist simultaneously.
558 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
559
560 bool MOUS;
561 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
562 return false;
563 }
564
565 DeclContext *DC = RDecl;
566 if (SS.isSet()) {
567 // If the member name was a qualified-id, look into the
568 // nested-name-specifier.
569 DC = SemaRef.computeDeclContext(SS, false);
570
571 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
572 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
573 << SS.getRange() << DC;
574 return true;
575 }
576
577 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
578
579 if (!isa<TypeDecl>(DC)) {
580 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
581 << DC << SS.getRange();
582 return true;
583 }
584 }
585
586 // The record definition is complete, now look up the member.
587 SemaRef.LookupQualifiedName(R, DC);
588
589 if (!R.empty())
590 return false;
591
592 // We didn't find anything with the given name, so try to correct
593 // for typos.
594 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000595 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000596 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
597 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000598 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000599 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000600 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000601 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000602 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000603 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000604 Corrected.getQuoted(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000605 R.setLookupName(Corrected.getCorrection());
606 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000607 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000608 << Name << DC << CorrectedQuotedStr << SS.getRange()
609 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
610 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
611 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000612 }
613
614 return false;
615}
616
617ExprResult
618Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
619 SourceLocation OpLoc, bool IsArrow,
620 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000621 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000622 NamedDecl *FirstQualifierInScope,
623 const DeclarationNameInfo &NameInfo,
624 const TemplateArgumentListInfo *TemplateArgs) {
625 if (BaseType->isDependentType() ||
626 (SS.isSet() && isDependentScopeSpecifier(SS)))
627 return ActOnDependentMemberExpr(Base, BaseType,
628 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000629 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000630 NameInfo, TemplateArgs);
631
632 LookupResult R(*this, NameInfo, LookupMemberName);
633
634 // Implicit member accesses.
635 if (!Base) {
636 QualType RecordTy = BaseType;
637 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
638 if (LookupMemberExprInRecord(*this, R, SourceRange(),
639 RecordTy->getAs<RecordType>(),
640 OpLoc, SS, TemplateArgs != 0))
641 return ExprError();
642
643 // Explicit member accesses.
644 } else {
645 ExprResult BaseResult = Owned(Base);
646 ExprResult Result =
647 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
648 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
649
650 if (BaseResult.isInvalid())
651 return ExprError();
652 Base = BaseResult.take();
653
654 if (Result.isInvalid()) {
655 Owned(Base);
656 return ExprError();
657 }
658
659 if (Result.get())
Benjamin Kramer3fe198b2012-08-23 21:35:17 +0000660 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000661
662 // LookupMemberExpr can modify Base, and thus change BaseType
663 BaseType = Base->getType();
664 }
665
666 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000667 OpLoc, IsArrow, SS, TemplateKWLoc,
668 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000669}
670
671static ExprResult
672BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
673 const CXXScopeSpec &SS, FieldDecl *Field,
674 DeclAccessPair FoundDecl,
675 const DeclarationNameInfo &MemberNameInfo);
676
677ExprResult
678Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
679 SourceLocation loc,
680 IndirectFieldDecl *indirectField,
681 Expr *baseObjectExpr,
682 SourceLocation opLoc) {
683 // First, build the expression that refers to the base object.
684
685 bool baseObjectIsPointer = false;
686 Qualifiers baseQuals;
687
688 // Case 1: the base of the indirect field is not a field.
689 VarDecl *baseVariable = indirectField->getVarDecl();
690 CXXScopeSpec EmptySS;
691 if (baseVariable) {
692 assert(baseVariable->getType()->isRecordType());
693
694 // In principle we could have a member access expression that
695 // accesses an anonymous struct/union that's a static member of
696 // the base object's class. However, under the current standard,
697 // static data members cannot be anonymous structs or unions.
698 // Supporting this is as easy as building a MemberExpr here.
699 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
700
701 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
702
703 ExprResult result
704 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
705 if (result.isInvalid()) return ExprError();
706
707 baseObjectExpr = result.take();
708 baseObjectIsPointer = false;
709 baseQuals = baseObjectExpr->getType().getQualifiers();
710
711 // Case 2: the base of the indirect field is a field and the user
712 // wrote a member expression.
713 } else if (baseObjectExpr) {
714 // The caller provided the base object expression. Determine
715 // whether its a pointer and whether it adds any qualifiers to the
716 // anonymous struct/union fields we're looking into.
717 QualType objectType = baseObjectExpr->getType();
718
719 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
720 baseObjectIsPointer = true;
721 objectType = ptr->getPointeeType();
722 } else {
723 baseObjectIsPointer = false;
724 }
725 baseQuals = objectType.getQualifiers();
726
727 // Case 3: the base of the indirect field is a field and we should
728 // build an implicit member access.
729 } else {
730 // We've found a member of an anonymous struct/union that is
731 // inside a non-anonymous struct/union, so in a well-formed
732 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000733 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000734 if (ThisTy.isNull()) {
735 Diag(loc, diag::err_invalid_member_use_in_static_method)
736 << indirectField->getDeclName();
737 return ExprError();
738 }
739
740 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000741 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000742 baseObjectExpr
743 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
744 baseObjectIsPointer = true;
745 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
746 }
747
748 // Build the implicit member references to the field of the
749 // anonymous struct/union.
750 Expr *result = baseObjectExpr;
751 IndirectFieldDecl::chain_iterator
752 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
753
754 // Build the first member access in the chain with full information.
755 if (!baseVariable) {
756 FieldDecl *field = cast<FieldDecl>(*FI);
757
758 // FIXME: use the real found-decl info!
759 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
760
761 // Make a nameInfo that properly uses the anonymous name.
762 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
763
764 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
765 EmptySS, field, foundDecl,
766 memberNameInfo).take();
767 baseObjectIsPointer = false;
768
769 // FIXME: check qualified member access
770 }
771
772 // In all cases, we should now skip the first declaration in the chain.
773 ++FI;
774
775 while (FI != FEnd) {
776 FieldDecl *field = cast<FieldDecl>(*FI++);
777
778 // FIXME: these are somewhat meaningless
779 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
780 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
781
782 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
783 (FI == FEnd? SS : EmptySS), field,
784 foundDecl, memberNameInfo).take();
785 }
786
787 return Owned(result);
788}
789
790/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000791static MemberExpr *BuildMemberExpr(Sema &SemaRef,
792 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000793 const CXXScopeSpec &SS,
794 SourceLocation TemplateKWLoc,
795 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000796 DeclAccessPair FoundDecl,
797 const DeclarationNameInfo &MemberNameInfo,
798 QualType Ty,
799 ExprValueKind VK, ExprObjectKind OK,
800 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000801 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000802 MemberExpr *E =
803 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
804 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
805 TemplateArgs, Ty, VK, OK);
806 SemaRef.MarkMemberReferenced(E);
807 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000808}
809
810ExprResult
811Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
812 SourceLocation OpLoc, bool IsArrow,
813 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000814 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000815 NamedDecl *FirstQualifierInScope,
816 LookupResult &R,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000817 const TemplateArgumentListInfo *TemplateArgs,
818 bool SuppressQualifierCheck,
819 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000820 QualType BaseType = BaseExprType;
821 if (IsArrow) {
822 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000823 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000824 }
825 R.setBaseObjectType(BaseType);
826
827 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
828 DeclarationName MemberName = MemberNameInfo.getName();
829 SourceLocation MemberLoc = MemberNameInfo.getLoc();
830
831 if (R.isAmbiguous())
832 return ExprError();
833
834 if (R.empty()) {
835 // Rederive where we looked up.
836 DeclContext *DC = (SS.isSet()
837 ? computeDeclContext(SS, false)
838 : BaseType->getAs<RecordType>()->getDecl());
839
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000840 if (ExtraArgs) {
841 ExprResult RetryExpr;
842 if (!IsArrow && BaseExpr) {
Kaelyn Uhrain111263c2012-05-01 01:17:53 +0000843 SFINAETrap Trap(*this, true);
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000844 ParsedType ObjectType;
845 bool MayBePseudoDestructor = false;
846 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
847 OpLoc, tok::arrow, ObjectType,
848 MayBePseudoDestructor);
849 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
850 CXXScopeSpec TempSS(SS);
851 RetryExpr = ActOnMemberAccessExpr(
852 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
853 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
854 ExtraArgs->HasTrailingLParen);
855 }
856 if (Trap.hasErrorOccurred())
857 RetryExpr = ExprError();
858 }
859 if (RetryExpr.isUsable()) {
860 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
861 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
862 return RetryExpr;
863 }
864 }
865
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000866 Diag(R.getNameLoc(), diag::err_no_member)
867 << MemberName << DC
868 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
869 return ExprError();
870 }
871
872 // Diagnose lookups that find only declarations from a non-base
873 // type. This is possible for either qualified lookups (which may
874 // have been qualified with an unrelated type) or implicit member
875 // expressions (which were found with unqualified lookup and thus
876 // may have come from an enclosing scope). Note that it's okay for
877 // lookup to find declarations from a non-base type as long as those
878 // aren't the ones picked by overload resolution.
879 if ((SS.isSet() || !BaseExpr ||
880 (isa<CXXThisExpr>(BaseExpr) &&
881 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
882 !SuppressQualifierCheck &&
883 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
884 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000885
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000886 // Construct an unresolved result if we in fact got an unresolved
887 // result.
888 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
889 // Suppress any lookup-related diagnostics; we'll do these when we
890 // pick a member.
891 R.suppressDiagnostics();
892
893 UnresolvedMemberExpr *MemExpr
894 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
895 BaseExpr, BaseExprType,
896 IsArrow, OpLoc,
897 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000898 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000899 TemplateArgs, R.begin(), R.end());
900
901 return Owned(MemExpr);
902 }
903
904 assert(R.isSingleResult());
905 DeclAccessPair FoundDecl = R.begin().getPair();
906 NamedDecl *MemberDecl = R.getFoundDecl();
907
908 // FIXME: diagnose the presence of template arguments now.
909
910 // If the decl being referenced had an error, return an error for this
911 // sub-expr without emitting another error, in order to avoid cascading
912 // error cases.
913 if (MemberDecl->isInvalidDecl())
914 return ExprError();
915
916 // Handle the implicit-member-access case.
917 if (!BaseExpr) {
918 // If this is not an instance member, convert to a non-member access.
919 if (!MemberDecl->isCXXInstanceMember())
920 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
921
922 SourceLocation Loc = R.getNameLoc();
923 if (SS.getRange().isValid())
924 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000925 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000926 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
927 }
928
929 bool ShouldCheckUse = true;
930 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
931 // Don't diagnose the use of a virtual member function unless it's
932 // explicitly qualified.
933 if (MD->isVirtual() && !SS.isSet())
934 ShouldCheckUse = false;
935 }
936
937 // Check the use of this member.
938 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
939 Owned(BaseExpr);
940 return ExprError();
941 }
942
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000943 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
944 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
945 SS, FD, FoundDecl, MemberNameInfo);
946
947 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
948 // We may have found a field within an anonymous union or struct
949 // (C++ [class.union]).
950 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
951 BaseExpr, OpLoc);
952
953 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000954 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
955 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000956 Var->getType().getNonReferenceType(),
957 VK_LValue, OK_Ordinary));
958 }
959
960 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
961 ExprValueKind valueKind;
962 QualType type;
963 if (MemberFn->isInstance()) {
964 valueKind = VK_RValue;
965 type = Context.BoundMemberTy;
966 } else {
967 valueKind = VK_LValue;
968 type = MemberFn->getType();
969 }
970
Eli Friedman5f2987c2012-02-02 03:46:19 +0000971 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
972 TemplateKWLoc, MemberFn, FoundDecl,
973 MemberNameInfo, type, valueKind,
974 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000975 }
976 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
977
978 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000979 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
980 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000981 Enum->getType(), VK_RValue, OK_Ordinary));
982 }
983
984 Owned(BaseExpr);
985
986 // We found something that we didn't expect. Complain.
987 if (isa<TypeDecl>(MemberDecl))
988 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
989 << MemberName << BaseType << int(IsArrow);
990 else
991 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
992 << MemberName << BaseType << int(IsArrow);
993
994 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
995 << MemberName;
996 R.suppressDiagnostics();
997 return ExprError();
998}
999
1000/// Given that normal member access failed on the given expression,
1001/// and given that the expression's type involves builtin-id or
1002/// builtin-Class, decide whether substituting in the redefinition
1003/// types would be profitable. The redefinition type is whatever
1004/// this translation unit tried to typedef to id/Class; we store
1005/// it to the side and then re-use it in places like this.
1006static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1007 const ObjCObjectPointerType *opty
1008 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1009 if (!opty) return false;
1010
1011 const ObjCObjectType *ty = opty->getObjectType();
1012
1013 QualType redef;
1014 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001015 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001016 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001017 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001018 } else {
1019 return false;
1020 }
1021
1022 // Do the substitution as long as the redefinition type isn't just a
1023 // possibly-qualified pointer to builtin-id or builtin-Class again.
1024 opty = redef->getAs<ObjCObjectPointerType>();
1025 if (opty && !opty->getObjectType()->getInterface() != 0)
1026 return false;
1027
1028 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1029 return true;
1030}
1031
John McCall6dbba4f2011-10-11 23:14:30 +00001032static bool isRecordType(QualType T) {
1033 return T->isRecordType();
1034}
1035static bool isPointerToRecordType(QualType T) {
1036 if (const PointerType *PT = T->getAs<PointerType>())
1037 return PT->getPointeeType()->isRecordType();
1038 return false;
1039}
1040
Richard Smith9138b4e2011-10-26 19:06:56 +00001041/// Perform conversions on the LHS of a member access expression.
1042ExprResult
1043Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001044 if (IsArrow && !Base->getType()->isFunctionType())
1045 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001046
Eli Friedman059d5782012-01-13 02:20:01 +00001047 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001048}
1049
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001050/// Look up the given member of the given non-type-dependent
1051/// expression. This can return in one of two ways:
1052/// * If it returns a sentinel null-but-valid result, the caller will
1053/// assume that lookup was performed and the results written into
1054/// the provided structure. It will take over from there.
1055/// * Otherwise, the returned expression will be produced in place of
1056/// an ordinary member expression.
1057///
1058/// The ObjCImpDecl bit is a gross hack that will need to be properly
1059/// fixed for ObjC++.
1060ExprResult
1061Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1062 bool &IsArrow, SourceLocation OpLoc,
1063 CXXScopeSpec &SS,
1064 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1065 assert(BaseExpr.get() && "no base expression");
1066
1067 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001068 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001069 if (BaseExpr.isInvalid())
1070 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001071
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001072 QualType BaseType = BaseExpr.get()->getType();
1073 assert(!BaseType->isDependentType());
1074
1075 DeclarationName MemberName = R.getLookupName();
1076 SourceLocation MemberLoc = R.getNameLoc();
1077
1078 // For later type-checking purposes, turn arrow accesses into dot
1079 // accesses. The only access type we support that doesn't follow
1080 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1081 // and those never use arrows, so this is unaffected.
1082 if (IsArrow) {
1083 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1084 BaseType = Ptr->getPointeeType();
1085 else if (const ObjCObjectPointerType *Ptr
1086 = BaseType->getAs<ObjCObjectPointerType>())
1087 BaseType = Ptr->getPointeeType();
1088 else if (BaseType->isRecordType()) {
1089 // Recover from arrow accesses to records, e.g.:
1090 // struct MyRecord foo;
1091 // foo->bar
1092 // This is actually well-formed in C++ if MyRecord has an
1093 // overloaded operator->, but that should have been dealt with
1094 // by now.
1095 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1096 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1097 << FixItHint::CreateReplacement(OpLoc, ".");
1098 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001099 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001100 goto fail;
1101 } else {
1102 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1103 << BaseType << BaseExpr.get()->getSourceRange();
1104 return ExprError();
1105 }
1106 }
1107
1108 // Handle field access to simple records.
1109 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1110 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1111 RTy, OpLoc, SS, HasTemplateArgs))
1112 return ExprError();
1113
1114 // Returning valid-but-null is how we indicate to the caller that
1115 // the lookup result was filled in.
1116 return Owned((Expr*) 0);
1117 }
1118
1119 // Handle ivar access to Objective-C objects.
1120 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001121 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001122 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1123 << 1 << SS.getScopeRep()
1124 << FixItHint::CreateRemoval(SS.getRange());
1125 SS.clear();
1126 }
1127
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001128 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1129
1130 // There are three cases for the base type:
1131 // - builtin id (qualified or unqualified)
1132 // - builtin Class (qualified or unqualified)
1133 // - an interface
1134 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1135 if (!IDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001136 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001137 (OTy->isObjCId() || OTy->isObjCClass()))
1138 goto fail;
1139 // There's an implicit 'isa' ivar on all objects.
1140 // But we only actually find it this way on objects of type 'id',
Eric Christopher2502ec82012-08-16 23:50:37 +00001141 // apparently.
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001142 if (OTy->isObjCId() && Member->isStr("isa")) {
1143 Diag(MemberLoc, diag::warn_objc_isa_use);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001144 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1145 Context.getObjCClassType()));
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001146 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001147
1148 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1149 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1150 ObjCImpDecl, HasTemplateArgs);
1151 goto fail;
1152 }
Fariborz Jahanian09100592012-06-21 21:35:15 +00001153 else if (Member && Member->isStr("isa")) {
1154 // If an ivar is (1) the first ivar in a root class and (2) named `isa`,
1155 // then issue the same deprecated warning that id->isa gets.
1156 ObjCInterfaceDecl *ClassDeclared = 0;
1157 if (ObjCIvarDecl *IV =
1158 IDecl->lookupInstanceVariable(Member, ClassDeclared)) {
1159 if (!ClassDeclared->getSuperClass()
1160 && (*ClassDeclared->ivar_begin()) == IV) {
1161 Diag(MemberLoc, diag::warn_objc_isa_use);
1162 Diag(IV->getLocation(), diag::note_ivar_decl);
1163 }
1164 }
1165 }
1166
Douglas Gregord10099e2012-05-04 16:32:21 +00001167 if (RequireCompleteType(OpLoc, BaseType, diag::err_typecheck_incomplete_tag,
1168 BaseExpr.get()))
Douglas Gregord07cc362012-01-02 17:18:37 +00001169 return ExprError();
1170
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001171 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001172 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1173
1174 if (!IV) {
1175 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001176 DeclFilterCCC<ObjCIvarDecl> Validator;
1177 Validator.IsObjCIvarLookup = IsArrow;
1178 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1179 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001180 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001181 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001182 Diag(R.getNameLoc(),
1183 diag::err_typecheck_member_reference_ivar_suggest)
1184 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1185 << FixItHint::CreateReplacement(R.getNameLoc(),
1186 IV->getNameAsString());
1187 Diag(IV->getLocation(), diag::note_previous_decl)
1188 << IV->getDeclName();
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001189
1190 // Figure out the class that declares the ivar.
1191 assert(!ClassDeclared);
1192 Decl *D = cast<Decl>(IV->getDeclContext());
1193 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1194 D = CAT->getClassInterface();
1195 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001196 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001197 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1198 Diag(MemberLoc,
1199 diag::err_property_found_suggest)
1200 << Member << BaseExpr.get()->getType()
1201 << FixItHint::CreateReplacement(OpLoc, ".");
1202 return ExprError();
1203 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001204
1205 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1206 << IDecl->getDeclName() << MemberName
1207 << BaseExpr.get()->getSourceRange();
1208 return ExprError();
1209 }
1210 }
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001211
1212 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001213
1214 // If the decl being referenced had an error, return an error for this
1215 // sub-expr without emitting another error, in order to avoid cascading
1216 // error cases.
1217 if (IV->isInvalidDecl())
1218 return ExprError();
1219
1220 // Check whether we can reference this field.
1221 if (DiagnoseUseOfDecl(IV, MemberLoc))
1222 return ExprError();
1223 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1224 IV->getAccessControl() != ObjCIvarDecl::Package) {
1225 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1226 if (ObjCMethodDecl *MD = getCurMethodDecl())
1227 ClassOfMethodDecl = MD->getClassInterface();
1228 else if (ObjCImpDecl && getCurFunctionDecl()) {
1229 // Case of a c-function declared inside an objc implementation.
1230 // FIXME: For a c-style function nested inside an objc implementation
1231 // class, there is no implementation context available, so we pass
1232 // down the context as argument to this routine. Ideally, this context
1233 // need be passed down in the AST node and somehow calculated from the
1234 // AST for a function decl.
1235 if (ObjCImplementationDecl *IMPD =
1236 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1237 ClassOfMethodDecl = IMPD->getClassInterface();
1238 else if (ObjCCategoryImplDecl* CatImplClass =
1239 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1240 ClassOfMethodDecl = CatImplClass->getClassInterface();
1241 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001242 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001243 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1244 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1245 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1246 Diag(MemberLoc, diag::error_private_ivar_access)
1247 << IV->getDeclName();
1248 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1249 // @protected
1250 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001251 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001252 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001253 }
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001254 bool warn = true;
David Blaikie4e4d0842012-03-11 07:00:24 +00001255 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001256 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1257 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1258 if (UO->getOpcode() == UO_Deref)
1259 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1260
1261 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001262 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001263 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
Fariborz Jahanianb25466e2012-08-07 23:48:10 +00001264 warn = false;
1265 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001266 }
Fariborz Jahanianed6662d2012-08-08 16:41:04 +00001267 if (warn) {
Fariborz Jahaniancff863f2012-08-07 16:38:44 +00001268 if (ObjCMethodDecl *MD = getCurMethodDecl()) {
1269 ObjCMethodFamily MF = MD->getMethodFamily();
1270 warn = (MF != OMF_init && MF != OMF_dealloc &&
1271 MF != OMF_finalize);
1272 }
1273 if (warn)
1274 Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1275 }
Jordan Rose7a270482012-09-28 22:21:35 +00001276
1277 ObjCIvarRefExpr *Result = new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1278 MemberLoc,
1279 BaseExpr.take(),
1280 IsArrow);
1281
1282 if (getLangOpts().ObjCAutoRefCount) {
1283 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1284 DiagnosticsEngine::Level Level =
1285 Diags.getDiagnosticLevel(diag::warn_arc_repeated_use_of_weak,
1286 MemberLoc);
1287 if (Level != DiagnosticsEngine::Ignored)
1288 getCurFunction()->recordUseOfWeak(Result);
1289 }
1290 }
1291
1292 return Owned(Result);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001293 }
1294
1295 // Objective-C property access.
1296 const ObjCObjectPointerType *OPT;
1297 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001298 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001299 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1300 << 0 << SS.getScopeRep()
1301 << FixItHint::CreateRemoval(SS.getRange());
1302 SS.clear();
1303 }
1304
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001305 // This actually uses the base as an r-value.
1306 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1307 if (BaseExpr.isInvalid())
1308 return ExprError();
1309
1310 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1311
1312 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1313
1314 const ObjCObjectType *OT = OPT->getObjectType();
1315
1316 // id, with and without qualifiers.
1317 if (OT->isObjCId()) {
1318 // Check protocols on qualified interfaces.
1319 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1320 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1321 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1322 // Check the use of this declaration
1323 if (DiagnoseUseOfDecl(PD, MemberLoc))
1324 return ExprError();
1325
John McCall3c3b7f92011-10-25 17:37:35 +00001326 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1327 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001328 VK_LValue,
1329 OK_ObjCProperty,
1330 MemberLoc,
1331 BaseExpr.take()));
1332 }
1333
1334 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1335 // Check the use of this method.
1336 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1337 return ExprError();
1338 Selector SetterSel =
1339 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1340 PP.getSelectorTable(), Member);
1341 ObjCMethodDecl *SMD = 0;
1342 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1343 SetterSel, Context))
1344 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001345
John McCall3c3b7f92011-10-25 17:37:35 +00001346 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1347 Context.PseudoObjectTy,
1348 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001349 MemberLoc, BaseExpr.take()));
1350 }
1351 }
1352 // Use of id.member can only be for a property reference. Do not
1353 // use the 'id' redefinition in this case.
1354 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1355 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1356 ObjCImpDecl, HasTemplateArgs);
1357
1358 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1359 << MemberName << BaseType);
1360 }
1361
1362 // 'Class', unqualified only.
1363 if (OT->isObjCClass()) {
1364 // Only works in a method declaration (??!).
1365 ObjCMethodDecl *MD = getCurMethodDecl();
1366 if (!MD) {
1367 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1368 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1369 ObjCImpDecl, HasTemplateArgs);
1370
1371 goto fail;
1372 }
1373
1374 // Also must look for a getter name which uses property syntax.
1375 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1376 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1377 ObjCMethodDecl *Getter;
1378 if ((Getter = IFace->lookupClassMethod(Sel))) {
1379 // Check the use of this method.
1380 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1381 return ExprError();
1382 } else
1383 Getter = IFace->lookupPrivateMethod(Sel, false);
1384 // If we found a getter then this may be a valid dot-reference, we
1385 // will look for the matching setter, in case it is needed.
1386 Selector SetterSel =
1387 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1388 PP.getSelectorTable(), Member);
1389 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1390 if (!Setter) {
1391 // If this reference is in an @implementation, also check for 'private'
1392 // methods.
1393 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1394 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001395
1396 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1397 return ExprError();
1398
1399 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001400 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001401 Context.PseudoObjectTy,
1402 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001403 MemberLoc, BaseExpr.take()));
1404 }
1405
1406 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1407 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1408 ObjCImpDecl, HasTemplateArgs);
1409
1410 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1411 << MemberName << BaseType);
1412 }
1413
1414 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001415 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1416 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001417 SourceLocation(), QualType(), false);
1418 }
1419
1420 // Handle 'field access' to vectors, such as 'V.xx'.
1421 if (BaseType->isExtVectorType()) {
1422 // FIXME: this expr should store IsArrow.
1423 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1424 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1425 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1426 Member, MemberLoc);
1427 if (ret.isNull())
1428 return ExprError();
1429
1430 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1431 *Member, MemberLoc));
1432 }
1433
1434 // Adjust builtin-sel to the appropriate redefinition type if that's
1435 // not just a pointer to builtin-sel again.
1436 if (IsArrow &&
1437 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001438 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1439 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1440 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001441 CK_BitCast);
1442 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1443 ObjCImpDecl, HasTemplateArgs);
1444 }
1445
1446 // Failure cases.
1447 fail:
1448
1449 // Recover from dot accesses to pointers, e.g.:
1450 // type *foo;
1451 // foo.bar
1452 // This is actually well-formed in two cases:
1453 // - 'type' is an Objective C type
1454 // - 'bar' is a pseudo-destructor name which happens to refer to
1455 // the appropriate pointer type
1456 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1457 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1458 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1459 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1460 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1461 << FixItHint::CreateReplacement(OpLoc, "->");
1462
1463 // Recurse as an -> access.
1464 IsArrow = true;
1465 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1466 ObjCImpDecl, HasTemplateArgs);
1467 }
1468 }
1469
1470 // If the user is trying to apply -> or . to a function name, it's probably
1471 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001472 if (tryToRecoverWithCall(BaseExpr,
1473 PDiag(diag::err_member_reference_needs_call),
1474 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001475 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001476 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001477 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001478 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1479 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1480 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001481 }
1482
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +00001483 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +00001484 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001485
1486 return ExprError();
1487}
1488
1489/// The main callback when the parser finds something like
1490/// expression . [nested-name-specifier] identifier
1491/// expression -> [nested-name-specifier] identifier
1492/// where 'identifier' encompasses a fairly broad spectrum of
1493/// possibilities, including destructor and operator references.
1494///
1495/// \param OpKind either tok::arrow or tok::period
1496/// \param HasTrailingLParen whether the next token is '(', which
1497/// is used to diagnose mis-uses of special members that can
1498/// only be called
James Dennett699c9042012-06-15 07:13:21 +00001499/// \param ObjCImpDecl the current Objective-C \@implementation
1500/// decl; this is an ugly hack around the fact that Objective-C
1501/// \@implementations aren't properly put in the context chain
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001502ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1503 SourceLocation OpLoc,
1504 tok::TokenKind OpKind,
1505 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001506 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001507 UnqualifiedId &Id,
1508 Decl *ObjCImpDecl,
1509 bool HasTrailingLParen) {
1510 if (SS.isSet() && SS.isInvalid())
1511 return ExprError();
1512
1513 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001514 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001515 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1516 Diag(Id.getSourceRange().getBegin(),
1517 diag::ext_ms_explicit_constructor_call);
1518
1519 TemplateArgumentListInfo TemplateArgsBuffer;
1520
1521 // Decompose the name into its component parts.
1522 DeclarationNameInfo NameInfo;
1523 const TemplateArgumentListInfo *TemplateArgs;
1524 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1525 NameInfo, TemplateArgs);
1526
1527 DeclarationName Name = NameInfo.getName();
1528 bool IsArrow = (OpKind == tok::arrow);
1529
1530 NamedDecl *FirstQualifierInScope
1531 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1532 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1533
1534 // This is a postfix expression, so get rid of ParenListExprs.
1535 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1536 if (Result.isInvalid()) return ExprError();
1537 Base = Result.take();
1538
1539 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1540 isDependentScopeSpecifier(SS)) {
1541 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1542 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001543 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001544 NameInfo, TemplateArgs);
1545 } else {
1546 LookupResult R(*this, NameInfo, LookupMemberName);
1547 ExprResult BaseResult = Owned(Base);
1548 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1549 SS, ObjCImpDecl, TemplateArgs != 0);
1550 if (BaseResult.isInvalid())
1551 return ExprError();
1552 Base = BaseResult.take();
1553
1554 if (Result.isInvalid()) {
1555 Owned(Base);
1556 return ExprError();
1557 }
1558
1559 if (Result.get()) {
1560 // The only way a reference to a destructor can be used is to
1561 // immediately call it, which falls into this case. If the
1562 // next token is not a '(', produce a diagnostic and build the
1563 // call now.
1564 if (!HasTrailingLParen &&
1565 Id.getKind() == UnqualifiedId::IK_DestructorName)
1566 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1567
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001568 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001569 }
1570
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001571 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001572 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001573 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001574 FirstQualifierInScope, R, TemplateArgs,
1575 false, &ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001576 }
1577
Benjamin Kramer3fe198b2012-08-23 21:35:17 +00001578 return Result;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001579}
1580
1581static ExprResult
1582BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1583 const CXXScopeSpec &SS, FieldDecl *Field,
1584 DeclAccessPair FoundDecl,
1585 const DeclarationNameInfo &MemberNameInfo) {
1586 // x.a is an l-value if 'a' has a reference type. Otherwise:
1587 // x.a is an l-value/x-value/pr-value if the base is (and note
1588 // that *x is always an l-value), except that if the base isn't
1589 // an ordinary object then we must have an rvalue.
1590 ExprValueKind VK = VK_LValue;
1591 ExprObjectKind OK = OK_Ordinary;
1592 if (!IsArrow) {
1593 if (BaseExpr->getObjectKind() == OK_Ordinary)
1594 VK = BaseExpr->getValueKind();
1595 else
1596 VK = VK_RValue;
1597 }
1598 if (VK != VK_RValue && Field->isBitField())
1599 OK = OK_BitField;
1600
1601 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1602 QualType MemberType = Field->getType();
1603 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1604 MemberType = Ref->getPointeeType();
1605 VK = VK_LValue;
1606 } else {
1607 QualType BaseType = BaseExpr->getType();
1608 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1609
1610 Qualifiers BaseQuals = BaseType.getQualifiers();
1611
1612 // GC attributes are never picked up by members.
1613 BaseQuals.removeObjCGCAttr();
1614
1615 // CVR attributes from the base are picked up by members,
1616 // except that 'mutable' members don't pick up 'const'.
1617 if (Field->isMutable()) BaseQuals.removeConst();
1618
1619 Qualifiers MemberQuals
1620 = S.Context.getCanonicalType(MemberType).getQualifiers();
1621
1622 // TR 18037 does not allow fields to be declared with address spaces.
1623 assert(!MemberQuals.hasAddressSpace());
1624
1625 Qualifiers Combined = BaseQuals + MemberQuals;
1626 if (Combined != MemberQuals)
1627 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1628 }
1629
Daniel Jasperf8cc02e2012-06-06 08:32:04 +00001630 S.UnusedPrivateFields.remove(Field);
1631
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001632 ExprResult Base =
1633 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1634 FoundDecl, Field);
1635 if (Base.isInvalid())
1636 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001637 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001638 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001639 Field, FoundDecl, MemberNameInfo,
1640 MemberType, VK, OK));
1641}
1642
1643/// Builds an implicit member access expression. The current context
1644/// is known to be an instance method, and the given unqualified lookup
1645/// set is known to contain only instance members, at least one of which
1646/// is from an appropriate type.
1647ExprResult
1648Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001649 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001650 LookupResult &R,
1651 const TemplateArgumentListInfo *TemplateArgs,
1652 bool IsKnownInstance) {
1653 assert(!R.empty() && !R.isAmbiguous());
1654
1655 SourceLocation loc = R.getNameLoc();
1656
1657 // We may have found a field within an anonymous union or struct
1658 // (C++ [class.union]).
1659 // FIXME: template-ids inside anonymous structs?
1660 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1661 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1662
1663 // If this is known to be an instance access, go ahead and build an
1664 // implicit 'this' expression now.
1665 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001666 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001667 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1668
1669 Expr *baseExpr = 0; // null signifies implicit access
1670 if (IsKnownInstance) {
1671 SourceLocation Loc = R.getNameLoc();
1672 if (SS.getRange().isValid())
1673 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001674 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001675 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1676 }
1677
1678 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1679 /*OpLoc*/ SourceLocation(),
1680 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001681 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001682 /*FirstQualifierInScope*/ 0,
1683 R, TemplateArgs);
1684}