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