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