blob: e0dfd677aae8e728a105d3199fafa9626a65ef5c [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
104 bool isStaticContext =
105 (!isa<CXXMethodDecl>(DC) ||
106 cast<CXXMethodDecl>(DC)->isStatic());
107
108 // C++0x [expr.prim]p4:
109 // Otherwise, if a member-declarator declares a non-static data member
110 // of a class X, the expression this is a prvalue of type "pointer to X"
111 // within the optional brace-or-equal-initializer.
112 if (CurScope->getFlags() & Scope::ThisScope)
113 isStaticContext = false;
114
115 if (R.isUnresolvableResult())
116 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
117
118 // Collect all the declaring classes of instance members we find.
119 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000120 bool isField = false;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000121 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
122 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
123 NamedDecl *D = *I;
124
125 if (D->isCXXInstanceMember()) {
126 if (dyn_cast<FieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000127 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000128
129 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
130 Classes.insert(R->getCanonicalDecl());
131 }
132 else
133 hasNonInstance = true;
134 }
135
136 // If we didn't find any instance members, it can't be an implicit
137 // member reference.
138 if (Classes.empty())
139 return IMA_Static;
140
Richard Smithd390de92012-02-25 10:20:59 +0000141 bool IsCXX11UnevaluatedField = false;
Richard Smith2c8aee42012-02-25 10:04:07 +0000142 if (SemaRef.getLangOptions().CPlusPlus0x && isField) {
143 // C++11 [expr.prim.general]p12:
144 // An id-expression that denotes a non-static data member or non-static
145 // member function of a class can only be used:
146 // (...)
147 // - if that id-expression denotes a non-static data member and it
148 // appears in an unevaluated operand.
149 const Sema::ExpressionEvaluationContextRecord& record
150 = SemaRef.ExprEvalContexts.back();
151 if (record.Context == Sema::Unevaluated)
Richard Smithd390de92012-02-25 10:20:59 +0000152 IsCXX11UnevaluatedField = true;
Richard Smith2c8aee42012-02-25 10:04:07 +0000153 }
154
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000155 // If the current context is not an instance method, it can't be
156 // an implicit member reference.
157 if (isStaticContext) {
158 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000159 return IMA_Mixed_StaticContext;
160
Richard Smithd390de92012-02-25 10:20:59 +0000161 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
162 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000163 }
164
165 CXXRecordDecl *contextClass;
166 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
167 contextClass = MD->getParent()->getCanonicalDecl();
168 else
169 contextClass = cast<CXXRecordDecl>(DC);
170
171 // [class.mfct.non-static]p3:
172 // ...is used in the body of a non-static member function of class X,
173 // if name lookup (3.4.1) resolves the name in the id-expression to a
174 // non-static non-type member of some class C [...]
175 // ...if C is not X or a base class of X, the class member access expression
176 // is ill-formed.
177 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000178 contextClass->getCanonicalDecl() !=
179 R.getNamingClass()->getCanonicalDecl() &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000180 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
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 // If we can prove that the current context is unrelated to all the
186 // declaring classes, it can't be an implicit member reference (in
187 // which case it's an error if any of those members are selected).
188 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smithd390de92012-02-25 10:20:59 +0000189 return hasNonInstance ? IMA_Mixed_Unrelated :
190 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
191 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000192
193 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
194}
195
196/// Diagnose a reference to a field with no object available.
197static void DiagnoseInstanceReference(Sema &SemaRef,
198 const CXXScopeSpec &SS,
199 NamedDecl *rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000200 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000201 SourceLocation Loc = nameInfo.getLoc();
202 SourceRange Range(Loc);
203 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
204
205 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
206 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
207 if (MD->isStatic()) {
208 // "invalid use of member 'x' in static member function"
Eli Friedmanef331b72012-01-20 01:26:23 +0000209 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
210 << Range << nameInfo.getName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000211 return;
212 }
213 }
Eli Friedman9bc291d2012-01-18 03:53:45 +0000214
Eli Friedmanef331b72012-01-20 01:26:23 +0000215 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
216 << nameInfo.getName() << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000217 return;
218 }
Eli Friedman9bc291d2012-01-18 03:53:45 +0000219
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000220 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
221}
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:
251 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
252 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>();
436 if (PT && (!getLangOptions().ObjC1 ||
437 PT->getPointeeType()->isRecordType())) {
438 assert(BaseExpr && "cannot happen with implicit member accesses");
439 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
440 << BaseType << BaseExpr->getSourceRange();
441 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)
471 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
472
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
544LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
545 SourceRange BaseRange, const RecordType *RTy,
546 SourceLocation OpLoc, CXXScopeSpec &SS,
547 bool HasTemplateArgs) {
548 RecordDecl *RDecl = RTy->getDecl();
549 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
550 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
551 << BaseRange))
552 return true;
553
554 if (HasTemplateArgs) {
555 // LookupTemplateName doesn't expect these both to exist simultaneously.
556 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
557
558 bool MOUS;
559 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
560 return false;
561 }
562
563 DeclContext *DC = RDecl;
564 if (SS.isSet()) {
565 // If the member name was a qualified-id, look into the
566 // nested-name-specifier.
567 DC = SemaRef.computeDeclContext(SS, false);
568
569 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
570 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
571 << SS.getRange() << DC;
572 return true;
573 }
574
575 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
576
577 if (!isa<TypeDecl>(DC)) {
578 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
579 << DC << SS.getRange();
580 return true;
581 }
582 }
583
584 // The record definition is complete, now look up the member.
585 SemaRef.LookupQualifiedName(R, DC);
586
587 if (!R.empty())
588 return false;
589
590 // We didn't find anything with the given name, so try to correct
591 // for typos.
592 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000593 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000594 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
595 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000596 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000597 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000598 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000599 std::string CorrectedStr(
600 Corrected.getAsString(SemaRef.getLangOptions()));
601 std::string CorrectedQuotedStr(
602 Corrected.getQuoted(SemaRef.getLangOptions()));
603 R.setLookupName(Corrected.getCorrection());
604 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000605 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000606 << Name << DC << CorrectedQuotedStr << SS.getRange()
607 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
608 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
609 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000610 }
611
612 return false;
613}
614
615ExprResult
616Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
617 SourceLocation OpLoc, bool IsArrow,
618 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000619 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000620 NamedDecl *FirstQualifierInScope,
621 const DeclarationNameInfo &NameInfo,
622 const TemplateArgumentListInfo *TemplateArgs) {
623 if (BaseType->isDependentType() ||
624 (SS.isSet() && isDependentScopeSpecifier(SS)))
625 return ActOnDependentMemberExpr(Base, BaseType,
626 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000627 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000628 NameInfo, TemplateArgs);
629
630 LookupResult R(*this, NameInfo, LookupMemberName);
631
632 // Implicit member accesses.
633 if (!Base) {
634 QualType RecordTy = BaseType;
635 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
636 if (LookupMemberExprInRecord(*this, R, SourceRange(),
637 RecordTy->getAs<RecordType>(),
638 OpLoc, SS, TemplateArgs != 0))
639 return ExprError();
640
641 // Explicit member accesses.
642 } else {
643 ExprResult BaseResult = Owned(Base);
644 ExprResult Result =
645 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
646 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
647
648 if (BaseResult.isInvalid())
649 return ExprError();
650 Base = BaseResult.take();
651
652 if (Result.isInvalid()) {
653 Owned(Base);
654 return ExprError();
655 }
656
657 if (Result.get())
658 return move(Result);
659
660 // LookupMemberExpr can modify Base, and thus change BaseType
661 BaseType = Base->getType();
662 }
663
664 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000665 OpLoc, IsArrow, SS, TemplateKWLoc,
666 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000667}
668
669static ExprResult
670BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
671 const CXXScopeSpec &SS, FieldDecl *Field,
672 DeclAccessPair FoundDecl,
673 const DeclarationNameInfo &MemberNameInfo);
674
675ExprResult
676Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
677 SourceLocation loc,
678 IndirectFieldDecl *indirectField,
679 Expr *baseObjectExpr,
680 SourceLocation opLoc) {
681 // First, build the expression that refers to the base object.
682
683 bool baseObjectIsPointer = false;
684 Qualifiers baseQuals;
685
686 // Case 1: the base of the indirect field is not a field.
687 VarDecl *baseVariable = indirectField->getVarDecl();
688 CXXScopeSpec EmptySS;
689 if (baseVariable) {
690 assert(baseVariable->getType()->isRecordType());
691
692 // In principle we could have a member access expression that
693 // accesses an anonymous struct/union that's a static member of
694 // the base object's class. However, under the current standard,
695 // static data members cannot be anonymous structs or unions.
696 // Supporting this is as easy as building a MemberExpr here.
697 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
698
699 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
700
701 ExprResult result
702 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
703 if (result.isInvalid()) return ExprError();
704
705 baseObjectExpr = result.take();
706 baseObjectIsPointer = false;
707 baseQuals = baseObjectExpr->getType().getQualifiers();
708
709 // Case 2: the base of the indirect field is a field and the user
710 // wrote a member expression.
711 } else if (baseObjectExpr) {
712 // The caller provided the base object expression. Determine
713 // whether its a pointer and whether it adds any qualifiers to the
714 // anonymous struct/union fields we're looking into.
715 QualType objectType = baseObjectExpr->getType();
716
717 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
718 baseObjectIsPointer = true;
719 objectType = ptr->getPointeeType();
720 } else {
721 baseObjectIsPointer = false;
722 }
723 baseQuals = objectType.getQualifiers();
724
725 // Case 3: the base of the indirect field is a field and we should
726 // build an implicit member access.
727 } else {
728 // We've found a member of an anonymous struct/union that is
729 // inside a non-anonymous struct/union, so in a well-formed
730 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000731 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000732 if (ThisTy.isNull()) {
733 Diag(loc, diag::err_invalid_member_use_in_static_method)
734 << indirectField->getDeclName();
735 return ExprError();
736 }
737
738 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000739 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000740 baseObjectExpr
741 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
742 baseObjectIsPointer = true;
743 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
744 }
745
746 // Build the implicit member references to the field of the
747 // anonymous struct/union.
748 Expr *result = baseObjectExpr;
749 IndirectFieldDecl::chain_iterator
750 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
751
752 // Build the first member access in the chain with full information.
753 if (!baseVariable) {
754 FieldDecl *field = cast<FieldDecl>(*FI);
755
756 // FIXME: use the real found-decl info!
757 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
758
759 // Make a nameInfo that properly uses the anonymous name.
760 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
761
762 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
763 EmptySS, field, foundDecl,
764 memberNameInfo).take();
765 baseObjectIsPointer = false;
766
767 // FIXME: check qualified member access
768 }
769
770 // In all cases, we should now skip the first declaration in the chain.
771 ++FI;
772
773 while (FI != FEnd) {
774 FieldDecl *field = cast<FieldDecl>(*FI++);
775
776 // FIXME: these are somewhat meaningless
777 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
778 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
779
780 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
781 (FI == FEnd? SS : EmptySS), field,
782 foundDecl, memberNameInfo).take();
783 }
784
785 return Owned(result);
786}
787
788/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000789static MemberExpr *BuildMemberExpr(Sema &SemaRef,
790 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000791 const CXXScopeSpec &SS,
792 SourceLocation TemplateKWLoc,
793 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000794 DeclAccessPair FoundDecl,
795 const DeclarationNameInfo &MemberNameInfo,
796 QualType Ty,
797 ExprValueKind VK, ExprObjectKind OK,
798 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000799 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000800 MemberExpr *E =
801 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
802 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
803 TemplateArgs, Ty, VK, OK);
804 SemaRef.MarkMemberReferenced(E);
805 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000806}
807
808ExprResult
809Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
810 SourceLocation OpLoc, bool IsArrow,
811 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000812 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000813 NamedDecl *FirstQualifierInScope,
814 LookupResult &R,
815 const TemplateArgumentListInfo *TemplateArgs,
816 bool SuppressQualifierCheck) {
817 QualType BaseType = BaseExprType;
818 if (IsArrow) {
819 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000820 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000821 }
822 R.setBaseObjectType(BaseType);
823
824 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
825 DeclarationName MemberName = MemberNameInfo.getName();
826 SourceLocation MemberLoc = MemberNameInfo.getLoc();
827
828 if (R.isAmbiguous())
829 return ExprError();
830
831 if (R.empty()) {
832 // Rederive where we looked up.
833 DeclContext *DC = (SS.isSet()
834 ? computeDeclContext(SS, false)
835 : BaseType->getAs<RecordType>()->getDecl());
836
837 Diag(R.getNameLoc(), diag::err_no_member)
838 << MemberName << DC
839 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
840 return ExprError();
841 }
842
843 // Diagnose lookups that find only declarations from a non-base
844 // type. This is possible for either qualified lookups (which may
845 // have been qualified with an unrelated type) or implicit member
846 // expressions (which were found with unqualified lookup and thus
847 // may have come from an enclosing scope). Note that it's okay for
848 // lookup to find declarations from a non-base type as long as those
849 // aren't the ones picked by overload resolution.
850 if ((SS.isSet() || !BaseExpr ||
851 (isa<CXXThisExpr>(BaseExpr) &&
852 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
853 !SuppressQualifierCheck &&
854 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
855 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000856
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000857 // Construct an unresolved result if we in fact got an unresolved
858 // result.
859 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
860 // Suppress any lookup-related diagnostics; we'll do these when we
861 // pick a member.
862 R.suppressDiagnostics();
863
864 UnresolvedMemberExpr *MemExpr
865 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
866 BaseExpr, BaseExprType,
867 IsArrow, OpLoc,
868 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000869 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000870 TemplateArgs, R.begin(), R.end());
871
872 return Owned(MemExpr);
873 }
874
875 assert(R.isSingleResult());
876 DeclAccessPair FoundDecl = R.begin().getPair();
877 NamedDecl *MemberDecl = R.getFoundDecl();
878
879 // FIXME: diagnose the presence of template arguments now.
880
881 // If the decl being referenced had an error, return an error for this
882 // sub-expr without emitting another error, in order to avoid cascading
883 // error cases.
884 if (MemberDecl->isInvalidDecl())
885 return ExprError();
886
887 // Handle the implicit-member-access case.
888 if (!BaseExpr) {
889 // If this is not an instance member, convert to a non-member access.
890 if (!MemberDecl->isCXXInstanceMember())
891 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
892
893 SourceLocation Loc = R.getNameLoc();
894 if (SS.getRange().isValid())
895 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000896 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000897 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
898 }
899
900 bool ShouldCheckUse = true;
901 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
902 // Don't diagnose the use of a virtual member function unless it's
903 // explicitly qualified.
904 if (MD->isVirtual() && !SS.isSet())
905 ShouldCheckUse = false;
906 }
907
908 // Check the use of this member.
909 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
910 Owned(BaseExpr);
911 return ExprError();
912 }
913
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000914 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
915 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
916 SS, FD, FoundDecl, MemberNameInfo);
917
918 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
919 // We may have found a field within an anonymous union or struct
920 // (C++ [class.union]).
921 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
922 BaseExpr, OpLoc);
923
924 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000925 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
926 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000927 Var->getType().getNonReferenceType(),
928 VK_LValue, OK_Ordinary));
929 }
930
931 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
932 ExprValueKind valueKind;
933 QualType type;
934 if (MemberFn->isInstance()) {
935 valueKind = VK_RValue;
936 type = Context.BoundMemberTy;
937 } else {
938 valueKind = VK_LValue;
939 type = MemberFn->getType();
940 }
941
Eli Friedman5f2987c2012-02-02 03:46:19 +0000942 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
943 TemplateKWLoc, MemberFn, FoundDecl,
944 MemberNameInfo, type, valueKind,
945 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000946 }
947 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
948
949 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000950 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
951 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000952 Enum->getType(), VK_RValue, OK_Ordinary));
953 }
954
955 Owned(BaseExpr);
956
957 // We found something that we didn't expect. Complain.
958 if (isa<TypeDecl>(MemberDecl))
959 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
960 << MemberName << BaseType << int(IsArrow);
961 else
962 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
963 << MemberName << BaseType << int(IsArrow);
964
965 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
966 << MemberName;
967 R.suppressDiagnostics();
968 return ExprError();
969}
970
971/// Given that normal member access failed on the given expression,
972/// and given that the expression's type involves builtin-id or
973/// builtin-Class, decide whether substituting in the redefinition
974/// types would be profitable. The redefinition type is whatever
975/// this translation unit tried to typedef to id/Class; we store
976/// it to the side and then re-use it in places like this.
977static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
978 const ObjCObjectPointerType *opty
979 = base.get()->getType()->getAs<ObjCObjectPointerType>();
980 if (!opty) return false;
981
982 const ObjCObjectType *ty = opty->getObjectType();
983
984 QualType redef;
985 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000986 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000987 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000988 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000989 } else {
990 return false;
991 }
992
993 // Do the substitution as long as the redefinition type isn't just a
994 // possibly-qualified pointer to builtin-id or builtin-Class again.
995 opty = redef->getAs<ObjCObjectPointerType>();
996 if (opty && !opty->getObjectType()->getInterface() != 0)
997 return false;
998
999 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1000 return true;
1001}
1002
John McCall6dbba4f2011-10-11 23:14:30 +00001003static bool isRecordType(QualType T) {
1004 return T->isRecordType();
1005}
1006static bool isPointerToRecordType(QualType T) {
1007 if (const PointerType *PT = T->getAs<PointerType>())
1008 return PT->getPointeeType()->isRecordType();
1009 return false;
1010}
1011
Richard Smith9138b4e2011-10-26 19:06:56 +00001012/// Perform conversions on the LHS of a member access expression.
1013ExprResult
1014Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001015 if (IsArrow && !Base->getType()->isFunctionType())
1016 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001017
Eli Friedman059d5782012-01-13 02:20:01 +00001018 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001019}
1020
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001021/// Look up the given member of the given non-type-dependent
1022/// expression. This can return in one of two ways:
1023/// * If it returns a sentinel null-but-valid result, the caller will
1024/// assume that lookup was performed and the results written into
1025/// the provided structure. It will take over from there.
1026/// * Otherwise, the returned expression will be produced in place of
1027/// an ordinary member expression.
1028///
1029/// The ObjCImpDecl bit is a gross hack that will need to be properly
1030/// fixed for ObjC++.
1031ExprResult
1032Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1033 bool &IsArrow, SourceLocation OpLoc,
1034 CXXScopeSpec &SS,
1035 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1036 assert(BaseExpr.get() && "no base expression");
1037
1038 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001039 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001040 if (BaseExpr.isInvalid())
1041 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001042
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001043 QualType BaseType = BaseExpr.get()->getType();
1044 assert(!BaseType->isDependentType());
1045
1046 DeclarationName MemberName = R.getLookupName();
1047 SourceLocation MemberLoc = R.getNameLoc();
1048
1049 // For later type-checking purposes, turn arrow accesses into dot
1050 // accesses. The only access type we support that doesn't follow
1051 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1052 // and those never use arrows, so this is unaffected.
1053 if (IsArrow) {
1054 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1055 BaseType = Ptr->getPointeeType();
1056 else if (const ObjCObjectPointerType *Ptr
1057 = BaseType->getAs<ObjCObjectPointerType>())
1058 BaseType = Ptr->getPointeeType();
1059 else if (BaseType->isRecordType()) {
1060 // Recover from arrow accesses to records, e.g.:
1061 // struct MyRecord foo;
1062 // foo->bar
1063 // This is actually well-formed in C++ if MyRecord has an
1064 // overloaded operator->, but that should have been dealt with
1065 // by now.
1066 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1067 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1068 << FixItHint::CreateReplacement(OpLoc, ".");
1069 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001070 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001071 goto fail;
1072 } else {
1073 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1074 << BaseType << BaseExpr.get()->getSourceRange();
1075 return ExprError();
1076 }
1077 }
1078
1079 // Handle field access to simple records.
1080 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1081 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1082 RTy, OpLoc, SS, HasTemplateArgs))
1083 return ExprError();
1084
1085 // Returning valid-but-null is how we indicate to the caller that
1086 // the lookup result was filled in.
1087 return Owned((Expr*) 0);
1088 }
1089
1090 // Handle ivar access to Objective-C objects.
1091 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001092 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001093 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1094 << 1 << SS.getScopeRep()
1095 << FixItHint::CreateRemoval(SS.getRange());
1096 SS.clear();
1097 }
1098
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001099 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1100
1101 // There are three cases for the base type:
1102 // - builtin id (qualified or unqualified)
1103 // - builtin Class (qualified or unqualified)
1104 // - an interface
1105 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1106 if (!IDecl) {
1107 if (getLangOptions().ObjCAutoRefCount &&
1108 (OTy->isObjCId() || OTy->isObjCClass()))
1109 goto fail;
1110 // There's an implicit 'isa' ivar on all objects.
1111 // But we only actually find it this way on objects of type 'id',
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001112 // apparently.ghjg
1113 if (OTy->isObjCId() && Member->isStr("isa")) {
1114 Diag(MemberLoc, diag::warn_objc_isa_use);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001115 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1116 Context.getObjCClassType()));
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001117 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001118
1119 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1120 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1121 ObjCImpDecl, HasTemplateArgs);
1122 goto fail;
1123 }
1124
Douglas Gregord07cc362012-01-02 17:18:37 +00001125 if (RequireCompleteType(OpLoc, BaseType,
1126 PDiag(diag::err_typecheck_incomplete_tag)
1127 << BaseExpr.get()->getSourceRange()))
1128 return ExprError();
1129
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001130 ObjCInterfaceDecl *ClassDeclared;
1131 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1132
1133 if (!IV) {
1134 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001135 DeclFilterCCC<ObjCIvarDecl> Validator;
1136 Validator.IsObjCIvarLookup = IsArrow;
1137 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1138 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001139 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001140 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001141 Diag(R.getNameLoc(),
1142 diag::err_typecheck_member_reference_ivar_suggest)
1143 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1144 << FixItHint::CreateReplacement(R.getNameLoc(),
1145 IV->getNameAsString());
1146 Diag(IV->getLocation(), diag::note_previous_decl)
1147 << IV->getDeclName();
1148 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001149 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1150 Diag(MemberLoc,
1151 diag::err_property_found_suggest)
1152 << Member << BaseExpr.get()->getType()
1153 << FixItHint::CreateReplacement(OpLoc, ".");
1154 return ExprError();
1155 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001156
1157 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1158 << IDecl->getDeclName() << MemberName
1159 << BaseExpr.get()->getSourceRange();
1160 return ExprError();
1161 }
1162 }
1163
1164 // If the decl being referenced had an error, return an error for this
1165 // sub-expr without emitting another error, in order to avoid cascading
1166 // error cases.
1167 if (IV->isInvalidDecl())
1168 return ExprError();
1169
1170 // Check whether we can reference this field.
1171 if (DiagnoseUseOfDecl(IV, MemberLoc))
1172 return ExprError();
1173 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1174 IV->getAccessControl() != ObjCIvarDecl::Package) {
1175 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1176 if (ObjCMethodDecl *MD = getCurMethodDecl())
1177 ClassOfMethodDecl = MD->getClassInterface();
1178 else if (ObjCImpDecl && getCurFunctionDecl()) {
1179 // Case of a c-function declared inside an objc implementation.
1180 // FIXME: For a c-style function nested inside an objc implementation
1181 // class, there is no implementation context available, so we pass
1182 // down the context as argument to this routine. Ideally, this context
1183 // need be passed down in the AST node and somehow calculated from the
1184 // AST for a function decl.
1185 if (ObjCImplementationDecl *IMPD =
1186 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1187 ClassOfMethodDecl = IMPD->getClassInterface();
1188 else if (ObjCCategoryImplDecl* CatImplClass =
1189 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1190 ClassOfMethodDecl = CatImplClass->getClassInterface();
1191 }
1192
1193 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Douglas Gregor60ef3082011-12-15 00:29:59 +00001194 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1195 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001196 Diag(MemberLoc, diag::error_private_ivar_access)
1197 << IV->getDeclName();
1198 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1199 // @protected
1200 Diag(MemberLoc, diag::error_protected_ivar_access)
1201 << IV->getDeclName();
1202 }
1203 if (getLangOptions().ObjCAutoRefCount) {
1204 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1205 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1206 if (UO->getOpcode() == UO_Deref)
1207 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1208
1209 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1210 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1211 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1212 }
1213
1214 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1215 MemberLoc, BaseExpr.take(),
1216 IsArrow));
1217 }
1218
1219 // Objective-C property access.
1220 const ObjCObjectPointerType *OPT;
1221 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001222 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001223 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1224 << 0 << SS.getScopeRep()
1225 << FixItHint::CreateRemoval(SS.getRange());
1226 SS.clear();
1227 }
1228
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001229 // This actually uses the base as an r-value.
1230 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1231 if (BaseExpr.isInvalid())
1232 return ExprError();
1233
1234 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1235
1236 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1237
1238 const ObjCObjectType *OT = OPT->getObjectType();
1239
1240 // id, with and without qualifiers.
1241 if (OT->isObjCId()) {
1242 // Check protocols on qualified interfaces.
1243 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1244 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1245 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1246 // Check the use of this declaration
1247 if (DiagnoseUseOfDecl(PD, MemberLoc))
1248 return ExprError();
1249
John McCall3c3b7f92011-10-25 17:37:35 +00001250 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1251 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001252 VK_LValue,
1253 OK_ObjCProperty,
1254 MemberLoc,
1255 BaseExpr.take()));
1256 }
1257
1258 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1259 // Check the use of this method.
1260 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1261 return ExprError();
1262 Selector SetterSel =
1263 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1264 PP.getSelectorTable(), Member);
1265 ObjCMethodDecl *SMD = 0;
1266 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1267 SetterSel, Context))
1268 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001269
John McCall3c3b7f92011-10-25 17:37:35 +00001270 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1271 Context.PseudoObjectTy,
1272 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001273 MemberLoc, BaseExpr.take()));
1274 }
1275 }
1276 // Use of id.member can only be for a property reference. Do not
1277 // use the 'id' redefinition in this case.
1278 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1279 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1280 ObjCImpDecl, HasTemplateArgs);
1281
1282 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1283 << MemberName << BaseType);
1284 }
1285
1286 // 'Class', unqualified only.
1287 if (OT->isObjCClass()) {
1288 // Only works in a method declaration (??!).
1289 ObjCMethodDecl *MD = getCurMethodDecl();
1290 if (!MD) {
1291 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1292 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1293 ObjCImpDecl, HasTemplateArgs);
1294
1295 goto fail;
1296 }
1297
1298 // Also must look for a getter name which uses property syntax.
1299 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1300 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1301 ObjCMethodDecl *Getter;
1302 if ((Getter = IFace->lookupClassMethod(Sel))) {
1303 // Check the use of this method.
1304 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1305 return ExprError();
1306 } else
1307 Getter = IFace->lookupPrivateMethod(Sel, false);
1308 // If we found a getter then this may be a valid dot-reference, we
1309 // will look for the matching setter, in case it is needed.
1310 Selector SetterSel =
1311 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1312 PP.getSelectorTable(), Member);
1313 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1314 if (!Setter) {
1315 // If this reference is in an @implementation, also check for 'private'
1316 // methods.
1317 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1318 }
1319 // Look through local category implementations associated with the class.
1320 if (!Setter)
1321 Setter = IFace->getCategoryClassMethod(SetterSel);
1322
1323 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1324 return ExprError();
1325
1326 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001327 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001328 Context.PseudoObjectTy,
1329 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001330 MemberLoc, BaseExpr.take()));
1331 }
1332
1333 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1334 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1335 ObjCImpDecl, HasTemplateArgs);
1336
1337 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1338 << MemberName << BaseType);
1339 }
1340
1341 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001342 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1343 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001344 SourceLocation(), QualType(), false);
1345 }
1346
1347 // Handle 'field access' to vectors, such as 'V.xx'.
1348 if (BaseType->isExtVectorType()) {
1349 // FIXME: this expr should store IsArrow.
1350 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1351 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1352 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1353 Member, MemberLoc);
1354 if (ret.isNull())
1355 return ExprError();
1356
1357 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1358 *Member, MemberLoc));
1359 }
1360
1361 // Adjust builtin-sel to the appropriate redefinition type if that's
1362 // not just a pointer to builtin-sel again.
1363 if (IsArrow &&
1364 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001365 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1366 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1367 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001368 CK_BitCast);
1369 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1370 ObjCImpDecl, HasTemplateArgs);
1371 }
1372
1373 // Failure cases.
1374 fail:
1375
1376 // Recover from dot accesses to pointers, e.g.:
1377 // type *foo;
1378 // foo.bar
1379 // This is actually well-formed in two cases:
1380 // - 'type' is an Objective C type
1381 // - 'bar' is a pseudo-destructor name which happens to refer to
1382 // the appropriate pointer type
1383 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1384 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1385 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1386 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1387 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1388 << FixItHint::CreateReplacement(OpLoc, "->");
1389
1390 // Recurse as an -> access.
1391 IsArrow = true;
1392 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1393 ObjCImpDecl, HasTemplateArgs);
1394 }
1395 }
1396
1397 // If the user is trying to apply -> or . to a function name, it's probably
1398 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001399 if (tryToRecoverWithCall(BaseExpr,
1400 PDiag(diag::err_member_reference_needs_call),
1401 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001402 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001403 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001404 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001405 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1406 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1407 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001408 }
1409
1410 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1411 << BaseType << BaseExpr.get()->getSourceRange();
1412
1413 return ExprError();
1414}
1415
1416/// The main callback when the parser finds something like
1417/// expression . [nested-name-specifier] identifier
1418/// expression -> [nested-name-specifier] identifier
1419/// where 'identifier' encompasses a fairly broad spectrum of
1420/// possibilities, including destructor and operator references.
1421///
1422/// \param OpKind either tok::arrow or tok::period
1423/// \param HasTrailingLParen whether the next token is '(', which
1424/// is used to diagnose mis-uses of special members that can
1425/// only be called
1426/// \param ObjCImpDecl the current ObjC @implementation decl;
1427/// this is an ugly hack around the fact that ObjC @implementations
1428/// aren't properly put in the context chain
1429ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1430 SourceLocation OpLoc,
1431 tok::TokenKind OpKind,
1432 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001433 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001434 UnqualifiedId &Id,
1435 Decl *ObjCImpDecl,
1436 bool HasTrailingLParen) {
1437 if (SS.isSet() && SS.isInvalid())
1438 return ExprError();
1439
1440 // Warn about the explicit constructor calls Microsoft extension.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001441 if (getLangOptions().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001442 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1443 Diag(Id.getSourceRange().getBegin(),
1444 diag::ext_ms_explicit_constructor_call);
1445
1446 TemplateArgumentListInfo TemplateArgsBuffer;
1447
1448 // Decompose the name into its component parts.
1449 DeclarationNameInfo NameInfo;
1450 const TemplateArgumentListInfo *TemplateArgs;
1451 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1452 NameInfo, TemplateArgs);
1453
1454 DeclarationName Name = NameInfo.getName();
1455 bool IsArrow = (OpKind == tok::arrow);
1456
1457 NamedDecl *FirstQualifierInScope
1458 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1459 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1460
1461 // This is a postfix expression, so get rid of ParenListExprs.
1462 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1463 if (Result.isInvalid()) return ExprError();
1464 Base = Result.take();
1465
1466 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1467 isDependentScopeSpecifier(SS)) {
1468 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1469 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001470 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001471 NameInfo, TemplateArgs);
1472 } else {
1473 LookupResult R(*this, NameInfo, LookupMemberName);
1474 ExprResult BaseResult = Owned(Base);
1475 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1476 SS, ObjCImpDecl, TemplateArgs != 0);
1477 if (BaseResult.isInvalid())
1478 return ExprError();
1479 Base = BaseResult.take();
1480
1481 if (Result.isInvalid()) {
1482 Owned(Base);
1483 return ExprError();
1484 }
1485
1486 if (Result.get()) {
1487 // The only way a reference to a destructor can be used is to
1488 // immediately call it, which falls into this case. If the
1489 // next token is not a '(', produce a diagnostic and build the
1490 // call now.
1491 if (!HasTrailingLParen &&
1492 Id.getKind() == UnqualifiedId::IK_DestructorName)
1493 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1494
1495 return move(Result);
1496 }
1497
1498 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001499 OpLoc, IsArrow, SS, TemplateKWLoc,
1500 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001501 }
1502
1503 return move(Result);
1504}
1505
1506static ExprResult
1507BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1508 const CXXScopeSpec &SS, FieldDecl *Field,
1509 DeclAccessPair FoundDecl,
1510 const DeclarationNameInfo &MemberNameInfo) {
1511 // x.a is an l-value if 'a' has a reference type. Otherwise:
1512 // x.a is an l-value/x-value/pr-value if the base is (and note
1513 // that *x is always an l-value), except that if the base isn't
1514 // an ordinary object then we must have an rvalue.
1515 ExprValueKind VK = VK_LValue;
1516 ExprObjectKind OK = OK_Ordinary;
1517 if (!IsArrow) {
1518 if (BaseExpr->getObjectKind() == OK_Ordinary)
1519 VK = BaseExpr->getValueKind();
1520 else
1521 VK = VK_RValue;
1522 }
1523 if (VK != VK_RValue && Field->isBitField())
1524 OK = OK_BitField;
1525
1526 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1527 QualType MemberType = Field->getType();
1528 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1529 MemberType = Ref->getPointeeType();
1530 VK = VK_LValue;
1531 } else {
1532 QualType BaseType = BaseExpr->getType();
1533 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1534
1535 Qualifiers BaseQuals = BaseType.getQualifiers();
1536
1537 // GC attributes are never picked up by members.
1538 BaseQuals.removeObjCGCAttr();
1539
1540 // CVR attributes from the base are picked up by members,
1541 // except that 'mutable' members don't pick up 'const'.
1542 if (Field->isMutable()) BaseQuals.removeConst();
1543
1544 Qualifiers MemberQuals
1545 = S.Context.getCanonicalType(MemberType).getQualifiers();
1546
1547 // TR 18037 does not allow fields to be declared with address spaces.
1548 assert(!MemberQuals.hasAddressSpace());
1549
1550 Qualifiers Combined = BaseQuals + MemberQuals;
1551 if (Combined != MemberQuals)
1552 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1553 }
1554
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001555 ExprResult Base =
1556 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1557 FoundDecl, Field);
1558 if (Base.isInvalid())
1559 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001560 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001561 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001562 Field, FoundDecl, MemberNameInfo,
1563 MemberType, VK, OK));
1564}
1565
1566/// Builds an implicit member access expression. The current context
1567/// is known to be an instance method, and the given unqualified lookup
1568/// set is known to contain only instance members, at least one of which
1569/// is from an appropriate type.
1570ExprResult
1571Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001572 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001573 LookupResult &R,
1574 const TemplateArgumentListInfo *TemplateArgs,
1575 bool IsKnownInstance) {
1576 assert(!R.empty() && !R.isAmbiguous());
1577
1578 SourceLocation loc = R.getNameLoc();
1579
1580 // We may have found a field within an anonymous union or struct
1581 // (C++ [class.union]).
1582 // FIXME: template-ids inside anonymous structs?
1583 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1584 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1585
1586 // If this is known to be an instance access, go ahead and build an
1587 // implicit 'this' expression now.
1588 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001589 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001590 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1591
1592 Expr *baseExpr = 0; // null signifies implicit access
1593 if (IsKnownInstance) {
1594 SourceLocation Loc = R.getNameLoc();
1595 if (SS.getRange().isValid())
1596 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001597 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001598 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1599 }
1600
1601 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1602 /*OpLoc*/ SourceLocation(),
1603 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001604 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001605 /*FirstQualifierInScope*/ 0,
1606 R, TemplateArgs);
1607}