blob: 26b88a2a7ee17ffc61b2713e655f7d2910fce4ca [file] [log] [blame]
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001//===--- SemaExprMember.cpp - Semantic Analysis for Expressions -----------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis member access expressions.
11//
12//===----------------------------------------------------------------------===//
13#include "clang/Sema/SemaInternal.h"
14#include "clang/Sema/Lookup.h"
15#include "clang/Sema/Scope.h"
16#include "clang/AST/DeclCXX.h"
17#include "clang/AST/DeclObjC.h"
18#include "clang/AST/DeclTemplate.h"
19#include "clang/AST/ExprCXX.h"
20#include "clang/AST/ExprObjC.h"
21#include "clang/Lex/Preprocessor.h"
22
23using namespace clang;
24using namespace sema;
25
26/// Determines if the given class is provably not derived from all of
27/// the prospective base classes.
28static bool IsProvablyNotDerivedFrom(Sema &SemaRef,
29 CXXRecordDecl *Record,
30 const llvm::SmallPtrSet<CXXRecordDecl*, 4> &Bases) {
31 if (Bases.count(Record->getCanonicalDecl()))
32 return false;
33
34 RecordDecl *RD = Record->getDefinition();
35 if (!RD) return false;
36 Record = cast<CXXRecordDecl>(RD);
37
38 for (CXXRecordDecl::base_class_iterator I = Record->bases_begin(),
39 E = Record->bases_end(); I != E; ++I) {
40 CanQualType BaseT = SemaRef.Context.getCanonicalType((*I).getType());
41 CanQual<RecordType> BaseRT = BaseT->getAs<RecordType>();
42 if (!BaseRT) return false;
43
44 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
45 if (!IsProvablyNotDerivedFrom(SemaRef, BaseRecord, Bases))
46 return false;
47 }
48
49 return true;
50}
51
52enum IMAKind {
53 /// The reference is definitely not an instance member access.
54 IMA_Static,
55
56 /// The reference may be an implicit instance member access.
57 IMA_Mixed,
58
Eli Friedman9bc291d2012-01-18 03:53:45 +000059 /// The reference may be to an instance member, but it might be invalid if
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000060 /// so, because the context is not an instance method.
61 IMA_Mixed_StaticContext,
62
63 /// The reference may be to an instance member, but it is invalid if
64 /// so, because the context is from an unrelated class.
65 IMA_Mixed_Unrelated,
66
67 /// The reference is definitely an implicit instance member access.
68 IMA_Instance,
69
70 /// The reference may be to an unresolved using declaration.
71 IMA_Unresolved,
72
73 /// The reference may be to an unresolved using declaration and the
74 /// context is not an instance method.
75 IMA_Unresolved_StaticContext,
76
Eli Friedmanef331b72012-01-20 01:26:23 +000077 // The reference refers to a field which is not a member of the containing
78 // class, which is allowed because we're in C++11 mode and the context is
79 // unevaluated.
80 IMA_Field_Uneval_Context,
Eli Friedman9bc291d2012-01-18 03:53:45 +000081
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000082 /// All possible referrents are instance members and the current
83 /// context is not an instance method.
84 IMA_Error_StaticContext,
85
86 /// All possible referrents are instance members of an unrelated
87 /// class.
88 IMA_Error_Unrelated
89};
90
91/// The given lookup names class member(s) and is not being used for
92/// an address-of-member expression. Classify the type of access
93/// according to whether it's possible that this reference names an
Eli Friedman9bc291d2012-01-18 03:53:45 +000094/// instance member. This is best-effort in dependent contexts; it is okay to
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +000095/// conservatively answer "yes", in which case some errors will simply
96/// not be caught until template-instantiation.
97static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
98 Scope *CurScope,
99 const LookupResult &R) {
100 assert(!R.empty() && (*R.begin())->isCXXClassMember());
101
102 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
103
104 bool isStaticContext =
105 (!isa<CXXMethodDecl>(DC) ||
106 cast<CXXMethodDecl>(DC)->isStatic());
107
108 // C++0x [expr.prim]p4:
109 // Otherwise, if a member-declarator declares a non-static data member
110 // of a class X, the expression this is a prvalue of type "pointer to X"
111 // within the optional brace-or-equal-initializer.
112 if (CurScope->getFlags() & Scope::ThisScope)
113 isStaticContext = false;
114
115 if (R.isUnresolvableResult())
116 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
117
118 // Collect all the declaring classes of instance members we find.
119 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000120 bool isField = false;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000121 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
122 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
123 NamedDecl *D = *I;
124
125 if (D->isCXXInstanceMember()) {
126 if (dyn_cast<FieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000127 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000128
129 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
130 Classes.insert(R->getCanonicalDecl());
131 }
132 else
133 hasNonInstance = true;
134 }
135
136 // If we didn't find any instance members, it can't be an implicit
137 // member reference.
138 if (Classes.empty())
139 return IMA_Static;
140
Richard Smithd390de92012-02-25 10:20:59 +0000141 bool IsCXX11UnevaluatedField = false;
David Blaikie4e4d0842012-03-11 07:00:24 +0000142 if (SemaRef.getLangOpts().CPlusPlus0x && isField) {
Richard Smith2c8aee42012-02-25 10:04:07 +0000143 // C++11 [expr.prim.general]p12:
144 // An id-expression that denotes a non-static data member or non-static
145 // member function of a class can only be used:
146 // (...)
147 // - if that id-expression denotes a non-static data member and it
148 // appears in an unevaluated operand.
149 const Sema::ExpressionEvaluationContextRecord& record
150 = SemaRef.ExprEvalContexts.back();
151 if (record.Context == Sema::Unevaluated)
Richard Smithd390de92012-02-25 10:20:59 +0000152 IsCXX11UnevaluatedField = true;
Richard Smith2c8aee42012-02-25 10:04:07 +0000153 }
154
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000155 // If the current context is not an instance method, it can't be
156 // an implicit member reference.
157 if (isStaticContext) {
158 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000159 return IMA_Mixed_StaticContext;
160
Richard Smithd390de92012-02-25 10:20:59 +0000161 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
162 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000163 }
164
165 CXXRecordDecl *contextClass;
166 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
167 contextClass = MD->getParent()->getCanonicalDecl();
168 else
169 contextClass = cast<CXXRecordDecl>(DC);
170
171 // [class.mfct.non-static]p3:
172 // ...is used in the body of a non-static member function of class X,
173 // if name lookup (3.4.1) resolves the name in the id-expression to a
174 // non-static non-type member of some class C [...]
175 // ...if C is not X or a base class of X, the class member access expression
176 // is ill-formed.
177 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000178 contextClass->getCanonicalDecl() !=
179 R.getNamingClass()->getCanonicalDecl() &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000180 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
Richard Smithd390de92012-02-25 10:20:59 +0000181 return hasNonInstance ? IMA_Mixed_Unrelated :
182 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
183 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000184
185 // If we can prove that the current context is unrelated to all the
186 // declaring classes, it can't be an implicit member reference (in
187 // which case it's an error if any of those members are selected).
188 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
Richard Smithd390de92012-02-25 10:20:59 +0000189 return hasNonInstance ? IMA_Mixed_Unrelated :
190 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
191 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000192
193 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
194}
195
196/// Diagnose a reference to a field with no object available.
Richard Smitha85cf392012-04-05 01:13:04 +0000197static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000198 const CXXScopeSpec &SS,
Richard Smitha85cf392012-04-05 01:13:04 +0000199 NamedDecl *Rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000200 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000201 SourceLocation Loc = nameInfo.getLoc();
202 SourceRange Range(Loc);
203 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman9bc291d2012-01-18 03:53:45 +0000204
Richard Smitha85cf392012-04-05 01:13:04 +0000205 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
206 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
207 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
208 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
209
210 bool InStaticMethod = Method && Method->isStatic();
211 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
212
213 if (IsField && InStaticMethod)
214 // "invalid use of member 'x' in static member function"
215 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
216 << Range << nameInfo.getName();
217 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
218 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
219 // Unqualified lookup in a non-static member function found a member of an
220 // enclosing class.
221 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
222 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
223 else if (IsField)
Eli Friedmanef331b72012-01-20 01:26:23 +0000224 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smitha85cf392012-04-05 01:13:04 +0000225 << nameInfo.getName() << Range;
226 else
227 SemaRef.Diag(Loc, diag::err_member_call_without_object)
228 << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000229}
230
231/// Builds an expression which might be an implicit member expression.
232ExprResult
233Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000234 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000235 LookupResult &R,
236 const TemplateArgumentListInfo *TemplateArgs) {
237 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
238 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000239 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000240
241 case IMA_Mixed:
242 case IMA_Mixed_Unrelated:
243 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000244 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000245
Richard Smithd390de92012-02-25 10:20:59 +0000246 case IMA_Field_Uneval_Context:
247 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
248 << R.getLookupNameInfo().getName();
249 // Fall through.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000250 case IMA_Static:
251 case IMA_Mixed_StaticContext:
252 case IMA_Unresolved_StaticContext:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000253 if (TemplateArgs || TemplateKWLoc.isValid())
254 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000255 return BuildDeclarationNameExpr(SS, R, false);
256
257 case IMA_Error_StaticContext:
258 case IMA_Error_Unrelated:
Richard Smitha85cf392012-04-05 01:13:04 +0000259 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000260 R.getLookupNameInfo());
261 return ExprError();
262 }
263
264 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000265}
266
267/// Check an ext-vector component access expression.
268///
269/// VK should be set in advance to the value kind of the base
270/// expression.
271static QualType
272CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
273 SourceLocation OpLoc, const IdentifierInfo *CompName,
274 SourceLocation CompLoc) {
275 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
276 // see FIXME there.
277 //
278 // FIXME: This logic can be greatly simplified by splitting it along
279 // halving/not halving and reworking the component checking.
280 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
281
282 // The vector accessor can't exceed the number of elements.
283 const char *compStr = CompName->getNameStart();
284
285 // This flag determines whether or not the component is one of the four
286 // special names that indicate a subset of exactly half the elements are
287 // to be selected.
288 bool HalvingSwizzle = false;
289
290 // This flag determines whether or not CompName has an 's' char prefix,
291 // indicating that it is a string of hex values to be used as vector indices.
292 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
293
294 bool HasRepeated = false;
295 bool HasIndex[16] = {};
296
297 int Idx;
298
299 // Check that we've found one of the special components, or that the component
300 // names must come from the same set.
301 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
302 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
303 HalvingSwizzle = true;
304 } else if (!HexSwizzle &&
305 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
306 do {
307 if (HasIndex[Idx]) HasRepeated = true;
308 HasIndex[Idx] = true;
309 compStr++;
310 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
311 } else {
312 if (HexSwizzle) compStr++;
313 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
314 if (HasIndex[Idx]) HasRepeated = true;
315 HasIndex[Idx] = true;
316 compStr++;
317 }
318 }
319
320 if (!HalvingSwizzle && *compStr) {
321 // We didn't get to the end of the string. This means the component names
322 // didn't come from the same set *or* we encountered an illegal name.
323 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000324 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000325 return QualType();
326 }
327
328 // Ensure no component accessor exceeds the width of the vector type it
329 // operates on.
330 if (!HalvingSwizzle) {
331 compStr = CompName->getNameStart();
332
333 if (HexSwizzle)
334 compStr++;
335
336 while (*compStr) {
337 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
338 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
339 << baseType << SourceRange(CompLoc);
340 return QualType();
341 }
342 }
343 }
344
345 // The component accessor looks fine - now we need to compute the actual type.
346 // The vector type is implied by the component accessor. For example,
347 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
348 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
349 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
350 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
351 : CompName->getLength();
352 if (HexSwizzle)
353 CompSize--;
354
355 if (CompSize == 1)
356 return vecType->getElementType();
357
358 if (HasRepeated) VK = VK_RValue;
359
360 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
361 // Now look up the TypeDefDecl from the vector type. Without this,
362 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000363 for (Sema::ExtVectorDeclsType::iterator
364 I = S.ExtVectorDecls.begin(S.ExternalSource),
365 E = S.ExtVectorDecls.end();
366 I != E; ++I) {
367 if ((*I)->getUnderlyingType() == VT)
368 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000369 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000370
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000371 return VT; // should never get here (a typedef type should always be found).
372}
373
374static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
375 IdentifierInfo *Member,
376 const Selector &Sel,
377 ASTContext &Context) {
378 if (Member)
379 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
380 return PD;
381 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
382 return OMD;
383
384 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
385 E = PDecl->protocol_end(); I != E; ++I) {
386 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
387 Context))
388 return D;
389 }
390 return 0;
391}
392
393static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
394 IdentifierInfo *Member,
395 const Selector &Sel,
396 ASTContext &Context) {
397 // Check protocols on qualified interfaces.
398 Decl *GDecl = 0;
399 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
400 E = QIdTy->qual_end(); I != E; ++I) {
401 if (Member)
402 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
403 GDecl = PD;
404 break;
405 }
406 // Also must look for a getter or setter name which uses property syntax.
407 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
408 GDecl = OMD;
409 break;
410 }
411 }
412 if (!GDecl) {
413 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
414 E = QIdTy->qual_end(); I != E; ++I) {
415 // Search in the protocol-qualifier list of current protocol.
416 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
417 Context);
418 if (GDecl)
419 return GDecl;
420 }
421 }
422 return GDecl;
423}
424
425ExprResult
426Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
427 bool IsArrow, SourceLocation OpLoc,
428 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000429 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000430 NamedDecl *FirstQualifierInScope,
431 const DeclarationNameInfo &NameInfo,
432 const TemplateArgumentListInfo *TemplateArgs) {
433 // Even in dependent contexts, try to diagnose base expressions with
434 // obviously wrong types, e.g.:
435 //
436 // T* t;
437 // t.f;
438 //
439 // In Obj-C++, however, the above expression is valid, since it could be
440 // accessing the 'f' property if T is an Obj-C interface. The extra check
441 // allows this, while still reporting an error if T is a struct pointer.
442 if (!IsArrow) {
443 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikie4e4d0842012-03-11 07:00:24 +0000444 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000445 PT->getPointeeType()->isRecordType())) {
446 assert(BaseExpr && "cannot happen with implicit member accesses");
447 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
448 << BaseType << BaseExpr->getSourceRange();
449 return ExprError();
450 }
451 }
452
453 assert(BaseType->isDependentType() ||
454 NameInfo.getName().isDependentName() ||
455 isDependentScopeSpecifier(SS));
456
457 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
458 // must have pointer type, and the accessed type is the pointee.
459 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
460 IsArrow, OpLoc,
461 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000462 TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000463 FirstQualifierInScope,
464 NameInfo, TemplateArgs));
465}
466
467/// We know that the given qualified member reference points only to
468/// declarations which do not belong to the static type of the base
469/// expression. Diagnose the problem.
470static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
471 Expr *BaseExpr,
472 QualType BaseType,
473 const CXXScopeSpec &SS,
474 NamedDecl *rep,
475 const DeclarationNameInfo &nameInfo) {
476 // If this is an implicit member access, use a different set of
477 // diagnostics.
478 if (!BaseExpr)
Richard Smitha85cf392012-04-05 01:13:04 +0000479 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000480
481 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
482 << SS.getRange() << rep << BaseType;
483}
484
485// Check whether the declarations we found through a nested-name
486// specifier in a member expression are actually members of the base
487// type. The restriction here is:
488//
489// C++ [expr.ref]p2:
490// ... In these cases, the id-expression shall name a
491// member of the class or of one of its base classes.
492//
493// So it's perfectly legitimate for the nested-name specifier to name
494// an unrelated class, and for us to find an overload set including
495// decls from classes which are not superclasses, as long as the decl
496// we actually pick through overload resolution is from a superclass.
497bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
498 QualType BaseType,
499 const CXXScopeSpec &SS,
500 const LookupResult &R) {
501 const RecordType *BaseRT = BaseType->getAs<RecordType>();
502 if (!BaseRT) {
503 // We can't check this yet because the base type is still
504 // dependent.
505 assert(BaseType->isDependentType());
506 return false;
507 }
508 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
509
510 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
511 // If this is an implicit member reference and we find a
512 // non-instance member, it's not an error.
513 if (!BaseExpr && !(*I)->isCXXInstanceMember())
514 return false;
515
516 // Note that we use the DC of the decl, not the underlying decl.
517 DeclContext *DC = (*I)->getDeclContext();
518 while (DC->isTransparentContext())
519 DC = DC->getParent();
520
521 if (!DC->isRecord())
522 continue;
523
524 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
525 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
526
527 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
528 return false;
529 }
530
531 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
532 R.getRepresentativeDecl(),
533 R.getLookupNameInfo());
534 return true;
535}
536
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000537namespace {
538
539// Callback to only accept typo corrections that are either a ValueDecl or a
540// FunctionTemplateDecl.
541class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
542 public:
543 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
544 NamedDecl *ND = candidate.getCorrectionDecl();
545 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
546 }
547};
548
549}
550
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000551static bool
552LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
553 SourceRange BaseRange, const RecordType *RTy,
554 SourceLocation OpLoc, CXXScopeSpec &SS,
555 bool HasTemplateArgs) {
556 RecordDecl *RDecl = RTy->getDecl();
557 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
558 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
559 << BaseRange))
560 return true;
561
562 if (HasTemplateArgs) {
563 // LookupTemplateName doesn't expect these both to exist simultaneously.
564 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
565
566 bool MOUS;
567 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
568 return false;
569 }
570
571 DeclContext *DC = RDecl;
572 if (SS.isSet()) {
573 // If the member name was a qualified-id, look into the
574 // nested-name-specifier.
575 DC = SemaRef.computeDeclContext(SS, false);
576
577 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
578 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
579 << SS.getRange() << DC;
580 return true;
581 }
582
583 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
584
585 if (!isa<TypeDecl>(DC)) {
586 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
587 << DC << SS.getRange();
588 return true;
589 }
590 }
591
592 // The record definition is complete, now look up the member.
593 SemaRef.LookupQualifiedName(R, DC);
594
595 if (!R.empty())
596 return false;
597
598 // We didn't find anything with the given name, so try to correct
599 // for typos.
600 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000601 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000602 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
603 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000604 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000605 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000606 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000607 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000608 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000609 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000610 Corrected.getQuoted(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000611 R.setLookupName(Corrected.getCorrection());
612 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000613 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000614 << Name << DC << CorrectedQuotedStr << SS.getRange()
615 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
616 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
617 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000618 }
619
620 return false;
621}
622
623ExprResult
624Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
625 SourceLocation OpLoc, bool IsArrow,
626 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000627 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000628 NamedDecl *FirstQualifierInScope,
629 const DeclarationNameInfo &NameInfo,
630 const TemplateArgumentListInfo *TemplateArgs) {
631 if (BaseType->isDependentType() ||
632 (SS.isSet() && isDependentScopeSpecifier(SS)))
633 return ActOnDependentMemberExpr(Base, BaseType,
634 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000635 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000636 NameInfo, TemplateArgs);
637
638 LookupResult R(*this, NameInfo, LookupMemberName);
639
640 // Implicit member accesses.
641 if (!Base) {
642 QualType RecordTy = BaseType;
643 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
644 if (LookupMemberExprInRecord(*this, R, SourceRange(),
645 RecordTy->getAs<RecordType>(),
646 OpLoc, SS, TemplateArgs != 0))
647 return ExprError();
648
649 // Explicit member accesses.
650 } else {
651 ExprResult BaseResult = Owned(Base);
652 ExprResult Result =
653 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
654 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
655
656 if (BaseResult.isInvalid())
657 return ExprError();
658 Base = BaseResult.take();
659
660 if (Result.isInvalid()) {
661 Owned(Base);
662 return ExprError();
663 }
664
665 if (Result.get())
666 return move(Result);
667
668 // LookupMemberExpr can modify Base, and thus change BaseType
669 BaseType = Base->getType();
670 }
671
672 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000673 OpLoc, IsArrow, SS, TemplateKWLoc,
674 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000675}
676
677static ExprResult
678BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
679 const CXXScopeSpec &SS, FieldDecl *Field,
680 DeclAccessPair FoundDecl,
681 const DeclarationNameInfo &MemberNameInfo);
682
683ExprResult
684Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
685 SourceLocation loc,
686 IndirectFieldDecl *indirectField,
687 Expr *baseObjectExpr,
688 SourceLocation opLoc) {
689 // First, build the expression that refers to the base object.
690
691 bool baseObjectIsPointer = false;
692 Qualifiers baseQuals;
693
694 // Case 1: the base of the indirect field is not a field.
695 VarDecl *baseVariable = indirectField->getVarDecl();
696 CXXScopeSpec EmptySS;
697 if (baseVariable) {
698 assert(baseVariable->getType()->isRecordType());
699
700 // In principle we could have a member access expression that
701 // accesses an anonymous struct/union that's a static member of
702 // the base object's class. However, under the current standard,
703 // static data members cannot be anonymous structs or unions.
704 // Supporting this is as easy as building a MemberExpr here.
705 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
706
707 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
708
709 ExprResult result
710 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
711 if (result.isInvalid()) return ExprError();
712
713 baseObjectExpr = result.take();
714 baseObjectIsPointer = false;
715 baseQuals = baseObjectExpr->getType().getQualifiers();
716
717 // Case 2: the base of the indirect field is a field and the user
718 // wrote a member expression.
719 } else if (baseObjectExpr) {
720 // The caller provided the base object expression. Determine
721 // whether its a pointer and whether it adds any qualifiers to the
722 // anonymous struct/union fields we're looking into.
723 QualType objectType = baseObjectExpr->getType();
724
725 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
726 baseObjectIsPointer = true;
727 objectType = ptr->getPointeeType();
728 } else {
729 baseObjectIsPointer = false;
730 }
731 baseQuals = objectType.getQualifiers();
732
733 // Case 3: the base of the indirect field is a field and we should
734 // build an implicit member access.
735 } else {
736 // We've found a member of an anonymous struct/union that is
737 // inside a non-anonymous struct/union, so in a well-formed
738 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000739 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000740 if (ThisTy.isNull()) {
741 Diag(loc, diag::err_invalid_member_use_in_static_method)
742 << indirectField->getDeclName();
743 return ExprError();
744 }
745
746 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000747 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000748 baseObjectExpr
749 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
750 baseObjectIsPointer = true;
751 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
752 }
753
754 // Build the implicit member references to the field of the
755 // anonymous struct/union.
756 Expr *result = baseObjectExpr;
757 IndirectFieldDecl::chain_iterator
758 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
759
760 // Build the first member access in the chain with full information.
761 if (!baseVariable) {
762 FieldDecl *field = cast<FieldDecl>(*FI);
763
764 // FIXME: use the real found-decl info!
765 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
766
767 // Make a nameInfo that properly uses the anonymous name.
768 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
769
770 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
771 EmptySS, field, foundDecl,
772 memberNameInfo).take();
773 baseObjectIsPointer = false;
774
775 // FIXME: check qualified member access
776 }
777
778 // In all cases, we should now skip the first declaration in the chain.
779 ++FI;
780
781 while (FI != FEnd) {
782 FieldDecl *field = cast<FieldDecl>(*FI++);
783
784 // FIXME: these are somewhat meaningless
785 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
786 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
787
788 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
789 (FI == FEnd? SS : EmptySS), field,
790 foundDecl, memberNameInfo).take();
791 }
792
793 return Owned(result);
794}
795
796/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000797static MemberExpr *BuildMemberExpr(Sema &SemaRef,
798 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000799 const CXXScopeSpec &SS,
800 SourceLocation TemplateKWLoc,
801 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000802 DeclAccessPair FoundDecl,
803 const DeclarationNameInfo &MemberNameInfo,
804 QualType Ty,
805 ExprValueKind VK, ExprObjectKind OK,
806 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000807 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000808 MemberExpr *E =
809 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
810 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
811 TemplateArgs, Ty, VK, OK);
812 SemaRef.MarkMemberReferenced(E);
813 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000814}
815
816ExprResult
817Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
818 SourceLocation OpLoc, bool IsArrow,
819 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000820 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000821 NamedDecl *FirstQualifierInScope,
822 LookupResult &R,
823 const TemplateArgumentListInfo *TemplateArgs,
824 bool SuppressQualifierCheck) {
825 QualType BaseType = BaseExprType;
826 if (IsArrow) {
827 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000828 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000829 }
830 R.setBaseObjectType(BaseType);
831
832 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
833 DeclarationName MemberName = MemberNameInfo.getName();
834 SourceLocation MemberLoc = MemberNameInfo.getLoc();
835
836 if (R.isAmbiguous())
837 return ExprError();
838
839 if (R.empty()) {
840 // Rederive where we looked up.
841 DeclContext *DC = (SS.isSet()
842 ? computeDeclContext(SS, false)
843 : BaseType->getAs<RecordType>()->getDecl());
844
845 Diag(R.getNameLoc(), diag::err_no_member)
846 << MemberName << DC
847 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
848 return ExprError();
849 }
850
851 // Diagnose lookups that find only declarations from a non-base
852 // type. This is possible for either qualified lookups (which may
853 // have been qualified with an unrelated type) or implicit member
854 // expressions (which were found with unqualified lookup and thus
855 // may have come from an enclosing scope). Note that it's okay for
856 // lookup to find declarations from a non-base type as long as those
857 // aren't the ones picked by overload resolution.
858 if ((SS.isSet() || !BaseExpr ||
859 (isa<CXXThisExpr>(BaseExpr) &&
860 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
861 !SuppressQualifierCheck &&
862 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
863 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000864
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000865 // Construct an unresolved result if we in fact got an unresolved
866 // result.
867 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
868 // Suppress any lookup-related diagnostics; we'll do these when we
869 // pick a member.
870 R.suppressDiagnostics();
871
872 UnresolvedMemberExpr *MemExpr
873 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
874 BaseExpr, BaseExprType,
875 IsArrow, OpLoc,
876 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000877 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000878 TemplateArgs, R.begin(), R.end());
879
880 return Owned(MemExpr);
881 }
882
883 assert(R.isSingleResult());
884 DeclAccessPair FoundDecl = R.begin().getPair();
885 NamedDecl *MemberDecl = R.getFoundDecl();
886
887 // FIXME: diagnose the presence of template arguments now.
888
889 // If the decl being referenced had an error, return an error for this
890 // sub-expr without emitting another error, in order to avoid cascading
891 // error cases.
892 if (MemberDecl->isInvalidDecl())
893 return ExprError();
894
895 // Handle the implicit-member-access case.
896 if (!BaseExpr) {
897 // If this is not an instance member, convert to a non-member access.
898 if (!MemberDecl->isCXXInstanceMember())
899 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
900
901 SourceLocation Loc = R.getNameLoc();
902 if (SS.getRange().isValid())
903 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000904 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000905 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
906 }
907
908 bool ShouldCheckUse = true;
909 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
910 // Don't diagnose the use of a virtual member function unless it's
911 // explicitly qualified.
912 if (MD->isVirtual() && !SS.isSet())
913 ShouldCheckUse = false;
914 }
915
916 // Check the use of this member.
917 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
918 Owned(BaseExpr);
919 return ExprError();
920 }
921
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000922 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
923 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
924 SS, FD, FoundDecl, MemberNameInfo);
925
926 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
927 // We may have found a field within an anonymous union or struct
928 // (C++ [class.union]).
929 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
930 BaseExpr, OpLoc);
931
932 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000933 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
934 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000935 Var->getType().getNonReferenceType(),
936 VK_LValue, OK_Ordinary));
937 }
938
939 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
940 ExprValueKind valueKind;
941 QualType type;
942 if (MemberFn->isInstance()) {
943 valueKind = VK_RValue;
944 type = Context.BoundMemberTy;
945 } else {
946 valueKind = VK_LValue;
947 type = MemberFn->getType();
948 }
949
Eli Friedman5f2987c2012-02-02 03:46:19 +0000950 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
951 TemplateKWLoc, MemberFn, FoundDecl,
952 MemberNameInfo, type, valueKind,
953 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000954 }
955 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
956
957 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000958 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
959 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000960 Enum->getType(), VK_RValue, OK_Ordinary));
961 }
962
963 Owned(BaseExpr);
964
965 // We found something that we didn't expect. Complain.
966 if (isa<TypeDecl>(MemberDecl))
967 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
968 << MemberName << BaseType << int(IsArrow);
969 else
970 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
971 << MemberName << BaseType << int(IsArrow);
972
973 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
974 << MemberName;
975 R.suppressDiagnostics();
976 return ExprError();
977}
978
979/// Given that normal member access failed on the given expression,
980/// and given that the expression's type involves builtin-id or
981/// builtin-Class, decide whether substituting in the redefinition
982/// types would be profitable. The redefinition type is whatever
983/// this translation unit tried to typedef to id/Class; we store
984/// it to the side and then re-use it in places like this.
985static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
986 const ObjCObjectPointerType *opty
987 = base.get()->getType()->getAs<ObjCObjectPointerType>();
988 if (!opty) return false;
989
990 const ObjCObjectType *ty = opty->getObjectType();
991
992 QualType redef;
993 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000994 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000995 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000996 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000997 } else {
998 return false;
999 }
1000
1001 // Do the substitution as long as the redefinition type isn't just a
1002 // possibly-qualified pointer to builtin-id or builtin-Class again.
1003 opty = redef->getAs<ObjCObjectPointerType>();
1004 if (opty && !opty->getObjectType()->getInterface() != 0)
1005 return false;
1006
1007 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1008 return true;
1009}
1010
John McCall6dbba4f2011-10-11 23:14:30 +00001011static bool isRecordType(QualType T) {
1012 return T->isRecordType();
1013}
1014static bool isPointerToRecordType(QualType T) {
1015 if (const PointerType *PT = T->getAs<PointerType>())
1016 return PT->getPointeeType()->isRecordType();
1017 return false;
1018}
1019
Richard Smith9138b4e2011-10-26 19:06:56 +00001020/// Perform conversions on the LHS of a member access expression.
1021ExprResult
1022Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001023 if (IsArrow && !Base->getType()->isFunctionType())
1024 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001025
Eli Friedman059d5782012-01-13 02:20:01 +00001026 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001027}
1028
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001029/// Look up the given member of the given non-type-dependent
1030/// expression. This can return in one of two ways:
1031/// * If it returns a sentinel null-but-valid result, the caller will
1032/// assume that lookup was performed and the results written into
1033/// the provided structure. It will take over from there.
1034/// * Otherwise, the returned expression will be produced in place of
1035/// an ordinary member expression.
1036///
1037/// The ObjCImpDecl bit is a gross hack that will need to be properly
1038/// fixed for ObjC++.
1039ExprResult
1040Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1041 bool &IsArrow, SourceLocation OpLoc,
1042 CXXScopeSpec &SS,
1043 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1044 assert(BaseExpr.get() && "no base expression");
1045
1046 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001047 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001048 if (BaseExpr.isInvalid())
1049 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001050
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001051 QualType BaseType = BaseExpr.get()->getType();
1052 assert(!BaseType->isDependentType());
1053
1054 DeclarationName MemberName = R.getLookupName();
1055 SourceLocation MemberLoc = R.getNameLoc();
1056
1057 // For later type-checking purposes, turn arrow accesses into dot
1058 // accesses. The only access type we support that doesn't follow
1059 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1060 // and those never use arrows, so this is unaffected.
1061 if (IsArrow) {
1062 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1063 BaseType = Ptr->getPointeeType();
1064 else if (const ObjCObjectPointerType *Ptr
1065 = BaseType->getAs<ObjCObjectPointerType>())
1066 BaseType = Ptr->getPointeeType();
1067 else if (BaseType->isRecordType()) {
1068 // Recover from arrow accesses to records, e.g.:
1069 // struct MyRecord foo;
1070 // foo->bar
1071 // This is actually well-formed in C++ if MyRecord has an
1072 // overloaded operator->, but that should have been dealt with
1073 // by now.
1074 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1075 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1076 << FixItHint::CreateReplacement(OpLoc, ".");
1077 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001078 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001079 goto fail;
1080 } else {
1081 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1082 << BaseType << BaseExpr.get()->getSourceRange();
1083 return ExprError();
1084 }
1085 }
1086
1087 // Handle field access to simple records.
1088 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1089 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1090 RTy, OpLoc, SS, HasTemplateArgs))
1091 return ExprError();
1092
1093 // Returning valid-but-null is how we indicate to the caller that
1094 // the lookup result was filled in.
1095 return Owned((Expr*) 0);
1096 }
1097
1098 // Handle ivar access to Objective-C objects.
1099 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001100 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001101 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1102 << 1 << SS.getScopeRep()
1103 << FixItHint::CreateRemoval(SS.getRange());
1104 SS.clear();
1105 }
1106
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001107 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1108
1109 // There are three cases for the base type:
1110 // - builtin id (qualified or unqualified)
1111 // - builtin Class (qualified or unqualified)
1112 // - an interface
1113 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1114 if (!IDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001115 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001116 (OTy->isObjCId() || OTy->isObjCClass()))
1117 goto fail;
1118 // There's an implicit 'isa' ivar on all objects.
1119 // But we only actually find it this way on objects of type 'id',
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001120 // apparently.ghjg
1121 if (OTy->isObjCId() && Member->isStr("isa")) {
1122 Diag(MemberLoc, diag::warn_objc_isa_use);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001123 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1124 Context.getObjCClassType()));
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001125 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001126
1127 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1128 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1129 ObjCImpDecl, HasTemplateArgs);
1130 goto fail;
1131 }
1132
Douglas Gregord07cc362012-01-02 17:18:37 +00001133 if (RequireCompleteType(OpLoc, BaseType,
1134 PDiag(diag::err_typecheck_incomplete_tag)
1135 << BaseExpr.get()->getSourceRange()))
1136 return ExprError();
1137
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001138 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001139 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1140
1141 if (!IV) {
1142 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001143 DeclFilterCCC<ObjCIvarDecl> Validator;
1144 Validator.IsObjCIvarLookup = IsArrow;
1145 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1146 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001147 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001148 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001149 Diag(R.getNameLoc(),
1150 diag::err_typecheck_member_reference_ivar_suggest)
1151 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1152 << FixItHint::CreateReplacement(R.getNameLoc(),
1153 IV->getNameAsString());
1154 Diag(IV->getLocation(), diag::note_previous_decl)
1155 << IV->getDeclName();
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001156
1157 // Figure out the class that declares the ivar.
1158 assert(!ClassDeclared);
1159 Decl *D = cast<Decl>(IV->getDeclContext());
1160 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1161 D = CAT->getClassInterface();
1162 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001163 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001164 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1165 Diag(MemberLoc,
1166 diag::err_property_found_suggest)
1167 << Member << BaseExpr.get()->getType()
1168 << FixItHint::CreateReplacement(OpLoc, ".");
1169 return ExprError();
1170 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001171
1172 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1173 << IDecl->getDeclName() << MemberName
1174 << BaseExpr.get()->getSourceRange();
1175 return ExprError();
1176 }
1177 }
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001178
1179 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001180
1181 // If the decl being referenced had an error, return an error for this
1182 // sub-expr without emitting another error, in order to avoid cascading
1183 // error cases.
1184 if (IV->isInvalidDecl())
1185 return ExprError();
1186
1187 // Check whether we can reference this field.
1188 if (DiagnoseUseOfDecl(IV, MemberLoc))
1189 return ExprError();
1190 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1191 IV->getAccessControl() != ObjCIvarDecl::Package) {
1192 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1193 if (ObjCMethodDecl *MD = getCurMethodDecl())
1194 ClassOfMethodDecl = MD->getClassInterface();
1195 else if (ObjCImpDecl && getCurFunctionDecl()) {
1196 // Case of a c-function declared inside an objc implementation.
1197 // FIXME: For a c-style function nested inside an objc implementation
1198 // class, there is no implementation context available, so we pass
1199 // down the context as argument to this routine. Ideally, this context
1200 // need be passed down in the AST node and somehow calculated from the
1201 // AST for a function decl.
1202 if (ObjCImplementationDecl *IMPD =
1203 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1204 ClassOfMethodDecl = IMPD->getClassInterface();
1205 else if (ObjCCategoryImplDecl* CatImplClass =
1206 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1207 ClassOfMethodDecl = CatImplClass->getClassInterface();
1208 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001209 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001210 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1211 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1212 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1213 Diag(MemberLoc, diag::error_private_ivar_access)
1214 << IV->getDeclName();
1215 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1216 // @protected
1217 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001218 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001219 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001220 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001221 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001222 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1223 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1224 if (UO->getOpcode() == UO_Deref)
1225 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1226
1227 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1228 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1229 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1230 }
1231
1232 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1233 MemberLoc, BaseExpr.take(),
1234 IsArrow));
1235 }
1236
1237 // Objective-C property access.
1238 const ObjCObjectPointerType *OPT;
1239 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001240 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001241 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1242 << 0 << SS.getScopeRep()
1243 << FixItHint::CreateRemoval(SS.getRange());
1244 SS.clear();
1245 }
1246
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001247 // This actually uses the base as an r-value.
1248 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1249 if (BaseExpr.isInvalid())
1250 return ExprError();
1251
1252 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1253
1254 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1255
1256 const ObjCObjectType *OT = OPT->getObjectType();
1257
1258 // id, with and without qualifiers.
1259 if (OT->isObjCId()) {
1260 // Check protocols on qualified interfaces.
1261 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1262 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1263 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1264 // Check the use of this declaration
1265 if (DiagnoseUseOfDecl(PD, MemberLoc))
1266 return ExprError();
1267
John McCall3c3b7f92011-10-25 17:37:35 +00001268 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1269 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001270 VK_LValue,
1271 OK_ObjCProperty,
1272 MemberLoc,
1273 BaseExpr.take()));
1274 }
1275
1276 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1277 // Check the use of this method.
1278 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1279 return ExprError();
1280 Selector SetterSel =
1281 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1282 PP.getSelectorTable(), Member);
1283 ObjCMethodDecl *SMD = 0;
1284 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1285 SetterSel, Context))
1286 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001287
John McCall3c3b7f92011-10-25 17:37:35 +00001288 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1289 Context.PseudoObjectTy,
1290 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001291 MemberLoc, BaseExpr.take()));
1292 }
1293 }
1294 // Use of id.member can only be for a property reference. Do not
1295 // use the 'id' redefinition in this case.
1296 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1297 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1298 ObjCImpDecl, HasTemplateArgs);
1299
1300 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1301 << MemberName << BaseType);
1302 }
1303
1304 // 'Class', unqualified only.
1305 if (OT->isObjCClass()) {
1306 // Only works in a method declaration (??!).
1307 ObjCMethodDecl *MD = getCurMethodDecl();
1308 if (!MD) {
1309 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1310 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1311 ObjCImpDecl, HasTemplateArgs);
1312
1313 goto fail;
1314 }
1315
1316 // Also must look for a getter name which uses property syntax.
1317 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1318 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1319 ObjCMethodDecl *Getter;
1320 if ((Getter = IFace->lookupClassMethod(Sel))) {
1321 // Check the use of this method.
1322 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1323 return ExprError();
1324 } else
1325 Getter = IFace->lookupPrivateMethod(Sel, false);
1326 // If we found a getter then this may be a valid dot-reference, we
1327 // will look for the matching setter, in case it is needed.
1328 Selector SetterSel =
1329 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1330 PP.getSelectorTable(), Member);
1331 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1332 if (!Setter) {
1333 // If this reference is in an @implementation, also check for 'private'
1334 // methods.
1335 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1336 }
1337 // Look through local category implementations associated with the class.
1338 if (!Setter)
1339 Setter = IFace->getCategoryClassMethod(SetterSel);
1340
1341 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1342 return ExprError();
1343
1344 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001345 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001346 Context.PseudoObjectTy,
1347 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001348 MemberLoc, BaseExpr.take()));
1349 }
1350
1351 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1352 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1353 ObjCImpDecl, HasTemplateArgs);
1354
1355 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1356 << MemberName << BaseType);
1357 }
1358
1359 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001360 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1361 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001362 SourceLocation(), QualType(), false);
1363 }
1364
1365 // Handle 'field access' to vectors, such as 'V.xx'.
1366 if (BaseType->isExtVectorType()) {
1367 // FIXME: this expr should store IsArrow.
1368 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1369 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1370 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1371 Member, MemberLoc);
1372 if (ret.isNull())
1373 return ExprError();
1374
1375 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1376 *Member, MemberLoc));
1377 }
1378
1379 // Adjust builtin-sel to the appropriate redefinition type if that's
1380 // not just a pointer to builtin-sel again.
1381 if (IsArrow &&
1382 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001383 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1384 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1385 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001386 CK_BitCast);
1387 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1388 ObjCImpDecl, HasTemplateArgs);
1389 }
1390
1391 // Failure cases.
1392 fail:
1393
1394 // Recover from dot accesses to pointers, e.g.:
1395 // type *foo;
1396 // foo.bar
1397 // This is actually well-formed in two cases:
1398 // - 'type' is an Objective C type
1399 // - 'bar' is a pseudo-destructor name which happens to refer to
1400 // the appropriate pointer type
1401 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1402 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1403 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1404 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1405 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1406 << FixItHint::CreateReplacement(OpLoc, "->");
1407
1408 // Recurse as an -> access.
1409 IsArrow = true;
1410 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1411 ObjCImpDecl, HasTemplateArgs);
1412 }
1413 }
1414
1415 // If the user is trying to apply -> or . to a function name, it's probably
1416 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001417 if (tryToRecoverWithCall(BaseExpr,
1418 PDiag(diag::err_member_reference_needs_call),
1419 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001420 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001421 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001422 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001423 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1424 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1425 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001426 }
1427
1428 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1429 << BaseType << BaseExpr.get()->getSourceRange();
1430
1431 return ExprError();
1432}
1433
1434/// The main callback when the parser finds something like
1435/// expression . [nested-name-specifier] identifier
1436/// expression -> [nested-name-specifier] identifier
1437/// where 'identifier' encompasses a fairly broad spectrum of
1438/// possibilities, including destructor and operator references.
1439///
1440/// \param OpKind either tok::arrow or tok::period
1441/// \param HasTrailingLParen whether the next token is '(', which
1442/// is used to diagnose mis-uses of special members that can
1443/// only be called
1444/// \param ObjCImpDecl the current ObjC @implementation decl;
1445/// this is an ugly hack around the fact that ObjC @implementations
1446/// aren't properly put in the context chain
1447ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1448 SourceLocation OpLoc,
1449 tok::TokenKind OpKind,
1450 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001451 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001452 UnqualifiedId &Id,
1453 Decl *ObjCImpDecl,
1454 bool HasTrailingLParen) {
1455 if (SS.isSet() && SS.isInvalid())
1456 return ExprError();
1457
1458 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001459 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001460 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1461 Diag(Id.getSourceRange().getBegin(),
1462 diag::ext_ms_explicit_constructor_call);
1463
1464 TemplateArgumentListInfo TemplateArgsBuffer;
1465
1466 // Decompose the name into its component parts.
1467 DeclarationNameInfo NameInfo;
1468 const TemplateArgumentListInfo *TemplateArgs;
1469 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1470 NameInfo, TemplateArgs);
1471
1472 DeclarationName Name = NameInfo.getName();
1473 bool IsArrow = (OpKind == tok::arrow);
1474
1475 NamedDecl *FirstQualifierInScope
1476 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1477 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1478
1479 // This is a postfix expression, so get rid of ParenListExprs.
1480 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1481 if (Result.isInvalid()) return ExprError();
1482 Base = Result.take();
1483
1484 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1485 isDependentScopeSpecifier(SS)) {
1486 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1487 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001488 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001489 NameInfo, TemplateArgs);
1490 } else {
1491 LookupResult R(*this, NameInfo, LookupMemberName);
1492 ExprResult BaseResult = Owned(Base);
1493 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1494 SS, ObjCImpDecl, TemplateArgs != 0);
1495 if (BaseResult.isInvalid())
1496 return ExprError();
1497 Base = BaseResult.take();
1498
1499 if (Result.isInvalid()) {
1500 Owned(Base);
1501 return ExprError();
1502 }
1503
1504 if (Result.get()) {
1505 // The only way a reference to a destructor can be used is to
1506 // immediately call it, which falls into this case. If the
1507 // next token is not a '(', produce a diagnostic and build the
1508 // call now.
1509 if (!HasTrailingLParen &&
1510 Id.getKind() == UnqualifiedId::IK_DestructorName)
1511 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1512
1513 return move(Result);
1514 }
1515
1516 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001517 OpLoc, IsArrow, SS, TemplateKWLoc,
1518 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001519 }
1520
1521 return move(Result);
1522}
1523
1524static ExprResult
1525BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1526 const CXXScopeSpec &SS, FieldDecl *Field,
1527 DeclAccessPair FoundDecl,
1528 const DeclarationNameInfo &MemberNameInfo) {
1529 // x.a is an l-value if 'a' has a reference type. Otherwise:
1530 // x.a is an l-value/x-value/pr-value if the base is (and note
1531 // that *x is always an l-value), except that if the base isn't
1532 // an ordinary object then we must have an rvalue.
1533 ExprValueKind VK = VK_LValue;
1534 ExprObjectKind OK = OK_Ordinary;
1535 if (!IsArrow) {
1536 if (BaseExpr->getObjectKind() == OK_Ordinary)
1537 VK = BaseExpr->getValueKind();
1538 else
1539 VK = VK_RValue;
1540 }
1541 if (VK != VK_RValue && Field->isBitField())
1542 OK = OK_BitField;
1543
1544 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1545 QualType MemberType = Field->getType();
1546 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1547 MemberType = Ref->getPointeeType();
1548 VK = VK_LValue;
1549 } else {
1550 QualType BaseType = BaseExpr->getType();
1551 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1552
1553 Qualifiers BaseQuals = BaseType.getQualifiers();
1554
1555 // GC attributes are never picked up by members.
1556 BaseQuals.removeObjCGCAttr();
1557
1558 // CVR attributes from the base are picked up by members,
1559 // except that 'mutable' members don't pick up 'const'.
1560 if (Field->isMutable()) BaseQuals.removeConst();
1561
1562 Qualifiers MemberQuals
1563 = S.Context.getCanonicalType(MemberType).getQualifiers();
1564
1565 // TR 18037 does not allow fields to be declared with address spaces.
1566 assert(!MemberQuals.hasAddressSpace());
1567
1568 Qualifiers Combined = BaseQuals + MemberQuals;
1569 if (Combined != MemberQuals)
1570 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1571 }
1572
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001573 ExprResult Base =
1574 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1575 FoundDecl, Field);
1576 if (Base.isInvalid())
1577 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001578 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001579 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001580 Field, FoundDecl, MemberNameInfo,
1581 MemberType, VK, OK));
1582}
1583
1584/// Builds an implicit member access expression. The current context
1585/// is known to be an instance method, and the given unqualified lookup
1586/// set is known to contain only instance members, at least one of which
1587/// is from an appropriate type.
1588ExprResult
1589Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001590 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001591 LookupResult &R,
1592 const TemplateArgumentListInfo *TemplateArgs,
1593 bool IsKnownInstance) {
1594 assert(!R.empty() && !R.isAmbiguous());
1595
1596 SourceLocation loc = R.getNameLoc();
1597
1598 // We may have found a field within an anonymous union or struct
1599 // (C++ [class.union]).
1600 // FIXME: template-ids inside anonymous structs?
1601 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1602 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1603
1604 // If this is known to be an instance access, go ahead and build an
1605 // implicit 'this' expression now.
1606 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001607 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001608 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1609
1610 Expr *baseExpr = 0; // null signifies implicit access
1611 if (IsKnownInstance) {
1612 SourceLocation Loc = R.getNameLoc();
1613 if (SS.getRange().isValid())
1614 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001615 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001616 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1617 }
1618
1619 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1620 /*OpLoc*/ SourceLocation(),
1621 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001622 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001623 /*FirstQualifierInScope*/ 0,
1624 R, TemplateArgs);
1625}