blob: 54296942d0d4bcb7c90f65795c739e80d44bbe4d [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
141 // If the current context is not an instance method, it can't be
142 // an implicit member reference.
143 if (isStaticContext) {
144 if (hasNonInstance)
145 return IMA_Mixed_StaticContext;
146
Eli Friedman9bc291d2012-01-18 03:53:45 +0000147 if (SemaRef.getLangOptions().CPlusPlus0x && isField) {
Richard Smithf6702a32011-12-20 02:08:33 +0000148 // C++11 [expr.prim.general]p12:
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000149 // An id-expression that denotes a non-static data member or non-static
150 // member function of a class can only be used:
151 // (...)
152 // - if that id-expression denotes a non-static data member and it
153 // appears in an unevaluated operand.
154 const Sema::ExpressionEvaluationContextRecord& record
155 = SemaRef.ExprEvalContexts.back();
Eli Friedman9bc291d2012-01-18 03:53:45 +0000156 if (record.Context == Sema::Unevaluated)
Eli Friedmanef331b72012-01-20 01:26:23 +0000157 return IMA_Field_Uneval_Context;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000158 }
159
160 return IMA_Error_StaticContext;
161 }
162
163 CXXRecordDecl *contextClass;
164 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
165 contextClass = MD->getParent()->getCanonicalDecl();
166 else
167 contextClass = cast<CXXRecordDecl>(DC);
168
169 // [class.mfct.non-static]p3:
170 // ...is used in the body of a non-static member function of class X,
171 // if name lookup (3.4.1) resolves the name in the id-expression to a
172 // non-static non-type member of some class C [...]
173 // ...if C is not X or a base class of X, the class member access expression
174 // is ill-formed.
175 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000176 contextClass->getCanonicalDecl() !=
177 R.getNamingClass()->getCanonicalDecl() &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000178 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
179 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
180
181 // If we can prove that the current context is unrelated to all the
182 // declaring classes, it can't be an implicit member reference (in
183 // which case it's an error if any of those members are selected).
184 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
185 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
186
187 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
188}
189
190/// Diagnose a reference to a field with no object available.
191static void DiagnoseInstanceReference(Sema &SemaRef,
192 const CXXScopeSpec &SS,
193 NamedDecl *rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000194 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000195 SourceLocation Loc = nameInfo.getLoc();
196 SourceRange Range(Loc);
197 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
198
199 if (isa<FieldDecl>(rep) || isa<IndirectFieldDecl>(rep)) {
200 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(SemaRef.CurContext)) {
201 if (MD->isStatic()) {
202 // "invalid use of member 'x' in static member function"
Eli Friedmanef331b72012-01-20 01:26:23 +0000203 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
204 << Range << nameInfo.getName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000205 return;
206 }
207 }
Eli Friedman9bc291d2012-01-18 03:53:45 +0000208
Eli Friedmanef331b72012-01-20 01:26:23 +0000209 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
210 << nameInfo.getName() << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000211 return;
212 }
Eli Friedman9bc291d2012-01-18 03:53:45 +0000213
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000214 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
215}
216
217/// Builds an expression which might be an implicit member expression.
218ExprResult
219Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000220 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000221 LookupResult &R,
222 const TemplateArgumentListInfo *TemplateArgs) {
223 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
224 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000225 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000226
227 case IMA_Mixed:
228 case IMA_Mixed_Unrelated:
229 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000230 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000231
232 case IMA_Static:
233 case IMA_Mixed_StaticContext:
234 case IMA_Unresolved_StaticContext:
Eli Friedmanef331b72012-01-20 01:26:23 +0000235 case IMA_Field_Uneval_Context:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000236 if (TemplateArgs || TemplateKWLoc.isValid())
237 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000238 return BuildDeclarationNameExpr(SS, R, false);
239
240 case IMA_Error_StaticContext:
241 case IMA_Error_Unrelated:
242 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
243 R.getLookupNameInfo());
244 return ExprError();
245 }
246
247 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000248}
249
250/// Check an ext-vector component access expression.
251///
252/// VK should be set in advance to the value kind of the base
253/// expression.
254static QualType
255CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
256 SourceLocation OpLoc, const IdentifierInfo *CompName,
257 SourceLocation CompLoc) {
258 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
259 // see FIXME there.
260 //
261 // FIXME: This logic can be greatly simplified by splitting it along
262 // halving/not halving and reworking the component checking.
263 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
264
265 // The vector accessor can't exceed the number of elements.
266 const char *compStr = CompName->getNameStart();
267
268 // This flag determines whether or not the component is one of the four
269 // special names that indicate a subset of exactly half the elements are
270 // to be selected.
271 bool HalvingSwizzle = false;
272
273 // This flag determines whether or not CompName has an 's' char prefix,
274 // indicating that it is a string of hex values to be used as vector indices.
275 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
276
277 bool HasRepeated = false;
278 bool HasIndex[16] = {};
279
280 int Idx;
281
282 // Check that we've found one of the special components, or that the component
283 // names must come from the same set.
284 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
285 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
286 HalvingSwizzle = true;
287 } else if (!HexSwizzle &&
288 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
289 do {
290 if (HasIndex[Idx]) HasRepeated = true;
291 HasIndex[Idx] = true;
292 compStr++;
293 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
294 } else {
295 if (HexSwizzle) compStr++;
296 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
297 if (HasIndex[Idx]) HasRepeated = true;
298 HasIndex[Idx] = true;
299 compStr++;
300 }
301 }
302
303 if (!HalvingSwizzle && *compStr) {
304 // We didn't get to the end of the string. This means the component names
305 // didn't come from the same set *or* we encountered an illegal name.
306 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000307 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000308 return QualType();
309 }
310
311 // Ensure no component accessor exceeds the width of the vector type it
312 // operates on.
313 if (!HalvingSwizzle) {
314 compStr = CompName->getNameStart();
315
316 if (HexSwizzle)
317 compStr++;
318
319 while (*compStr) {
320 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
321 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
322 << baseType << SourceRange(CompLoc);
323 return QualType();
324 }
325 }
326 }
327
328 // The component accessor looks fine - now we need to compute the actual type.
329 // The vector type is implied by the component accessor. For example,
330 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
331 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
332 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
333 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
334 : CompName->getLength();
335 if (HexSwizzle)
336 CompSize--;
337
338 if (CompSize == 1)
339 return vecType->getElementType();
340
341 if (HasRepeated) VK = VK_RValue;
342
343 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
344 // Now look up the TypeDefDecl from the vector type. Without this,
345 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000346 for (Sema::ExtVectorDeclsType::iterator
347 I = S.ExtVectorDecls.begin(S.ExternalSource),
348 E = S.ExtVectorDecls.end();
349 I != E; ++I) {
350 if ((*I)->getUnderlyingType() == VT)
351 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000352 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000353
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000354 return VT; // should never get here (a typedef type should always be found).
355}
356
357static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
358 IdentifierInfo *Member,
359 const Selector &Sel,
360 ASTContext &Context) {
361 if (Member)
362 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
363 return PD;
364 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
365 return OMD;
366
367 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
368 E = PDecl->protocol_end(); I != E; ++I) {
369 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
370 Context))
371 return D;
372 }
373 return 0;
374}
375
376static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
377 IdentifierInfo *Member,
378 const Selector &Sel,
379 ASTContext &Context) {
380 // Check protocols on qualified interfaces.
381 Decl *GDecl = 0;
382 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
383 E = QIdTy->qual_end(); I != E; ++I) {
384 if (Member)
385 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
386 GDecl = PD;
387 break;
388 }
389 // Also must look for a getter or setter name which uses property syntax.
390 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
391 GDecl = OMD;
392 break;
393 }
394 }
395 if (!GDecl) {
396 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
397 E = QIdTy->qual_end(); I != E; ++I) {
398 // Search in the protocol-qualifier list of current protocol.
399 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
400 Context);
401 if (GDecl)
402 return GDecl;
403 }
404 }
405 return GDecl;
406}
407
408ExprResult
409Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
410 bool IsArrow, SourceLocation OpLoc,
411 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000412 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000413 NamedDecl *FirstQualifierInScope,
414 const DeclarationNameInfo &NameInfo,
415 const TemplateArgumentListInfo *TemplateArgs) {
416 // Even in dependent contexts, try to diagnose base expressions with
417 // obviously wrong types, e.g.:
418 //
419 // T* t;
420 // t.f;
421 //
422 // In Obj-C++, however, the above expression is valid, since it could be
423 // accessing the 'f' property if T is an Obj-C interface. The extra check
424 // allows this, while still reporting an error if T is a struct pointer.
425 if (!IsArrow) {
426 const PointerType *PT = BaseType->getAs<PointerType>();
427 if (PT && (!getLangOptions().ObjC1 ||
428 PT->getPointeeType()->isRecordType())) {
429 assert(BaseExpr && "cannot happen with implicit member accesses");
430 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
431 << BaseType << BaseExpr->getSourceRange();
432 return ExprError();
433 }
434 }
435
436 assert(BaseType->isDependentType() ||
437 NameInfo.getName().isDependentName() ||
438 isDependentScopeSpecifier(SS));
439
440 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
441 // must have pointer type, and the accessed type is the pointee.
442 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
443 IsArrow, OpLoc,
444 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000445 TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000446 FirstQualifierInScope,
447 NameInfo, TemplateArgs));
448}
449
450/// We know that the given qualified member reference points only to
451/// declarations which do not belong to the static type of the base
452/// expression. Diagnose the problem.
453static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
454 Expr *BaseExpr,
455 QualType BaseType,
456 const CXXScopeSpec &SS,
457 NamedDecl *rep,
458 const DeclarationNameInfo &nameInfo) {
459 // If this is an implicit member access, use a different set of
460 // diagnostics.
461 if (!BaseExpr)
462 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
463
464 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
465 << SS.getRange() << rep << BaseType;
466}
467
468// Check whether the declarations we found through a nested-name
469// specifier in a member expression are actually members of the base
470// type. The restriction here is:
471//
472// C++ [expr.ref]p2:
473// ... In these cases, the id-expression shall name a
474// member of the class or of one of its base classes.
475//
476// So it's perfectly legitimate for the nested-name specifier to name
477// an unrelated class, and for us to find an overload set including
478// decls from classes which are not superclasses, as long as the decl
479// we actually pick through overload resolution is from a superclass.
480bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
481 QualType BaseType,
482 const CXXScopeSpec &SS,
483 const LookupResult &R) {
484 const RecordType *BaseRT = BaseType->getAs<RecordType>();
485 if (!BaseRT) {
486 // We can't check this yet because the base type is still
487 // dependent.
488 assert(BaseType->isDependentType());
489 return false;
490 }
491 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
492
493 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
494 // If this is an implicit member reference and we find a
495 // non-instance member, it's not an error.
496 if (!BaseExpr && !(*I)->isCXXInstanceMember())
497 return false;
498
499 // Note that we use the DC of the decl, not the underlying decl.
500 DeclContext *DC = (*I)->getDeclContext();
501 while (DC->isTransparentContext())
502 DC = DC->getParent();
503
504 if (!DC->isRecord())
505 continue;
506
507 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
508 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
509
510 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
511 return false;
512 }
513
514 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
515 R.getRepresentativeDecl(),
516 R.getLookupNameInfo());
517 return true;
518}
519
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000520namespace {
521
522// Callback to only accept typo corrections that are either a ValueDecl or a
523// FunctionTemplateDecl.
524class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
525 public:
526 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
527 NamedDecl *ND = candidate.getCorrectionDecl();
528 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
529 }
530};
531
532}
533
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000534static bool
535LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
536 SourceRange BaseRange, const RecordType *RTy,
537 SourceLocation OpLoc, CXXScopeSpec &SS,
538 bool HasTemplateArgs) {
539 RecordDecl *RDecl = RTy->getDecl();
540 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
541 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
542 << BaseRange))
543 return true;
544
545 if (HasTemplateArgs) {
546 // LookupTemplateName doesn't expect these both to exist simultaneously.
547 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
548
549 bool MOUS;
550 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
551 return false;
552 }
553
554 DeclContext *DC = RDecl;
555 if (SS.isSet()) {
556 // If the member name was a qualified-id, look into the
557 // nested-name-specifier.
558 DC = SemaRef.computeDeclContext(SS, false);
559
560 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
561 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
562 << SS.getRange() << DC;
563 return true;
564 }
565
566 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
567
568 if (!isa<TypeDecl>(DC)) {
569 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
570 << DC << SS.getRange();
571 return true;
572 }
573 }
574
575 // The record definition is complete, now look up the member.
576 SemaRef.LookupQualifiedName(R, DC);
577
578 if (!R.empty())
579 return false;
580
581 // We didn't find anything with the given name, so try to correct
582 // for typos.
583 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000584 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000585 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
586 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000587 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000588 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000589 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000590 std::string CorrectedStr(
591 Corrected.getAsString(SemaRef.getLangOptions()));
592 std::string CorrectedQuotedStr(
593 Corrected.getQuoted(SemaRef.getLangOptions()));
594 R.setLookupName(Corrected.getCorrection());
595 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000596 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000597 << Name << DC << CorrectedQuotedStr << SS.getRange()
598 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
599 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
600 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000601 }
602
603 return false;
604}
605
606ExprResult
607Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
608 SourceLocation OpLoc, bool IsArrow,
609 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000610 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000611 NamedDecl *FirstQualifierInScope,
612 const DeclarationNameInfo &NameInfo,
613 const TemplateArgumentListInfo *TemplateArgs) {
614 if (BaseType->isDependentType() ||
615 (SS.isSet() && isDependentScopeSpecifier(SS)))
616 return ActOnDependentMemberExpr(Base, BaseType,
617 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000618 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000619 NameInfo, TemplateArgs);
620
621 LookupResult R(*this, NameInfo, LookupMemberName);
622
623 // Implicit member accesses.
624 if (!Base) {
625 QualType RecordTy = BaseType;
626 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
627 if (LookupMemberExprInRecord(*this, R, SourceRange(),
628 RecordTy->getAs<RecordType>(),
629 OpLoc, SS, TemplateArgs != 0))
630 return ExprError();
631
632 // Explicit member accesses.
633 } else {
634 ExprResult BaseResult = Owned(Base);
635 ExprResult Result =
636 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
637 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
638
639 if (BaseResult.isInvalid())
640 return ExprError();
641 Base = BaseResult.take();
642
643 if (Result.isInvalid()) {
644 Owned(Base);
645 return ExprError();
646 }
647
648 if (Result.get())
649 return move(Result);
650
651 // LookupMemberExpr can modify Base, and thus change BaseType
652 BaseType = Base->getType();
653 }
654
655 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000656 OpLoc, IsArrow, SS, TemplateKWLoc,
657 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000658}
659
660static ExprResult
661BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
662 const CXXScopeSpec &SS, FieldDecl *Field,
663 DeclAccessPair FoundDecl,
664 const DeclarationNameInfo &MemberNameInfo);
665
666ExprResult
667Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
668 SourceLocation loc,
669 IndirectFieldDecl *indirectField,
670 Expr *baseObjectExpr,
671 SourceLocation opLoc) {
672 // First, build the expression that refers to the base object.
673
674 bool baseObjectIsPointer = false;
675 Qualifiers baseQuals;
676
677 // Case 1: the base of the indirect field is not a field.
678 VarDecl *baseVariable = indirectField->getVarDecl();
679 CXXScopeSpec EmptySS;
680 if (baseVariable) {
681 assert(baseVariable->getType()->isRecordType());
682
683 // In principle we could have a member access expression that
684 // accesses an anonymous struct/union that's a static member of
685 // the base object's class. However, under the current standard,
686 // static data members cannot be anonymous structs or unions.
687 // Supporting this is as easy as building a MemberExpr here.
688 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
689
690 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
691
692 ExprResult result
693 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
694 if (result.isInvalid()) return ExprError();
695
696 baseObjectExpr = result.take();
697 baseObjectIsPointer = false;
698 baseQuals = baseObjectExpr->getType().getQualifiers();
699
700 // Case 2: the base of the indirect field is a field and the user
701 // wrote a member expression.
702 } else if (baseObjectExpr) {
703 // The caller provided the base object expression. Determine
704 // whether its a pointer and whether it adds any qualifiers to the
705 // anonymous struct/union fields we're looking into.
706 QualType objectType = baseObjectExpr->getType();
707
708 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
709 baseObjectIsPointer = true;
710 objectType = ptr->getPointeeType();
711 } else {
712 baseObjectIsPointer = false;
713 }
714 baseQuals = objectType.getQualifiers();
715
716 // Case 3: the base of the indirect field is a field and we should
717 // build an implicit member access.
718 } else {
719 // We've found a member of an anonymous struct/union that is
720 // inside a non-anonymous struct/union, so in a well-formed
721 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000722 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000723 if (ThisTy.isNull()) {
724 Diag(loc, diag::err_invalid_member_use_in_static_method)
725 << indirectField->getDeclName();
726 return ExprError();
727 }
728
729 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000730 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000731 baseObjectExpr
732 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
733 baseObjectIsPointer = true;
734 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
735 }
736
737 // Build the implicit member references to the field of the
738 // anonymous struct/union.
739 Expr *result = baseObjectExpr;
740 IndirectFieldDecl::chain_iterator
741 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
742
743 // Build the first member access in the chain with full information.
744 if (!baseVariable) {
745 FieldDecl *field = cast<FieldDecl>(*FI);
746
747 // FIXME: use the real found-decl info!
748 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
749
750 // Make a nameInfo that properly uses the anonymous name.
751 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
752
753 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
754 EmptySS, field, foundDecl,
755 memberNameInfo).take();
756 baseObjectIsPointer = false;
757
758 // FIXME: check qualified member access
759 }
760
761 // In all cases, we should now skip the first declaration in the chain.
762 ++FI;
763
764 while (FI != FEnd) {
765 FieldDecl *field = cast<FieldDecl>(*FI++);
766
767 // FIXME: these are somewhat meaningless
768 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
769 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
770
771 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
772 (FI == FEnd? SS : EmptySS), field,
773 foundDecl, memberNameInfo).take();
774 }
775
776 return Owned(result);
777}
778
779/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000780static MemberExpr *BuildMemberExpr(Sema &SemaRef,
781 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000782 const CXXScopeSpec &SS,
783 SourceLocation TemplateKWLoc,
784 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000785 DeclAccessPair FoundDecl,
786 const DeclarationNameInfo &MemberNameInfo,
787 QualType Ty,
788 ExprValueKind VK, ExprObjectKind OK,
789 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000790 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000791 MemberExpr *E =
792 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
793 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
794 TemplateArgs, Ty, VK, OK);
795 SemaRef.MarkMemberReferenced(E);
796 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000797}
798
799ExprResult
800Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
801 SourceLocation OpLoc, bool IsArrow,
802 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000803 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000804 NamedDecl *FirstQualifierInScope,
805 LookupResult &R,
806 const TemplateArgumentListInfo *TemplateArgs,
807 bool SuppressQualifierCheck) {
808 QualType BaseType = BaseExprType;
809 if (IsArrow) {
810 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000811 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000812 }
813 R.setBaseObjectType(BaseType);
814
815 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
816 DeclarationName MemberName = MemberNameInfo.getName();
817 SourceLocation MemberLoc = MemberNameInfo.getLoc();
818
819 if (R.isAmbiguous())
820 return ExprError();
821
822 if (R.empty()) {
823 // Rederive where we looked up.
824 DeclContext *DC = (SS.isSet()
825 ? computeDeclContext(SS, false)
826 : BaseType->getAs<RecordType>()->getDecl());
827
828 Diag(R.getNameLoc(), diag::err_no_member)
829 << MemberName << DC
830 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
831 return ExprError();
832 }
833
834 // Diagnose lookups that find only declarations from a non-base
835 // type. This is possible for either qualified lookups (which may
836 // have been qualified with an unrelated type) or implicit member
837 // expressions (which were found with unqualified lookup and thus
838 // may have come from an enclosing scope). Note that it's okay for
839 // lookup to find declarations from a non-base type as long as those
840 // aren't the ones picked by overload resolution.
841 if ((SS.isSet() || !BaseExpr ||
842 (isa<CXXThisExpr>(BaseExpr) &&
843 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
844 !SuppressQualifierCheck &&
845 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
846 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000847
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000848 // Construct an unresolved result if we in fact got an unresolved
849 // result.
850 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
851 // Suppress any lookup-related diagnostics; we'll do these when we
852 // pick a member.
853 R.suppressDiagnostics();
854
855 UnresolvedMemberExpr *MemExpr
856 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
857 BaseExpr, BaseExprType,
858 IsArrow, OpLoc,
859 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000860 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000861 TemplateArgs, R.begin(), R.end());
862
863 return Owned(MemExpr);
864 }
865
866 assert(R.isSingleResult());
867 DeclAccessPair FoundDecl = R.begin().getPair();
868 NamedDecl *MemberDecl = R.getFoundDecl();
869
870 // FIXME: diagnose the presence of template arguments now.
871
872 // If the decl being referenced had an error, return an error for this
873 // sub-expr without emitting another error, in order to avoid cascading
874 // error cases.
875 if (MemberDecl->isInvalidDecl())
876 return ExprError();
877
878 // Handle the implicit-member-access case.
879 if (!BaseExpr) {
880 // If this is not an instance member, convert to a non-member access.
881 if (!MemberDecl->isCXXInstanceMember())
882 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
883
884 SourceLocation Loc = R.getNameLoc();
885 if (SS.getRange().isValid())
886 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000887 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000888 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
889 }
890
891 bool ShouldCheckUse = true;
892 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
893 // Don't diagnose the use of a virtual member function unless it's
894 // explicitly qualified.
895 if (MD->isVirtual() && !SS.isSet())
896 ShouldCheckUse = false;
897 }
898
899 // Check the use of this member.
900 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
901 Owned(BaseExpr);
902 return ExprError();
903 }
904
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000905 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
906 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
907 SS, FD, FoundDecl, MemberNameInfo);
908
909 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
910 // We may have found a field within an anonymous union or struct
911 // (C++ [class.union]).
912 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
913 BaseExpr, OpLoc);
914
915 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000916 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
917 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000918 Var->getType().getNonReferenceType(),
919 VK_LValue, OK_Ordinary));
920 }
921
922 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
923 ExprValueKind valueKind;
924 QualType type;
925 if (MemberFn->isInstance()) {
926 valueKind = VK_RValue;
927 type = Context.BoundMemberTy;
928 } else {
929 valueKind = VK_LValue;
930 type = MemberFn->getType();
931 }
932
Eli Friedman5f2987c2012-02-02 03:46:19 +0000933 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
934 TemplateKWLoc, MemberFn, FoundDecl,
935 MemberNameInfo, type, valueKind,
936 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000937 }
938 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
939
940 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000941 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
942 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000943 Enum->getType(), VK_RValue, OK_Ordinary));
944 }
945
946 Owned(BaseExpr);
947
948 // We found something that we didn't expect. Complain.
949 if (isa<TypeDecl>(MemberDecl))
950 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
951 << MemberName << BaseType << int(IsArrow);
952 else
953 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
954 << MemberName << BaseType << int(IsArrow);
955
956 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
957 << MemberName;
958 R.suppressDiagnostics();
959 return ExprError();
960}
961
962/// Given that normal member access failed on the given expression,
963/// and given that the expression's type involves builtin-id or
964/// builtin-Class, decide whether substituting in the redefinition
965/// types would be profitable. The redefinition type is whatever
966/// this translation unit tried to typedef to id/Class; we store
967/// it to the side and then re-use it in places like this.
968static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
969 const ObjCObjectPointerType *opty
970 = base.get()->getType()->getAs<ObjCObjectPointerType>();
971 if (!opty) return false;
972
973 const ObjCObjectType *ty = opty->getObjectType();
974
975 QualType redef;
976 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000977 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000978 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000979 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000980 } else {
981 return false;
982 }
983
984 // Do the substitution as long as the redefinition type isn't just a
985 // possibly-qualified pointer to builtin-id or builtin-Class again.
986 opty = redef->getAs<ObjCObjectPointerType>();
987 if (opty && !opty->getObjectType()->getInterface() != 0)
988 return false;
989
990 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
991 return true;
992}
993
John McCall6dbba4f2011-10-11 23:14:30 +0000994static bool isRecordType(QualType T) {
995 return T->isRecordType();
996}
997static bool isPointerToRecordType(QualType T) {
998 if (const PointerType *PT = T->getAs<PointerType>())
999 return PT->getPointeeType()->isRecordType();
1000 return false;
1001}
1002
Richard Smith9138b4e2011-10-26 19:06:56 +00001003/// Perform conversions on the LHS of a member access expression.
1004ExprResult
1005Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001006 if (IsArrow && !Base->getType()->isFunctionType())
1007 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001008
Eli Friedman059d5782012-01-13 02:20:01 +00001009 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001010}
1011
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001012/// Look up the given member of the given non-type-dependent
1013/// expression. This can return in one of two ways:
1014/// * If it returns a sentinel null-but-valid result, the caller will
1015/// assume that lookup was performed and the results written into
1016/// the provided structure. It will take over from there.
1017/// * Otherwise, the returned expression will be produced in place of
1018/// an ordinary member expression.
1019///
1020/// The ObjCImpDecl bit is a gross hack that will need to be properly
1021/// fixed for ObjC++.
1022ExprResult
1023Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1024 bool &IsArrow, SourceLocation OpLoc,
1025 CXXScopeSpec &SS,
1026 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1027 assert(BaseExpr.get() && "no base expression");
1028
1029 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001030 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001031 if (BaseExpr.isInvalid())
1032 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001033
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001034 QualType BaseType = BaseExpr.get()->getType();
1035 assert(!BaseType->isDependentType());
1036
1037 DeclarationName MemberName = R.getLookupName();
1038 SourceLocation MemberLoc = R.getNameLoc();
1039
1040 // For later type-checking purposes, turn arrow accesses into dot
1041 // accesses. The only access type we support that doesn't follow
1042 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1043 // and those never use arrows, so this is unaffected.
1044 if (IsArrow) {
1045 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1046 BaseType = Ptr->getPointeeType();
1047 else if (const ObjCObjectPointerType *Ptr
1048 = BaseType->getAs<ObjCObjectPointerType>())
1049 BaseType = Ptr->getPointeeType();
1050 else if (BaseType->isRecordType()) {
1051 // Recover from arrow accesses to records, e.g.:
1052 // struct MyRecord foo;
1053 // foo->bar
1054 // This is actually well-formed in C++ if MyRecord has an
1055 // overloaded operator->, but that should have been dealt with
1056 // by now.
1057 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1058 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1059 << FixItHint::CreateReplacement(OpLoc, ".");
1060 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001061 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001062 goto fail;
1063 } else {
1064 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1065 << BaseType << BaseExpr.get()->getSourceRange();
1066 return ExprError();
1067 }
1068 }
1069
1070 // Handle field access to simple records.
1071 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1072 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1073 RTy, OpLoc, SS, HasTemplateArgs))
1074 return ExprError();
1075
1076 // Returning valid-but-null is how we indicate to the caller that
1077 // the lookup result was filled in.
1078 return Owned((Expr*) 0);
1079 }
1080
1081 // Handle ivar access to Objective-C objects.
1082 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001083 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001084 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1085 << 1 << SS.getScopeRep()
1086 << FixItHint::CreateRemoval(SS.getRange());
1087 SS.clear();
1088 }
1089
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001090 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1091
1092 // There are three cases for the base type:
1093 // - builtin id (qualified or unqualified)
1094 // - builtin Class (qualified or unqualified)
1095 // - an interface
1096 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1097 if (!IDecl) {
1098 if (getLangOptions().ObjCAutoRefCount &&
1099 (OTy->isObjCId() || OTy->isObjCClass()))
1100 goto fail;
1101 // There's an implicit 'isa' ivar on all objects.
1102 // But we only actually find it this way on objects of type 'id',
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001103 // apparently.ghjg
1104 if (OTy->isObjCId() && Member->isStr("isa")) {
1105 Diag(MemberLoc, diag::warn_objc_isa_use);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001106 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1107 Context.getObjCClassType()));
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001108 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001109
1110 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1111 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1112 ObjCImpDecl, HasTemplateArgs);
1113 goto fail;
1114 }
1115
Douglas Gregord07cc362012-01-02 17:18:37 +00001116 if (RequireCompleteType(OpLoc, BaseType,
1117 PDiag(diag::err_typecheck_incomplete_tag)
1118 << BaseExpr.get()->getSourceRange()))
1119 return ExprError();
1120
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001121 ObjCInterfaceDecl *ClassDeclared;
1122 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1123
1124 if (!IV) {
1125 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001126 DeclFilterCCC<ObjCIvarDecl> Validator;
1127 Validator.IsObjCIvarLookup = IsArrow;
1128 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1129 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001130 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001131 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001132 Diag(R.getNameLoc(),
1133 diag::err_typecheck_member_reference_ivar_suggest)
1134 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1135 << FixItHint::CreateReplacement(R.getNameLoc(),
1136 IV->getNameAsString());
1137 Diag(IV->getLocation(), diag::note_previous_decl)
1138 << IV->getDeclName();
1139 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001140 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1141 Diag(MemberLoc,
1142 diag::err_property_found_suggest)
1143 << Member << BaseExpr.get()->getType()
1144 << FixItHint::CreateReplacement(OpLoc, ".");
1145 return ExprError();
1146 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001147
1148 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1149 << IDecl->getDeclName() << MemberName
1150 << BaseExpr.get()->getSourceRange();
1151 return ExprError();
1152 }
1153 }
1154
1155 // If the decl being referenced had an error, return an error for this
1156 // sub-expr without emitting another error, in order to avoid cascading
1157 // error cases.
1158 if (IV->isInvalidDecl())
1159 return ExprError();
1160
1161 // Check whether we can reference this field.
1162 if (DiagnoseUseOfDecl(IV, MemberLoc))
1163 return ExprError();
1164 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1165 IV->getAccessControl() != ObjCIvarDecl::Package) {
1166 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1167 if (ObjCMethodDecl *MD = getCurMethodDecl())
1168 ClassOfMethodDecl = MD->getClassInterface();
1169 else if (ObjCImpDecl && getCurFunctionDecl()) {
1170 // Case of a c-function declared inside an objc implementation.
1171 // FIXME: For a c-style function nested inside an objc implementation
1172 // class, there is no implementation context available, so we pass
1173 // down the context as argument to this routine. Ideally, this context
1174 // need be passed down in the AST node and somehow calculated from the
1175 // AST for a function decl.
1176 if (ObjCImplementationDecl *IMPD =
1177 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1178 ClassOfMethodDecl = IMPD->getClassInterface();
1179 else if (ObjCCategoryImplDecl* CatImplClass =
1180 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1181 ClassOfMethodDecl = CatImplClass->getClassInterface();
1182 }
1183
1184 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Douglas Gregor60ef3082011-12-15 00:29:59 +00001185 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1186 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001187 Diag(MemberLoc, diag::error_private_ivar_access)
1188 << IV->getDeclName();
1189 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1190 // @protected
1191 Diag(MemberLoc, diag::error_protected_ivar_access)
1192 << IV->getDeclName();
1193 }
1194 if (getLangOptions().ObjCAutoRefCount) {
1195 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1196 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1197 if (UO->getOpcode() == UO_Deref)
1198 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1199
1200 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1201 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1202 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1203 }
1204
1205 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1206 MemberLoc, BaseExpr.take(),
1207 IsArrow));
1208 }
1209
1210 // Objective-C property access.
1211 const ObjCObjectPointerType *OPT;
1212 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001213 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001214 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1215 << 0 << SS.getScopeRep()
1216 << FixItHint::CreateRemoval(SS.getRange());
1217 SS.clear();
1218 }
1219
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001220 // This actually uses the base as an r-value.
1221 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1222 if (BaseExpr.isInvalid())
1223 return ExprError();
1224
1225 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1226
1227 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1228
1229 const ObjCObjectType *OT = OPT->getObjectType();
1230
1231 // id, with and without qualifiers.
1232 if (OT->isObjCId()) {
1233 // Check protocols on qualified interfaces.
1234 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1235 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1236 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1237 // Check the use of this declaration
1238 if (DiagnoseUseOfDecl(PD, MemberLoc))
1239 return ExprError();
1240
John McCall3c3b7f92011-10-25 17:37:35 +00001241 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1242 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001243 VK_LValue,
1244 OK_ObjCProperty,
1245 MemberLoc,
1246 BaseExpr.take()));
1247 }
1248
1249 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1250 // Check the use of this method.
1251 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1252 return ExprError();
1253 Selector SetterSel =
1254 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1255 PP.getSelectorTable(), Member);
1256 ObjCMethodDecl *SMD = 0;
1257 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1258 SetterSel, Context))
1259 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001260
John McCall3c3b7f92011-10-25 17:37:35 +00001261 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1262 Context.PseudoObjectTy,
1263 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001264 MemberLoc, BaseExpr.take()));
1265 }
1266 }
1267 // Use of id.member can only be for a property reference. Do not
1268 // use the 'id' redefinition in this case.
1269 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1270 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1271 ObjCImpDecl, HasTemplateArgs);
1272
1273 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1274 << MemberName << BaseType);
1275 }
1276
1277 // 'Class', unqualified only.
1278 if (OT->isObjCClass()) {
1279 // Only works in a method declaration (??!).
1280 ObjCMethodDecl *MD = getCurMethodDecl();
1281 if (!MD) {
1282 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1283 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1284 ObjCImpDecl, HasTemplateArgs);
1285
1286 goto fail;
1287 }
1288
1289 // Also must look for a getter name which uses property syntax.
1290 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1291 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1292 ObjCMethodDecl *Getter;
1293 if ((Getter = IFace->lookupClassMethod(Sel))) {
1294 // Check the use of this method.
1295 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1296 return ExprError();
1297 } else
1298 Getter = IFace->lookupPrivateMethod(Sel, false);
1299 // If we found a getter then this may be a valid dot-reference, we
1300 // will look for the matching setter, in case it is needed.
1301 Selector SetterSel =
1302 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1303 PP.getSelectorTable(), Member);
1304 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1305 if (!Setter) {
1306 // If this reference is in an @implementation, also check for 'private'
1307 // methods.
1308 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1309 }
1310 // Look through local category implementations associated with the class.
1311 if (!Setter)
1312 Setter = IFace->getCategoryClassMethod(SetterSel);
1313
1314 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1315 return ExprError();
1316
1317 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001318 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001319 Context.PseudoObjectTy,
1320 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001321 MemberLoc, BaseExpr.take()));
1322 }
1323
1324 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1325 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1326 ObjCImpDecl, HasTemplateArgs);
1327
1328 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1329 << MemberName << BaseType);
1330 }
1331
1332 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001333 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1334 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001335 SourceLocation(), QualType(), false);
1336 }
1337
1338 // Handle 'field access' to vectors, such as 'V.xx'.
1339 if (BaseType->isExtVectorType()) {
1340 // FIXME: this expr should store IsArrow.
1341 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1342 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1343 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1344 Member, MemberLoc);
1345 if (ret.isNull())
1346 return ExprError();
1347
1348 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1349 *Member, MemberLoc));
1350 }
1351
1352 // Adjust builtin-sel to the appropriate redefinition type if that's
1353 // not just a pointer to builtin-sel again.
1354 if (IsArrow &&
1355 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001356 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1357 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1358 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001359 CK_BitCast);
1360 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1361 ObjCImpDecl, HasTemplateArgs);
1362 }
1363
1364 // Failure cases.
1365 fail:
1366
1367 // Recover from dot accesses to pointers, e.g.:
1368 // type *foo;
1369 // foo.bar
1370 // This is actually well-formed in two cases:
1371 // - 'type' is an Objective C type
1372 // - 'bar' is a pseudo-destructor name which happens to refer to
1373 // the appropriate pointer type
1374 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1375 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1376 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1377 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1378 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1379 << FixItHint::CreateReplacement(OpLoc, "->");
1380
1381 // Recurse as an -> access.
1382 IsArrow = true;
1383 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1384 ObjCImpDecl, HasTemplateArgs);
1385 }
1386 }
1387
1388 // If the user is trying to apply -> or . to a function name, it's probably
1389 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001390 if (tryToRecoverWithCall(BaseExpr,
1391 PDiag(diag::err_member_reference_needs_call),
1392 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001393 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001394 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001395 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001396 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1397 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1398 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001399 }
1400
1401 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1402 << BaseType << BaseExpr.get()->getSourceRange();
1403
1404 return ExprError();
1405}
1406
1407/// The main callback when the parser finds something like
1408/// expression . [nested-name-specifier] identifier
1409/// expression -> [nested-name-specifier] identifier
1410/// where 'identifier' encompasses a fairly broad spectrum of
1411/// possibilities, including destructor and operator references.
1412///
1413/// \param OpKind either tok::arrow or tok::period
1414/// \param HasTrailingLParen whether the next token is '(', which
1415/// is used to diagnose mis-uses of special members that can
1416/// only be called
1417/// \param ObjCImpDecl the current ObjC @implementation decl;
1418/// this is an ugly hack around the fact that ObjC @implementations
1419/// aren't properly put in the context chain
1420ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1421 SourceLocation OpLoc,
1422 tok::TokenKind OpKind,
1423 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001424 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001425 UnqualifiedId &Id,
1426 Decl *ObjCImpDecl,
1427 bool HasTrailingLParen) {
1428 if (SS.isSet() && SS.isInvalid())
1429 return ExprError();
1430
1431 // Warn about the explicit constructor calls Microsoft extension.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001432 if (getLangOptions().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001433 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1434 Diag(Id.getSourceRange().getBegin(),
1435 diag::ext_ms_explicit_constructor_call);
1436
1437 TemplateArgumentListInfo TemplateArgsBuffer;
1438
1439 // Decompose the name into its component parts.
1440 DeclarationNameInfo NameInfo;
1441 const TemplateArgumentListInfo *TemplateArgs;
1442 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1443 NameInfo, TemplateArgs);
1444
1445 DeclarationName Name = NameInfo.getName();
1446 bool IsArrow = (OpKind == tok::arrow);
1447
1448 NamedDecl *FirstQualifierInScope
1449 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1450 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1451
1452 // This is a postfix expression, so get rid of ParenListExprs.
1453 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1454 if (Result.isInvalid()) return ExprError();
1455 Base = Result.take();
1456
1457 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1458 isDependentScopeSpecifier(SS)) {
1459 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1460 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001461 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001462 NameInfo, TemplateArgs);
1463 } else {
1464 LookupResult R(*this, NameInfo, LookupMemberName);
1465 ExprResult BaseResult = Owned(Base);
1466 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1467 SS, ObjCImpDecl, TemplateArgs != 0);
1468 if (BaseResult.isInvalid())
1469 return ExprError();
1470 Base = BaseResult.take();
1471
1472 if (Result.isInvalid()) {
1473 Owned(Base);
1474 return ExprError();
1475 }
1476
1477 if (Result.get()) {
1478 // The only way a reference to a destructor can be used is to
1479 // immediately call it, which falls into this case. If the
1480 // next token is not a '(', produce a diagnostic and build the
1481 // call now.
1482 if (!HasTrailingLParen &&
1483 Id.getKind() == UnqualifiedId::IK_DestructorName)
1484 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1485
1486 return move(Result);
1487 }
1488
1489 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001490 OpLoc, IsArrow, SS, TemplateKWLoc,
1491 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001492 }
1493
1494 return move(Result);
1495}
1496
1497static ExprResult
1498BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1499 const CXXScopeSpec &SS, FieldDecl *Field,
1500 DeclAccessPair FoundDecl,
1501 const DeclarationNameInfo &MemberNameInfo) {
1502 // x.a is an l-value if 'a' has a reference type. Otherwise:
1503 // x.a is an l-value/x-value/pr-value if the base is (and note
1504 // that *x is always an l-value), except that if the base isn't
1505 // an ordinary object then we must have an rvalue.
1506 ExprValueKind VK = VK_LValue;
1507 ExprObjectKind OK = OK_Ordinary;
1508 if (!IsArrow) {
1509 if (BaseExpr->getObjectKind() == OK_Ordinary)
1510 VK = BaseExpr->getValueKind();
1511 else
1512 VK = VK_RValue;
1513 }
1514 if (VK != VK_RValue && Field->isBitField())
1515 OK = OK_BitField;
1516
1517 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1518 QualType MemberType = Field->getType();
1519 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1520 MemberType = Ref->getPointeeType();
1521 VK = VK_LValue;
1522 } else {
1523 QualType BaseType = BaseExpr->getType();
1524 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1525
1526 Qualifiers BaseQuals = BaseType.getQualifiers();
1527
1528 // GC attributes are never picked up by members.
1529 BaseQuals.removeObjCGCAttr();
1530
1531 // CVR attributes from the base are picked up by members,
1532 // except that 'mutable' members don't pick up 'const'.
1533 if (Field->isMutable()) BaseQuals.removeConst();
1534
1535 Qualifiers MemberQuals
1536 = S.Context.getCanonicalType(MemberType).getQualifiers();
1537
1538 // TR 18037 does not allow fields to be declared with address spaces.
1539 assert(!MemberQuals.hasAddressSpace());
1540
1541 Qualifiers Combined = BaseQuals + MemberQuals;
1542 if (Combined != MemberQuals)
1543 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1544 }
1545
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001546 ExprResult Base =
1547 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1548 FoundDecl, Field);
1549 if (Base.isInvalid())
1550 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001551 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001552 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001553 Field, FoundDecl, MemberNameInfo,
1554 MemberType, VK, OK));
1555}
1556
1557/// Builds an implicit member access expression. The current context
1558/// is known to be an instance method, and the given unqualified lookup
1559/// set is known to contain only instance members, at least one of which
1560/// is from an appropriate type.
1561ExprResult
1562Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001563 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001564 LookupResult &R,
1565 const TemplateArgumentListInfo *TemplateArgs,
1566 bool IsKnownInstance) {
1567 assert(!R.empty() && !R.isAmbiguous());
1568
1569 SourceLocation loc = R.getNameLoc();
1570
1571 // We may have found a field within an anonymous union or struct
1572 // (C++ [class.union]).
1573 // FIXME: template-ids inside anonymous structs?
1574 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1575 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1576
1577 // If this is known to be an instance access, go ahead and build an
1578 // implicit 'this' expression now.
1579 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001580 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001581 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1582
1583 Expr *baseExpr = 0; // null signifies implicit access
1584 if (IsKnownInstance) {
1585 SourceLocation Loc = R.getNameLoc();
1586 if (SS.getRange().isValid())
1587 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001588 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001589 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1590 }
1591
1592 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1593 /*OpLoc*/ SourceLocation(),
1594 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001595 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001596 /*FirstQualifierInScope*/ 0,
1597 R, TemplateArgs);
1598}