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