blob: 82249df2110c8985073068ba43306fb0d7c8397b [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 Friedman9bc291d2012-01-18 03:53:45 +000077 // The reference is an instance data member access, which is allowed
78 // because we're in C++11 mode and the context is unevaluated.
79 IMA_Field_Uneval_StaticContext,
80
81 // The reference is an instance data member access, which may be allowed
82 // because we're in C++11 mode and the context may be unevaluated
83 // (i.e. the context is PotentiallyPotentiallyEvaluated).
84 IMA_Field_PPE_StaticContext,
85
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000086 /// All possible referrents are instance members and the current
87 /// context is not an instance method.
88 IMA_Error_StaticContext,
89
90 /// All possible referrents are instance members of an unrelated
91 /// class.
92 IMA_Error_Unrelated
93};
94
95/// The given lookup names class member(s) and is not being used for
96/// an address-of-member expression. Classify the type of access
97/// according to whether it's possible that this reference names an
Eli Friedman9bc291d2012-01-18 03:53:45 +000098/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000099/// conservatively answer "yes", in which case some errors will simply
100/// not be caught until template-instantiation.
101static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
102 Scope *CurScope,
103 const LookupResult &R) {
104 assert(!R.empty() && (*R.begin())->isCXXClassMember());
105
106 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
107
108 bool isStaticContext =
109 (!isa<CXXMethodDecl>(DC) ||
110 cast<CXXMethodDecl>(DC)->isStatic());
111
112 // C++0x [expr.prim]p4:
113 // Otherwise, if a member-declarator declares a non-static data member
114 // of a class X, the expression this is a prvalue of type "pointer to X"
115 // within the optional brace-or-equal-initializer.
116 if (CurScope->getFlags() & Scope::ThisScope)
117 isStaticContext = false;
118
119 if (R.isUnresolvableResult())
120 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
121
122 // Collect all the declaring classes of instance members we find.
123 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000124 bool isField = false;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000125 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
126 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
127 NamedDecl *D = *I;
128
129 if (D->isCXXInstanceMember()) {
130 if (dyn_cast<FieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000131 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000132
133 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
134 Classes.insert(R->getCanonicalDecl());
135 }
136 else
137 hasNonInstance = true;
138 }
139
140 // If we didn't find any instance members, it can't be an implicit
141 // member reference.
142 if (Classes.empty())
143 return IMA_Static;
144
145 // If the current context is not an instance method, it can't be
146 // an implicit member reference.
147 if (isStaticContext) {
148 if (hasNonInstance)
149 return IMA_Mixed_StaticContext;
150
Eli Friedman9bc291d2012-01-18 03:53:45 +0000151 if (SemaRef.getLangOptions().CPlusPlus0x && isField) {
Richard Smithf6702a32011-12-20 02:08:33 +0000152 // C++11 [expr.prim.general]p12:
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000153 // An id-expression that denotes a non-static data member or non-static
154 // member function of a class can only be used:
155 // (...)
156 // - if that id-expression denotes a non-static data member and it
157 // appears in an unevaluated operand.
158 const Sema::ExpressionEvaluationContextRecord& record
159 = SemaRef.ExprEvalContexts.back();
Eli Friedman9bc291d2012-01-18 03:53:45 +0000160 if (record.Context == Sema::Unevaluated)
161 return IMA_Field_Uneval_StaticContext;
162 if (record.Context == Sema::PotentiallyPotentiallyEvaluated)
163 return IMA_Field_PPE_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000164 }
165
166 return IMA_Error_StaticContext;
167 }
168
169 CXXRecordDecl *contextClass;
170 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
171 contextClass = MD->getParent()->getCanonicalDecl();
172 else
173 contextClass = cast<CXXRecordDecl>(DC);
174
175 // [class.mfct.non-static]p3:
176 // ...is used in the body of a non-static member function of class X,
177 // if name lookup (3.4.1) resolves the name in the id-expression to a
178 // non-static non-type member of some class C [...]
179 // ...if C is not X or a base class of X, the class member access expression
180 // is ill-formed.
181 if (R.getNamingClass() &&
182 contextClass != R.getNamingClass()->getCanonicalDecl() &&
183 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
184 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
185
186 // If we can prove that the current context is unrelated to all the
187 // declaring classes, it can't be an implicit member reference (in
188 // which case it's an error if any of those members are selected).
189 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
190 return (hasNonInstance ? IMA_Mixed_Unrelated : IMA_Error_Unrelated);
191
192 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
193}
194
195/// Diagnose a reference to a field with no object available.
196static void DiagnoseInstanceReference(Sema &SemaRef,
197 const CXXScopeSpec &SS,
198 NamedDecl *rep,
Eli Friedman9bc291d2012-01-18 03:53:45 +0000199 const DeclarationNameInfo &nameInfo,
200 bool DelayPPEDiag = false) {
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 Friedman9bc291d2012-01-18 03:53:45 +0000209 if (DelayPPEDiag)
210 SemaRef.ExprEvalContexts.back().addDiagnostic(Loc,
211 SemaRef.PDiag(diag::err_invalid_member_use_in_static_method)
212 << Range << nameInfo.getName());
213 else
214 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
215 << Range << nameInfo.getName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000216 return;
217 }
218 }
Eli Friedman9bc291d2012-01-18 03:53:45 +0000219
220 if (DelayPPEDiag)
221 SemaRef.ExprEvalContexts.back().addDiagnostic(Loc,
222 SemaRef.PDiag(diag::err_invalid_non_static_member_use)
223 << nameInfo.getName() << Range);
224 else
225 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
226 << nameInfo.getName() << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000227 return;
228 }
Eli Friedman9bc291d2012-01-18 03:53:45 +0000229
230 assert(!DelayPPEDiag && "Only need to delay diagnostic for fields");
231
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000232 SemaRef.Diag(Loc, diag::err_member_call_without_object) << Range;
233}
234
235/// Builds an expression which might be an implicit member expression.
236ExprResult
237Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
238 LookupResult &R,
239 const TemplateArgumentListInfo *TemplateArgs) {
240 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
241 case IMA_Instance:
242 return BuildImplicitMemberExpr(SS, R, TemplateArgs, true);
243
244 case IMA_Mixed:
245 case IMA_Mixed_Unrelated:
246 case IMA_Unresolved:
247 return BuildImplicitMemberExpr(SS, R, TemplateArgs, false);
248
Eli Friedman9bc291d2012-01-18 03:53:45 +0000249 case IMA_Field_PPE_StaticContext:
250 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
251 R.getLookupNameInfo(), /*DelayPPEDiag*/true);
252 // FALL-THROUGH
253
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000254 case IMA_Static:
255 case IMA_Mixed_StaticContext:
256 case IMA_Unresolved_StaticContext:
Eli Friedman9bc291d2012-01-18 03:53:45 +0000257 case IMA_Field_Uneval_StaticContext:
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000258 if (TemplateArgs)
259 return BuildTemplateIdExpr(SS, R, false, *TemplateArgs);
260 return BuildDeclarationNameExpr(SS, R, false);
261
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
264 DiagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
265 R.getLookupNameInfo());
266 return ExprError();
267 }
268
269 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000270}
271
272/// Check an ext-vector component access expression.
273///
274/// VK should be set in advance to the value kind of the base
275/// expression.
276static QualType
277CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
278 SourceLocation OpLoc, const IdentifierInfo *CompName,
279 SourceLocation CompLoc) {
280 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
281 // see FIXME there.
282 //
283 // FIXME: This logic can be greatly simplified by splitting it along
284 // halving/not halving and reworking the component checking.
285 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
286
287 // The vector accessor can't exceed the number of elements.
288 const char *compStr = CompName->getNameStart();
289
290 // This flag determines whether or not the component is one of the four
291 // special names that indicate a subset of exactly half the elements are
292 // to be selected.
293 bool HalvingSwizzle = false;
294
295 // This flag determines whether or not CompName has an 's' char prefix,
296 // indicating that it is a string of hex values to be used as vector indices.
297 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
298
299 bool HasRepeated = false;
300 bool HasIndex[16] = {};
301
302 int Idx;
303
304 // Check that we've found one of the special components, or that the component
305 // names must come from the same set.
306 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
307 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
308 HalvingSwizzle = true;
309 } else if (!HexSwizzle &&
310 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
311 do {
312 if (HasIndex[Idx]) HasRepeated = true;
313 HasIndex[Idx] = true;
314 compStr++;
315 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
316 } else {
317 if (HexSwizzle) compStr++;
318 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
319 if (HasIndex[Idx]) HasRepeated = true;
320 HasIndex[Idx] = true;
321 compStr++;
322 }
323 }
324
325 if (!HalvingSwizzle && *compStr) {
326 // We didn't get to the end of the string. This means the component names
327 // didn't come from the same set *or* we encountered an illegal name.
328 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000329 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000330 return QualType();
331 }
332
333 // Ensure no component accessor exceeds the width of the vector type it
334 // operates on.
335 if (!HalvingSwizzle) {
336 compStr = CompName->getNameStart();
337
338 if (HexSwizzle)
339 compStr++;
340
341 while (*compStr) {
342 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
343 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
344 << baseType << SourceRange(CompLoc);
345 return QualType();
346 }
347 }
348 }
349
350 // The component accessor looks fine - now we need to compute the actual type.
351 // The vector type is implied by the component accessor. For example,
352 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
353 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
354 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
355 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
356 : CompName->getLength();
357 if (HexSwizzle)
358 CompSize--;
359
360 if (CompSize == 1)
361 return vecType->getElementType();
362
363 if (HasRepeated) VK = VK_RValue;
364
365 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
366 // Now look up the TypeDefDecl from the vector type. Without this,
367 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000368 for (Sema::ExtVectorDeclsType::iterator
369 I = S.ExtVectorDecls.begin(S.ExternalSource),
370 E = S.ExtVectorDecls.end();
371 I != E; ++I) {
372 if ((*I)->getUnderlyingType() == VT)
373 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000374 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000375
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000376 return VT; // should never get here (a typedef type should always be found).
377}
378
379static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
380 IdentifierInfo *Member,
381 const Selector &Sel,
382 ASTContext &Context) {
383 if (Member)
384 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
385 return PD;
386 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
387 return OMD;
388
389 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
390 E = PDecl->protocol_end(); I != E; ++I) {
391 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
392 Context))
393 return D;
394 }
395 return 0;
396}
397
398static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
399 IdentifierInfo *Member,
400 const Selector &Sel,
401 ASTContext &Context) {
402 // Check protocols on qualified interfaces.
403 Decl *GDecl = 0;
404 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
405 E = QIdTy->qual_end(); I != E; ++I) {
406 if (Member)
407 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
408 GDecl = PD;
409 break;
410 }
411 // Also must look for a getter or setter name which uses property syntax.
412 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
413 GDecl = OMD;
414 break;
415 }
416 }
417 if (!GDecl) {
418 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
419 E = QIdTy->qual_end(); I != E; ++I) {
420 // Search in the protocol-qualifier list of current protocol.
421 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
422 Context);
423 if (GDecl)
424 return GDecl;
425 }
426 }
427 return GDecl;
428}
429
430ExprResult
431Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
432 bool IsArrow, SourceLocation OpLoc,
433 const CXXScopeSpec &SS,
434 NamedDecl *FirstQualifierInScope,
435 const DeclarationNameInfo &NameInfo,
436 const TemplateArgumentListInfo *TemplateArgs) {
437 // Even in dependent contexts, try to diagnose base expressions with
438 // obviously wrong types, e.g.:
439 //
440 // T* t;
441 // t.f;
442 //
443 // In Obj-C++, however, the above expression is valid, since it could be
444 // accessing the 'f' property if T is an Obj-C interface. The extra check
445 // allows this, while still reporting an error if T is a struct pointer.
446 if (!IsArrow) {
447 const PointerType *PT = BaseType->getAs<PointerType>();
448 if (PT && (!getLangOptions().ObjC1 ||
449 PT->getPointeeType()->isRecordType())) {
450 assert(BaseExpr && "cannot happen with implicit member accesses");
451 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
452 << BaseType << BaseExpr->getSourceRange();
453 return ExprError();
454 }
455 }
456
457 assert(BaseType->isDependentType() ||
458 NameInfo.getName().isDependentName() ||
459 isDependentScopeSpecifier(SS));
460
461 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
462 // must have pointer type, and the accessed type is the pointee.
463 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
464 IsArrow, OpLoc,
465 SS.getWithLocInContext(Context),
466 FirstQualifierInScope,
467 NameInfo, TemplateArgs));
468}
469
470/// We know that the given qualified member reference points only to
471/// declarations which do not belong to the static type of the base
472/// expression. Diagnose the problem.
473static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
474 Expr *BaseExpr,
475 QualType BaseType,
476 const CXXScopeSpec &SS,
477 NamedDecl *rep,
478 const DeclarationNameInfo &nameInfo) {
479 // If this is an implicit member access, use a different set of
480 // diagnostics.
481 if (!BaseExpr)
482 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
483
484 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
485 << SS.getRange() << rep << BaseType;
486}
487
488// Check whether the declarations we found through a nested-name
489// specifier in a member expression are actually members of the base
490// type. The restriction here is:
491//
492// C++ [expr.ref]p2:
493// ... In these cases, the id-expression shall name a
494// member of the class or of one of its base classes.
495//
496// So it's perfectly legitimate for the nested-name specifier to name
497// an unrelated class, and for us to find an overload set including
498// decls from classes which are not superclasses, as long as the decl
499// we actually pick through overload resolution is from a superclass.
500bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
501 QualType BaseType,
502 const CXXScopeSpec &SS,
503 const LookupResult &R) {
504 const RecordType *BaseRT = BaseType->getAs<RecordType>();
505 if (!BaseRT) {
506 // We can't check this yet because the base type is still
507 // dependent.
508 assert(BaseType->isDependentType());
509 return false;
510 }
511 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
512
513 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
514 // If this is an implicit member reference and we find a
515 // non-instance member, it's not an error.
516 if (!BaseExpr && !(*I)->isCXXInstanceMember())
517 return false;
518
519 // Note that we use the DC of the decl, not the underlying decl.
520 DeclContext *DC = (*I)->getDeclContext();
521 while (DC->isTransparentContext())
522 DC = DC->getParent();
523
524 if (!DC->isRecord())
525 continue;
526
527 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
528 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
529
530 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
531 return false;
532 }
533
534 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
535 R.getRepresentativeDecl(),
536 R.getLookupNameInfo());
537 return true;
538}
539
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000540namespace {
541
542// Callback to only accept typo corrections that are either a ValueDecl or a
543// FunctionTemplateDecl.
544class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
545 public:
546 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
547 NamedDecl *ND = candidate.getCorrectionDecl();
548 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
549 }
550};
551
552}
553
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000554static bool
555LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
556 SourceRange BaseRange, const RecordType *RTy,
557 SourceLocation OpLoc, CXXScopeSpec &SS,
558 bool HasTemplateArgs) {
559 RecordDecl *RDecl = RTy->getDecl();
560 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
561 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
562 << BaseRange))
563 return true;
564
565 if (HasTemplateArgs) {
566 // LookupTemplateName doesn't expect these both to exist simultaneously.
567 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
568
569 bool MOUS;
570 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
571 return false;
572 }
573
574 DeclContext *DC = RDecl;
575 if (SS.isSet()) {
576 // If the member name was a qualified-id, look into the
577 // nested-name-specifier.
578 DC = SemaRef.computeDeclContext(SS, false);
579
580 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
581 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
582 << SS.getRange() << DC;
583 return true;
584 }
585
586 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
587
588 if (!isa<TypeDecl>(DC)) {
589 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
590 << DC << SS.getRange();
591 return true;
592 }
593 }
594
595 // The record definition is complete, now look up the member.
596 SemaRef.LookupQualifiedName(R, DC);
597
598 if (!R.empty())
599 return false;
600
601 // We didn't find anything with the given name, so try to correct
602 // for typos.
603 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000604 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000605 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
606 R.getLookupKind(), NULL,
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000607 &SS, &Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000608 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000609 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000610 std::string CorrectedStr(
611 Corrected.getAsString(SemaRef.getLangOptions()));
612 std::string CorrectedQuotedStr(
613 Corrected.getQuoted(SemaRef.getLangOptions()));
614 R.setLookupName(Corrected.getCorrection());
615 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000616 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000617 << Name << DC << CorrectedQuotedStr << SS.getRange()
618 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
619 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
620 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000621 }
622
623 return false;
624}
625
626ExprResult
627Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
628 SourceLocation OpLoc, bool IsArrow,
629 CXXScopeSpec &SS,
630 NamedDecl *FirstQualifierInScope,
631 const DeclarationNameInfo &NameInfo,
632 const TemplateArgumentListInfo *TemplateArgs) {
633 if (BaseType->isDependentType() ||
634 (SS.isSet() && isDependentScopeSpecifier(SS)))
635 return ActOnDependentMemberExpr(Base, BaseType,
636 IsArrow, OpLoc,
637 SS, FirstQualifierInScope,
638 NameInfo, TemplateArgs);
639
640 LookupResult R(*this, NameInfo, LookupMemberName);
641
642 // Implicit member accesses.
643 if (!Base) {
644 QualType RecordTy = BaseType;
645 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
646 if (LookupMemberExprInRecord(*this, R, SourceRange(),
647 RecordTy->getAs<RecordType>(),
648 OpLoc, SS, TemplateArgs != 0))
649 return ExprError();
650
651 // Explicit member accesses.
652 } else {
653 ExprResult BaseResult = Owned(Base);
654 ExprResult Result =
655 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
656 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
657
658 if (BaseResult.isInvalid())
659 return ExprError();
660 Base = BaseResult.take();
661
662 if (Result.isInvalid()) {
663 Owned(Base);
664 return ExprError();
665 }
666
667 if (Result.get())
668 return move(Result);
669
670 // LookupMemberExpr can modify Base, and thus change BaseType
671 BaseType = Base->getType();
672 }
673
674 return BuildMemberReferenceExpr(Base, BaseType,
675 OpLoc, IsArrow, SS, FirstQualifierInScope,
676 R, TemplateArgs);
677}
678
679static ExprResult
680BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
681 const CXXScopeSpec &SS, FieldDecl *Field,
682 DeclAccessPair FoundDecl,
683 const DeclarationNameInfo &MemberNameInfo);
684
685ExprResult
686Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
687 SourceLocation loc,
688 IndirectFieldDecl *indirectField,
689 Expr *baseObjectExpr,
690 SourceLocation opLoc) {
691 // First, build the expression that refers to the base object.
692
693 bool baseObjectIsPointer = false;
694 Qualifiers baseQuals;
695
696 // Case 1: the base of the indirect field is not a field.
697 VarDecl *baseVariable = indirectField->getVarDecl();
698 CXXScopeSpec EmptySS;
699 if (baseVariable) {
700 assert(baseVariable->getType()->isRecordType());
701
702 // In principle we could have a member access expression that
703 // accesses an anonymous struct/union that's a static member of
704 // the base object's class. However, under the current standard,
705 // static data members cannot be anonymous structs or unions.
706 // Supporting this is as easy as building a MemberExpr here.
707 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
708
709 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
710
711 ExprResult result
712 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
713 if (result.isInvalid()) return ExprError();
714
715 baseObjectExpr = result.take();
716 baseObjectIsPointer = false;
717 baseQuals = baseObjectExpr->getType().getQualifiers();
718
719 // Case 2: the base of the indirect field is a field and the user
720 // wrote a member expression.
721 } else if (baseObjectExpr) {
722 // The caller provided the base object expression. Determine
723 // whether its a pointer and whether it adds any qualifiers to the
724 // anonymous struct/union fields we're looking into.
725 QualType objectType = baseObjectExpr->getType();
726
727 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
728 baseObjectIsPointer = true;
729 objectType = ptr->getPointeeType();
730 } else {
731 baseObjectIsPointer = false;
732 }
733 baseQuals = objectType.getQualifiers();
734
735 // Case 3: the base of the indirect field is a field and we should
736 // build an implicit member access.
737 } else {
738 // We've found a member of an anonymous struct/union that is
739 // inside a non-anonymous struct/union, so in a well-formed
740 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000741 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000742 if (ThisTy.isNull()) {
743 Diag(loc, diag::err_invalid_member_use_in_static_method)
744 << indirectField->getDeclName();
745 return ExprError();
746 }
747
748 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000749 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000750 baseObjectExpr
751 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
752 baseObjectIsPointer = true;
753 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
754 }
755
756 // Build the implicit member references to the field of the
757 // anonymous struct/union.
758 Expr *result = baseObjectExpr;
759 IndirectFieldDecl::chain_iterator
760 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
761
762 // Build the first member access in the chain with full information.
763 if (!baseVariable) {
764 FieldDecl *field = cast<FieldDecl>(*FI);
765
766 // FIXME: use the real found-decl info!
767 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
768
769 // Make a nameInfo that properly uses the anonymous name.
770 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
771
772 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
773 EmptySS, field, foundDecl,
774 memberNameInfo).take();
775 baseObjectIsPointer = false;
776
777 // FIXME: check qualified member access
778 }
779
780 // In all cases, we should now skip the first declaration in the chain.
781 ++FI;
782
783 while (FI != FEnd) {
784 FieldDecl *field = cast<FieldDecl>(*FI++);
785
786 // FIXME: these are somewhat meaningless
787 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
788 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
789
790 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
791 (FI == FEnd? SS : EmptySS), field,
792 foundDecl, memberNameInfo).take();
793 }
794
795 return Owned(result);
796}
797
798/// \brief Build a MemberExpr AST node.
799static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
800 const CXXScopeSpec &SS, ValueDecl *Member,
801 DeclAccessPair FoundDecl,
802 const DeclarationNameInfo &MemberNameInfo,
803 QualType Ty,
804 ExprValueKind VK, ExprObjectKind OK,
805 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000806 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000807 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
808 Member, FoundDecl, MemberNameInfo,
809 TemplateArgs, Ty, VK, OK);
810}
811
812ExprResult
813Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
814 SourceLocation OpLoc, bool IsArrow,
815 const CXXScopeSpec &SS,
816 NamedDecl *FirstQualifierInScope,
817 LookupResult &R,
818 const TemplateArgumentListInfo *TemplateArgs,
819 bool SuppressQualifierCheck) {
820 QualType BaseType = BaseExprType;
821 if (IsArrow) {
822 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000823 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000824 }
825 R.setBaseObjectType(BaseType);
826
827 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
828 DeclarationName MemberName = MemberNameInfo.getName();
829 SourceLocation MemberLoc = MemberNameInfo.getLoc();
830
831 if (R.isAmbiguous())
832 return ExprError();
833
834 if (R.empty()) {
835 // Rederive where we looked up.
836 DeclContext *DC = (SS.isSet()
837 ? computeDeclContext(SS, false)
838 : BaseType->getAs<RecordType>()->getDecl());
839
840 Diag(R.getNameLoc(), diag::err_no_member)
841 << MemberName << DC
842 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
843 return ExprError();
844 }
845
846 // Diagnose lookups that find only declarations from a non-base
847 // type. This is possible for either qualified lookups (which may
848 // have been qualified with an unrelated type) or implicit member
849 // expressions (which were found with unqualified lookup and thus
850 // may have come from an enclosing scope). Note that it's okay for
851 // lookup to find declarations from a non-base type as long as those
852 // aren't the ones picked by overload resolution.
853 if ((SS.isSet() || !BaseExpr ||
854 (isa<CXXThisExpr>(BaseExpr) &&
855 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
856 !SuppressQualifierCheck &&
857 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
858 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000859
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000860 // Construct an unresolved result if we in fact got an unresolved
861 // result.
862 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
863 // Suppress any lookup-related diagnostics; we'll do these when we
864 // pick a member.
865 R.suppressDiagnostics();
866
867 UnresolvedMemberExpr *MemExpr
868 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
869 BaseExpr, BaseExprType,
870 IsArrow, OpLoc,
871 SS.getWithLocInContext(Context),
872 MemberNameInfo,
873 TemplateArgs, R.begin(), R.end());
874
875 return Owned(MemExpr);
876 }
877
878 assert(R.isSingleResult());
879 DeclAccessPair FoundDecl = R.begin().getPair();
880 NamedDecl *MemberDecl = R.getFoundDecl();
881
882 // FIXME: diagnose the presence of template arguments now.
883
884 // If the decl being referenced had an error, return an error for this
885 // sub-expr without emitting another error, in order to avoid cascading
886 // error cases.
887 if (MemberDecl->isInvalidDecl())
888 return ExprError();
889
890 // Handle the implicit-member-access case.
891 if (!BaseExpr) {
892 // If this is not an instance member, convert to a non-member access.
893 if (!MemberDecl->isCXXInstanceMember())
894 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
895
896 SourceLocation Loc = R.getNameLoc();
897 if (SS.getRange().isValid())
898 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000899 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000900 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
901 }
902
903 bool ShouldCheckUse = true;
904 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
905 // Don't diagnose the use of a virtual member function unless it's
906 // explicitly qualified.
907 if (MD->isVirtual() && !SS.isSet())
908 ShouldCheckUse = false;
909 }
910
911 // Check the use of this member.
912 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
913 Owned(BaseExpr);
914 return ExprError();
915 }
916
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000917 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
918 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
919 SS, FD, FoundDecl, MemberNameInfo);
920
921 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
922 // We may have found a field within an anonymous union or struct
923 // (C++ [class.union]).
924 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
925 BaseExpr, OpLoc);
926
927 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
928 MarkDeclarationReferenced(MemberLoc, Var);
929 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
930 Var, FoundDecl, MemberNameInfo,
931 Var->getType().getNonReferenceType(),
932 VK_LValue, OK_Ordinary));
933 }
934
935 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
936 ExprValueKind valueKind;
937 QualType type;
938 if (MemberFn->isInstance()) {
939 valueKind = VK_RValue;
940 type = Context.BoundMemberTy;
941 } else {
942 valueKind = VK_LValue;
943 type = MemberFn->getType();
944 }
945
946 MarkDeclarationReferenced(MemberLoc, MemberDecl);
947 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
948 MemberFn, FoundDecl, MemberNameInfo,
949 type, valueKind, OK_Ordinary));
950 }
951 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
952
953 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
954 MarkDeclarationReferenced(MemberLoc, MemberDecl);
955 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
956 Enum, FoundDecl, MemberNameInfo,
957 Enum->getType(), VK_RValue, OK_Ordinary));
958 }
959
960 Owned(BaseExpr);
961
962 // We found something that we didn't expect. Complain.
963 if (isa<TypeDecl>(MemberDecl))
964 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
965 << MemberName << BaseType << int(IsArrow);
966 else
967 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
968 << MemberName << BaseType << int(IsArrow);
969
970 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
971 << MemberName;
972 R.suppressDiagnostics();
973 return ExprError();
974}
975
976/// Given that normal member access failed on the given expression,
977/// and given that the expression's type involves builtin-id or
978/// builtin-Class, decide whether substituting in the redefinition
979/// types would be profitable. The redefinition type is whatever
980/// this translation unit tried to typedef to id/Class; we store
981/// it to the side and then re-use it in places like this.
982static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
983 const ObjCObjectPointerType *opty
984 = base.get()->getType()->getAs<ObjCObjectPointerType>();
985 if (!opty) return false;
986
987 const ObjCObjectType *ty = opty->getObjectType();
988
989 QualType redef;
990 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000991 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000992 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000993 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000994 } else {
995 return false;
996 }
997
998 // Do the substitution as long as the redefinition type isn't just a
999 // possibly-qualified pointer to builtin-id or builtin-Class again.
1000 opty = redef->getAs<ObjCObjectPointerType>();
1001 if (opty && !opty->getObjectType()->getInterface() != 0)
1002 return false;
1003
1004 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1005 return true;
1006}
1007
John McCall6dbba4f2011-10-11 23:14:30 +00001008static bool isRecordType(QualType T) {
1009 return T->isRecordType();
1010}
1011static bool isPointerToRecordType(QualType T) {
1012 if (const PointerType *PT = T->getAs<PointerType>())
1013 return PT->getPointeeType()->isRecordType();
1014 return false;
1015}
1016
Richard Smith9138b4e2011-10-26 19:06:56 +00001017/// Perform conversions on the LHS of a member access expression.
1018ExprResult
1019Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001020 if (IsArrow && !Base->getType()->isFunctionType())
1021 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001022
Eli Friedman059d5782012-01-13 02:20:01 +00001023 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001024}
1025
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001026/// Look up the given member of the given non-type-dependent
1027/// expression. This can return in one of two ways:
1028/// * If it returns a sentinel null-but-valid result, the caller will
1029/// assume that lookup was performed and the results written into
1030/// the provided structure. It will take over from there.
1031/// * Otherwise, the returned expression will be produced in place of
1032/// an ordinary member expression.
1033///
1034/// The ObjCImpDecl bit is a gross hack that will need to be properly
1035/// fixed for ObjC++.
1036ExprResult
1037Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1038 bool &IsArrow, SourceLocation OpLoc,
1039 CXXScopeSpec &SS,
1040 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1041 assert(BaseExpr.get() && "no base expression");
1042
1043 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001044 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001045 if (BaseExpr.isInvalid())
1046 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001047
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001048 QualType BaseType = BaseExpr.get()->getType();
1049 assert(!BaseType->isDependentType());
1050
1051 DeclarationName MemberName = R.getLookupName();
1052 SourceLocation MemberLoc = R.getNameLoc();
1053
1054 // For later type-checking purposes, turn arrow accesses into dot
1055 // accesses. The only access type we support that doesn't follow
1056 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1057 // and those never use arrows, so this is unaffected.
1058 if (IsArrow) {
1059 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1060 BaseType = Ptr->getPointeeType();
1061 else if (const ObjCObjectPointerType *Ptr
1062 = BaseType->getAs<ObjCObjectPointerType>())
1063 BaseType = Ptr->getPointeeType();
1064 else if (BaseType->isRecordType()) {
1065 // Recover from arrow accesses to records, e.g.:
1066 // struct MyRecord foo;
1067 // foo->bar
1068 // This is actually well-formed in C++ if MyRecord has an
1069 // overloaded operator->, but that should have been dealt with
1070 // by now.
1071 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1072 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1073 << FixItHint::CreateReplacement(OpLoc, ".");
1074 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001075 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001076 goto fail;
1077 } else {
1078 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1079 << BaseType << BaseExpr.get()->getSourceRange();
1080 return ExprError();
1081 }
1082 }
1083
1084 // Handle field access to simple records.
1085 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1086 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1087 RTy, OpLoc, SS, HasTemplateArgs))
1088 return ExprError();
1089
1090 // Returning valid-but-null is how we indicate to the caller that
1091 // the lookup result was filled in.
1092 return Owned((Expr*) 0);
1093 }
1094
1095 // Handle ivar access to Objective-C objects.
1096 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001097 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001098 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1099 << 1 << SS.getScopeRep()
1100 << FixItHint::CreateRemoval(SS.getRange());
1101 SS.clear();
1102 }
1103
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001104 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1105
1106 // There are three cases for the base type:
1107 // - builtin id (qualified or unqualified)
1108 // - builtin Class (qualified or unqualified)
1109 // - an interface
1110 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1111 if (!IDecl) {
1112 if (getLangOptions().ObjCAutoRefCount &&
1113 (OTy->isObjCId() || OTy->isObjCClass()))
1114 goto fail;
1115 // There's an implicit 'isa' ivar on all objects.
1116 // But we only actually find it this way on objects of type 'id',
1117 // apparently.
1118 if (OTy->isObjCId() && Member->isStr("isa"))
1119 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1120 Context.getObjCClassType()));
1121
1122 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1123 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1124 ObjCImpDecl, HasTemplateArgs);
1125 goto fail;
1126 }
1127
Douglas Gregord07cc362012-01-02 17:18:37 +00001128 if (RequireCompleteType(OpLoc, BaseType,
1129 PDiag(diag::err_typecheck_incomplete_tag)
1130 << BaseExpr.get()->getSourceRange()))
1131 return ExprError();
1132
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001133 ObjCInterfaceDecl *ClassDeclared;
1134 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1135
1136 if (!IV) {
1137 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001138 DeclFilterCCC<ObjCIvarDecl> Validator;
1139 Validator.IsObjCIvarLookup = IsArrow;
1140 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1141 LookupMemberName, NULL, NULL,
1142 &Validator, IDecl)) {
1143 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001144 Diag(R.getNameLoc(),
1145 diag::err_typecheck_member_reference_ivar_suggest)
1146 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1147 << FixItHint::CreateReplacement(R.getNameLoc(),
1148 IV->getNameAsString());
1149 Diag(IV->getLocation(), diag::note_previous_decl)
1150 << IV->getDeclName();
1151 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001152 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1153 Diag(MemberLoc,
1154 diag::err_property_found_suggest)
1155 << Member << BaseExpr.get()->getType()
1156 << FixItHint::CreateReplacement(OpLoc, ".");
1157 return ExprError();
1158 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001159
1160 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1161 << IDecl->getDeclName() << MemberName
1162 << BaseExpr.get()->getSourceRange();
1163 return ExprError();
1164 }
1165 }
1166
1167 // If the decl being referenced had an error, return an error for this
1168 // sub-expr without emitting another error, in order to avoid cascading
1169 // error cases.
1170 if (IV->isInvalidDecl())
1171 return ExprError();
1172
1173 // Check whether we can reference this field.
1174 if (DiagnoseUseOfDecl(IV, MemberLoc))
1175 return ExprError();
1176 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1177 IV->getAccessControl() != ObjCIvarDecl::Package) {
1178 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1179 if (ObjCMethodDecl *MD = getCurMethodDecl())
1180 ClassOfMethodDecl = MD->getClassInterface();
1181 else if (ObjCImpDecl && getCurFunctionDecl()) {
1182 // Case of a c-function declared inside an objc implementation.
1183 // FIXME: For a c-style function nested inside an objc implementation
1184 // class, there is no implementation context available, so we pass
1185 // down the context as argument to this routine. Ideally, this context
1186 // need be passed down in the AST node and somehow calculated from the
1187 // AST for a function decl.
1188 if (ObjCImplementationDecl *IMPD =
1189 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1190 ClassOfMethodDecl = IMPD->getClassInterface();
1191 else if (ObjCCategoryImplDecl* CatImplClass =
1192 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1193 ClassOfMethodDecl = CatImplClass->getClassInterface();
1194 }
1195
1196 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Douglas Gregor60ef3082011-12-15 00:29:59 +00001197 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1198 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001199 Diag(MemberLoc, diag::error_private_ivar_access)
1200 << IV->getDeclName();
1201 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1202 // @protected
1203 Diag(MemberLoc, diag::error_protected_ivar_access)
1204 << IV->getDeclName();
1205 }
1206 if (getLangOptions().ObjCAutoRefCount) {
1207 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1208 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1209 if (UO->getOpcode() == UO_Deref)
1210 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1211
1212 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1213 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1214 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1215 }
1216
1217 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1218 MemberLoc, BaseExpr.take(),
1219 IsArrow));
1220 }
1221
1222 // Objective-C property access.
1223 const ObjCObjectPointerType *OPT;
1224 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001225 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001226 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1227 << 0 << SS.getScopeRep()
1228 << FixItHint::CreateRemoval(SS.getRange());
1229 SS.clear();
1230 }
1231
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001232 // This actually uses the base as an r-value.
1233 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1234 if (BaseExpr.isInvalid())
1235 return ExprError();
1236
1237 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1238
1239 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1240
1241 const ObjCObjectType *OT = OPT->getObjectType();
1242
1243 // id, with and without qualifiers.
1244 if (OT->isObjCId()) {
1245 // Check protocols on qualified interfaces.
1246 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1247 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1248 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1249 // Check the use of this declaration
1250 if (DiagnoseUseOfDecl(PD, MemberLoc))
1251 return ExprError();
1252
John McCall3c3b7f92011-10-25 17:37:35 +00001253 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1254 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001255 VK_LValue,
1256 OK_ObjCProperty,
1257 MemberLoc,
1258 BaseExpr.take()));
1259 }
1260
1261 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1262 // Check the use of this method.
1263 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1264 return ExprError();
1265 Selector SetterSel =
1266 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1267 PP.getSelectorTable(), Member);
1268 ObjCMethodDecl *SMD = 0;
1269 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1270 SetterSel, Context))
1271 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001272
John McCall3c3b7f92011-10-25 17:37:35 +00001273 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1274 Context.PseudoObjectTy,
1275 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001276 MemberLoc, BaseExpr.take()));
1277 }
1278 }
1279 // Use of id.member can only be for a property reference. Do not
1280 // use the 'id' redefinition in this case.
1281 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1282 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1283 ObjCImpDecl, HasTemplateArgs);
1284
1285 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1286 << MemberName << BaseType);
1287 }
1288
1289 // 'Class', unqualified only.
1290 if (OT->isObjCClass()) {
1291 // Only works in a method declaration (??!).
1292 ObjCMethodDecl *MD = getCurMethodDecl();
1293 if (!MD) {
1294 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1295 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1296 ObjCImpDecl, HasTemplateArgs);
1297
1298 goto fail;
1299 }
1300
1301 // Also must look for a getter name which uses property syntax.
1302 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1303 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1304 ObjCMethodDecl *Getter;
1305 if ((Getter = IFace->lookupClassMethod(Sel))) {
1306 // Check the use of this method.
1307 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1308 return ExprError();
1309 } else
1310 Getter = IFace->lookupPrivateMethod(Sel, false);
1311 // If we found a getter then this may be a valid dot-reference, we
1312 // will look for the matching setter, in case it is needed.
1313 Selector SetterSel =
1314 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1315 PP.getSelectorTable(), Member);
1316 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1317 if (!Setter) {
1318 // If this reference is in an @implementation, also check for 'private'
1319 // methods.
1320 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1321 }
1322 // Look through local category implementations associated with the class.
1323 if (!Setter)
1324 Setter = IFace->getCategoryClassMethod(SetterSel);
1325
1326 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1327 return ExprError();
1328
1329 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001330 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001331 Context.PseudoObjectTy,
1332 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001333 MemberLoc, BaseExpr.take()));
1334 }
1335
1336 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1337 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1338 ObjCImpDecl, HasTemplateArgs);
1339
1340 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1341 << MemberName << BaseType);
1342 }
1343
1344 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001345 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1346 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001347 SourceLocation(), QualType(), false);
1348 }
1349
1350 // Handle 'field access' to vectors, such as 'V.xx'.
1351 if (BaseType->isExtVectorType()) {
1352 // FIXME: this expr should store IsArrow.
1353 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1354 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1355 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1356 Member, MemberLoc);
1357 if (ret.isNull())
1358 return ExprError();
1359
1360 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1361 *Member, MemberLoc));
1362 }
1363
1364 // Adjust builtin-sel to the appropriate redefinition type if that's
1365 // not just a pointer to builtin-sel again.
1366 if (IsArrow &&
1367 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001368 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1369 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1370 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001371 CK_BitCast);
1372 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1373 ObjCImpDecl, HasTemplateArgs);
1374 }
1375
1376 // Failure cases.
1377 fail:
1378
1379 // Recover from dot accesses to pointers, e.g.:
1380 // type *foo;
1381 // foo.bar
1382 // This is actually well-formed in two cases:
1383 // - 'type' is an Objective C type
1384 // - 'bar' is a pseudo-destructor name which happens to refer to
1385 // the appropriate pointer type
1386 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1387 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1388 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1389 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1390 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1391 << FixItHint::CreateReplacement(OpLoc, "->");
1392
1393 // Recurse as an -> access.
1394 IsArrow = true;
1395 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1396 ObjCImpDecl, HasTemplateArgs);
1397 }
1398 }
1399
1400 // If the user is trying to apply -> or . to a function name, it's probably
1401 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001402 if (tryToRecoverWithCall(BaseExpr,
1403 PDiag(diag::err_member_reference_needs_call),
1404 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001405 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001406 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001407 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001408 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1409 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1410 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001411 }
1412
1413 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1414 << BaseType << BaseExpr.get()->getSourceRange();
1415
1416 return ExprError();
1417}
1418
1419/// The main callback when the parser finds something like
1420/// expression . [nested-name-specifier] identifier
1421/// expression -> [nested-name-specifier] identifier
1422/// where 'identifier' encompasses a fairly broad spectrum of
1423/// possibilities, including destructor and operator references.
1424///
1425/// \param OpKind either tok::arrow or tok::period
1426/// \param HasTrailingLParen whether the next token is '(', which
1427/// is used to diagnose mis-uses of special members that can
1428/// only be called
1429/// \param ObjCImpDecl the current ObjC @implementation decl;
1430/// this is an ugly hack around the fact that ObjC @implementations
1431/// aren't properly put in the context chain
1432ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1433 SourceLocation OpLoc,
1434 tok::TokenKind OpKind,
1435 CXXScopeSpec &SS,
1436 UnqualifiedId &Id,
1437 Decl *ObjCImpDecl,
1438 bool HasTrailingLParen) {
1439 if (SS.isSet() && SS.isInvalid())
1440 return ExprError();
1441
1442 // Warn about the explicit constructor calls Microsoft extension.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001443 if (getLangOptions().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001444 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1445 Diag(Id.getSourceRange().getBegin(),
1446 diag::ext_ms_explicit_constructor_call);
1447
1448 TemplateArgumentListInfo TemplateArgsBuffer;
1449
1450 // Decompose the name into its component parts.
1451 DeclarationNameInfo NameInfo;
1452 const TemplateArgumentListInfo *TemplateArgs;
1453 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1454 NameInfo, TemplateArgs);
1455
1456 DeclarationName Name = NameInfo.getName();
1457 bool IsArrow = (OpKind == tok::arrow);
1458
1459 NamedDecl *FirstQualifierInScope
1460 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1461 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1462
1463 // This is a postfix expression, so get rid of ParenListExprs.
1464 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1465 if (Result.isInvalid()) return ExprError();
1466 Base = Result.take();
1467
1468 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1469 isDependentScopeSpecifier(SS)) {
1470 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1471 IsArrow, OpLoc,
1472 SS, FirstQualifierInScope,
1473 NameInfo, TemplateArgs);
1474 } else {
1475 LookupResult R(*this, NameInfo, LookupMemberName);
1476 ExprResult BaseResult = Owned(Base);
1477 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1478 SS, ObjCImpDecl, TemplateArgs != 0);
1479 if (BaseResult.isInvalid())
1480 return ExprError();
1481 Base = BaseResult.take();
1482
1483 if (Result.isInvalid()) {
1484 Owned(Base);
1485 return ExprError();
1486 }
1487
1488 if (Result.get()) {
1489 // The only way a reference to a destructor can be used is to
1490 // immediately call it, which falls into this case. If the
1491 // next token is not a '(', produce a diagnostic and build the
1492 // call now.
1493 if (!HasTrailingLParen &&
1494 Id.getKind() == UnqualifiedId::IK_DestructorName)
1495 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1496
1497 return move(Result);
1498 }
1499
1500 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1501 OpLoc, IsArrow, SS, FirstQualifierInScope,
1502 R, TemplateArgs);
1503 }
1504
1505 return move(Result);
1506}
1507
1508static ExprResult
1509BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1510 const CXXScopeSpec &SS, FieldDecl *Field,
1511 DeclAccessPair FoundDecl,
1512 const DeclarationNameInfo &MemberNameInfo) {
1513 // x.a is an l-value if 'a' has a reference type. Otherwise:
1514 // x.a is an l-value/x-value/pr-value if the base is (and note
1515 // that *x is always an l-value), except that if the base isn't
1516 // an ordinary object then we must have an rvalue.
1517 ExprValueKind VK = VK_LValue;
1518 ExprObjectKind OK = OK_Ordinary;
1519 if (!IsArrow) {
1520 if (BaseExpr->getObjectKind() == OK_Ordinary)
1521 VK = BaseExpr->getValueKind();
1522 else
1523 VK = VK_RValue;
1524 }
1525 if (VK != VK_RValue && Field->isBitField())
1526 OK = OK_BitField;
1527
1528 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1529 QualType MemberType = Field->getType();
1530 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1531 MemberType = Ref->getPointeeType();
1532 VK = VK_LValue;
1533 } else {
1534 QualType BaseType = BaseExpr->getType();
1535 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1536
1537 Qualifiers BaseQuals = BaseType.getQualifiers();
1538
1539 // GC attributes are never picked up by members.
1540 BaseQuals.removeObjCGCAttr();
1541
1542 // CVR attributes from the base are picked up by members,
1543 // except that 'mutable' members don't pick up 'const'.
1544 if (Field->isMutable()) BaseQuals.removeConst();
1545
1546 Qualifiers MemberQuals
1547 = S.Context.getCanonicalType(MemberType).getQualifiers();
1548
1549 // TR 18037 does not allow fields to be declared with address spaces.
1550 assert(!MemberQuals.hasAddressSpace());
1551
1552 Qualifiers Combined = BaseQuals + MemberQuals;
1553 if (Combined != MemberQuals)
1554 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1555 }
1556
1557 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1558 ExprResult Base =
1559 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1560 FoundDecl, Field);
1561 if (Base.isInvalid())
1562 return ExprError();
1563 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
1564 Field, FoundDecl, MemberNameInfo,
1565 MemberType, VK, OK));
1566}
1567
1568/// Builds an implicit member access expression. The current context
1569/// is known to be an instance method, and the given unqualified lookup
1570/// set is known to contain only instance members, at least one of which
1571/// is from an appropriate type.
1572ExprResult
1573Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1574 LookupResult &R,
1575 const TemplateArgumentListInfo *TemplateArgs,
1576 bool IsKnownInstance) {
1577 assert(!R.empty() && !R.isAmbiguous());
1578
1579 SourceLocation loc = R.getNameLoc();
1580
1581 // We may have found a field within an anonymous union or struct
1582 // (C++ [class.union]).
1583 // FIXME: template-ids inside anonymous structs?
1584 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1585 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1586
1587 // If this is known to be an instance access, go ahead and build an
1588 // implicit 'this' expression now.
1589 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001590 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001591 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1592
1593 Expr *baseExpr = 0; // null signifies implicit access
1594 if (IsKnownInstance) {
1595 SourceLocation Loc = R.getNameLoc();
1596 if (SS.getRange().isValid())
1597 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001598 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001599 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1600 }
1601
1602 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1603 /*OpLoc*/ SourceLocation(),
1604 /*IsArrow*/ true,
1605 SS,
1606 /*FirstQualifierInScope*/ 0,
1607 R, TemplateArgs);
1608}