blob: 7532cb448575c5e68ec1443dbf5a24b778520840 [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
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000104 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
105 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000106
107 if (R.isUnresolvableResult())
108 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
109
110 // Collect all the declaring classes of instance members we find.
111 bool hasNonInstance = false;
Eli Friedman9bc291d2012-01-18 03:53:45 +0000112 bool isField = false;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000113 llvm::SmallPtrSet<CXXRecordDecl*, 4> Classes;
114 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
115 NamedDecl *D = *I;
116
117 if (D->isCXXInstanceMember()) {
118 if (dyn_cast<FieldDecl>(D))
Eli Friedman9bc291d2012-01-18 03:53:45 +0000119 isField = true;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000120
121 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
122 Classes.insert(R->getCanonicalDecl());
123 }
124 else
125 hasNonInstance = true;
126 }
127
128 // If we didn't find any instance members, it can't be an implicit
129 // member reference.
130 if (Classes.empty())
131 return IMA_Static;
132
Richard Smithd390de92012-02-25 10:20:59 +0000133 bool IsCXX11UnevaluatedField = false;
David Blaikie4e4d0842012-03-11 07:00:24 +0000134 if (SemaRef.getLangOpts().CPlusPlus0x && isField) {
Richard Smith2c8aee42012-02-25 10:04:07 +0000135 // C++11 [expr.prim.general]p12:
136 // An id-expression that denotes a non-static data member or non-static
137 // member function of a class can only be used:
138 // (...)
139 // - if that id-expression denotes a non-static data member and it
140 // appears in an unevaluated operand.
141 const Sema::ExpressionEvaluationContextRecord& record
142 = SemaRef.ExprEvalContexts.back();
143 if (record.Context == Sema::Unevaluated)
Richard Smithd390de92012-02-25 10:20:59 +0000144 IsCXX11UnevaluatedField = true;
Richard Smith2c8aee42012-02-25 10:04:07 +0000145 }
146
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000147 // If the current context is not an instance method, it can't be
148 // an implicit member reference.
149 if (isStaticContext) {
150 if (hasNonInstance)
Richard Smith2c8aee42012-02-25 10:04:07 +0000151 return IMA_Mixed_StaticContext;
152
Richard Smithd390de92012-02-25 10:20:59 +0000153 return IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context
154 : IMA_Error_StaticContext;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000155 }
156
157 CXXRecordDecl *contextClass;
158 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
159 contextClass = MD->getParent()->getCanonicalDecl();
160 else
161 contextClass = cast<CXXRecordDecl>(DC);
162
163 // [class.mfct.non-static]p3:
164 // ...is used in the body of a non-static member function of class X,
165 // if name lookup (3.4.1) resolves the name in the id-expression to a
166 // non-static non-type member of some class C [...]
167 // ...if C is not X or a base class of X, the class member access expression
168 // is ill-formed.
169 if (R.getNamingClass() &&
DeLesley Hutchinsd08d5992012-02-25 00:11:55 +0000170 contextClass->getCanonicalDecl() !=
171 R.getNamingClass()->getCanonicalDecl() &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000172 contextClass->isProvablyNotDerivedFrom(R.getNamingClass()))
Richard Smithd390de92012-02-25 10:20:59 +0000173 return hasNonInstance ? IMA_Mixed_Unrelated :
174 IsCXX11UnevaluatedField ? IMA_Field_Uneval_Context :
175 IMA_Error_Unrelated;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000176
177 // If we can prove that the current context is unrelated to all the
178 // declaring classes, it can't be an implicit member reference (in
179 // which case it's an error if any of those members are selected).
180 if (IsProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
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 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
186}
187
188/// Diagnose a reference to a field with no object available.
Richard Smitha85cf392012-04-05 01:13:04 +0000189static void diagnoseInstanceReference(Sema &SemaRef,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000190 const CXXScopeSpec &SS,
Richard Smitha85cf392012-04-05 01:13:04 +0000191 NamedDecl *Rep,
Eli Friedmanef331b72012-01-20 01:26:23 +0000192 const DeclarationNameInfo &nameInfo) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000193 SourceLocation Loc = nameInfo.getLoc();
194 SourceRange Range(Loc);
195 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
Eli Friedman9bc291d2012-01-18 03:53:45 +0000196
Richard Smitha85cf392012-04-05 01:13:04 +0000197 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
198 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
199 CXXRecordDecl *ContextClass = Method ? Method->getParent() : 0;
200 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
201
202 bool InStaticMethod = Method && Method->isStatic();
203 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
204
205 if (IsField && InStaticMethod)
206 // "invalid use of member 'x' in static member function"
207 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
208 << Range << nameInfo.getName();
209 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
210 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
211 // Unqualified lookup in a non-static member function found a member of an
212 // enclosing class.
213 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
214 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
215 else if (IsField)
Eli Friedmanef331b72012-01-20 01:26:23 +0000216 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
Richard Smitha85cf392012-04-05 01:13:04 +0000217 << nameInfo.getName() << Range;
218 else
219 SemaRef.Diag(Loc, diag::err_member_call_without_object)
220 << Range;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000221}
222
223/// Builds an expression which might be an implicit member expression.
224ExprResult
225Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000226 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000227 LookupResult &R,
228 const TemplateArgumentListInfo *TemplateArgs) {
229 switch (ClassifyImplicitMemberAccess(*this, CurScope, R)) {
230 case IMA_Instance:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000231 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000232
233 case IMA_Mixed:
234 case IMA_Mixed_Unrelated:
235 case IMA_Unresolved:
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000236 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000237
Richard Smithd390de92012-02-25 10:20:59 +0000238 case IMA_Field_Uneval_Context:
239 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
240 << R.getLookupNameInfo().getName();
241 // Fall through.
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000242 case IMA_Static:
243 case IMA_Mixed_StaticContext:
244 case IMA_Unresolved_StaticContext:
Abramo Bagnara9d9922a2012-02-06 14:31:00 +0000245 if (TemplateArgs || TemplateKWLoc.isValid())
246 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000247 return BuildDeclarationNameExpr(SS, R, false);
248
249 case IMA_Error_StaticContext:
250 case IMA_Error_Unrelated:
Richard Smitha85cf392012-04-05 01:13:04 +0000251 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000252 R.getLookupNameInfo());
253 return ExprError();
254 }
255
256 llvm_unreachable("unexpected instance member access kind");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000257}
258
259/// Check an ext-vector component access expression.
260///
261/// VK should be set in advance to the value kind of the base
262/// expression.
263static QualType
264CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
265 SourceLocation OpLoc, const IdentifierInfo *CompName,
266 SourceLocation CompLoc) {
267 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
268 // see FIXME there.
269 //
270 // FIXME: This logic can be greatly simplified by splitting it along
271 // halving/not halving and reworking the component checking.
272 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
273
274 // The vector accessor can't exceed the number of elements.
275 const char *compStr = CompName->getNameStart();
276
277 // This flag determines whether or not the component is one of the four
278 // special names that indicate a subset of exactly half the elements are
279 // to be selected.
280 bool HalvingSwizzle = false;
281
282 // This flag determines whether or not CompName has an 's' char prefix,
283 // indicating that it is a string of hex values to be used as vector indices.
284 bool HexSwizzle = *compStr == 's' || *compStr == 'S';
285
286 bool HasRepeated = false;
287 bool HasIndex[16] = {};
288
289 int Idx;
290
291 // Check that we've found one of the special components, or that the component
292 // names must come from the same set.
293 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
294 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
295 HalvingSwizzle = true;
296 } else if (!HexSwizzle &&
297 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
298 do {
299 if (HasIndex[Idx]) HasRepeated = true;
300 HasIndex[Idx] = true;
301 compStr++;
302 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
303 } else {
304 if (HexSwizzle) compStr++;
305 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
306 if (HasIndex[Idx]) HasRepeated = true;
307 HasIndex[Idx] = true;
308 compStr++;
309 }
310 }
311
312 if (!HalvingSwizzle && *compStr) {
313 // We didn't get to the end of the string. This means the component names
314 // didn't come from the same set *or* we encountered an illegal name.
315 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000316 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000317 return QualType();
318 }
319
320 // Ensure no component accessor exceeds the width of the vector type it
321 // operates on.
322 if (!HalvingSwizzle) {
323 compStr = CompName->getNameStart();
324
325 if (HexSwizzle)
326 compStr++;
327
328 while (*compStr) {
329 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
330 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
331 << baseType << SourceRange(CompLoc);
332 return QualType();
333 }
334 }
335 }
336
337 // The component accessor looks fine - now we need to compute the actual type.
338 // The vector type is implied by the component accessor. For example,
339 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
340 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
341 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
342 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
343 : CompName->getLength();
344 if (HexSwizzle)
345 CompSize--;
346
347 if (CompSize == 1)
348 return vecType->getElementType();
349
350 if (HasRepeated) VK = VK_RValue;
351
352 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
353 // Now look up the TypeDefDecl from the vector type. Without this,
354 // diagostics look bad. We want extended vector types to appear built-in.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000355 for (Sema::ExtVectorDeclsType::iterator
356 I = S.ExtVectorDecls.begin(S.ExternalSource),
357 E = S.ExtVectorDecls.end();
358 I != E; ++I) {
359 if ((*I)->getUnderlyingType() == VT)
360 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000361 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000362
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000363 return VT; // should never get here (a typedef type should always be found).
364}
365
366static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
367 IdentifierInfo *Member,
368 const Selector &Sel,
369 ASTContext &Context) {
370 if (Member)
371 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
372 return PD;
373 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
374 return OMD;
375
376 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
377 E = PDecl->protocol_end(); I != E; ++I) {
378 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
379 Context))
380 return D;
381 }
382 return 0;
383}
384
385static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
386 IdentifierInfo *Member,
387 const Selector &Sel,
388 ASTContext &Context) {
389 // Check protocols on qualified interfaces.
390 Decl *GDecl = 0;
391 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
392 E = QIdTy->qual_end(); I != E; ++I) {
393 if (Member)
394 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
395 GDecl = PD;
396 break;
397 }
398 // Also must look for a getter or setter name which uses property syntax.
399 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
400 GDecl = OMD;
401 break;
402 }
403 }
404 if (!GDecl) {
405 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
406 E = QIdTy->qual_end(); I != E; ++I) {
407 // Search in the protocol-qualifier list of current protocol.
408 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
409 Context);
410 if (GDecl)
411 return GDecl;
412 }
413 }
414 return GDecl;
415}
416
417ExprResult
418Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
419 bool IsArrow, SourceLocation OpLoc,
420 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000421 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000422 NamedDecl *FirstQualifierInScope,
423 const DeclarationNameInfo &NameInfo,
424 const TemplateArgumentListInfo *TemplateArgs) {
425 // Even in dependent contexts, try to diagnose base expressions with
426 // obviously wrong types, e.g.:
427 //
428 // T* t;
429 // t.f;
430 //
431 // In Obj-C++, however, the above expression is valid, since it could be
432 // accessing the 'f' property if T is an Obj-C interface. The extra check
433 // allows this, while still reporting an error if T is a struct pointer.
434 if (!IsArrow) {
435 const PointerType *PT = BaseType->getAs<PointerType>();
David Blaikie4e4d0842012-03-11 07:00:24 +0000436 if (PT && (!getLangOpts().ObjC1 ||
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000437 PT->getPointeeType()->isRecordType())) {
438 assert(BaseExpr && "cannot happen with implicit member accesses");
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +0000439 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +0000440 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000441 return ExprError();
442 }
443 }
444
445 assert(BaseType->isDependentType() ||
446 NameInfo.getName().isDependentName() ||
447 isDependentScopeSpecifier(SS));
448
449 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
450 // must have pointer type, and the accessed type is the pointee.
451 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
452 IsArrow, OpLoc,
453 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000454 TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000455 FirstQualifierInScope,
456 NameInfo, TemplateArgs));
457}
458
459/// We know that the given qualified member reference points only to
460/// declarations which do not belong to the static type of the base
461/// expression. Diagnose the problem.
462static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
463 Expr *BaseExpr,
464 QualType BaseType,
465 const CXXScopeSpec &SS,
466 NamedDecl *rep,
467 const DeclarationNameInfo &nameInfo) {
468 // If this is an implicit member access, use a different set of
469 // diagnostics.
470 if (!BaseExpr)
Richard Smitha85cf392012-04-05 01:13:04 +0000471 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000472
473 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
474 << SS.getRange() << rep << BaseType;
475}
476
477// Check whether the declarations we found through a nested-name
478// specifier in a member expression are actually members of the base
479// type. The restriction here is:
480//
481// C++ [expr.ref]p2:
482// ... In these cases, the id-expression shall name a
483// member of the class or of one of its base classes.
484//
485// So it's perfectly legitimate for the nested-name specifier to name
486// an unrelated class, and for us to find an overload set including
487// decls from classes which are not superclasses, as long as the decl
488// we actually pick through overload resolution is from a superclass.
489bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
490 QualType BaseType,
491 const CXXScopeSpec &SS,
492 const LookupResult &R) {
493 const RecordType *BaseRT = BaseType->getAs<RecordType>();
494 if (!BaseRT) {
495 // We can't check this yet because the base type is still
496 // dependent.
497 assert(BaseType->isDependentType());
498 return false;
499 }
500 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
501
502 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
503 // If this is an implicit member reference and we find a
504 // non-instance member, it's not an error.
505 if (!BaseExpr && !(*I)->isCXXInstanceMember())
506 return false;
507
508 // Note that we use the DC of the decl, not the underlying decl.
509 DeclContext *DC = (*I)->getDeclContext();
510 while (DC->isTransparentContext())
511 DC = DC->getParent();
512
513 if (!DC->isRecord())
514 continue;
515
516 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
517 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
518
519 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
520 return false;
521 }
522
523 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
524 R.getRepresentativeDecl(),
525 R.getLookupNameInfo());
526 return true;
527}
528
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000529namespace {
530
531// Callback to only accept typo corrections that are either a ValueDecl or a
532// FunctionTemplateDecl.
533class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
534 public:
535 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
536 NamedDecl *ND = candidate.getCorrectionDecl();
537 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
538 }
539};
540
541}
542
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000543static bool
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000544LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000545 SourceRange BaseRange, const RecordType *RTy,
546 SourceLocation OpLoc, CXXScopeSpec &SS,
547 bool HasTemplateArgs) {
548 RecordDecl *RDecl = RTy->getDecl();
Douglas Gregorcefc3af2012-04-16 07:05:22 +0000549 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
550 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000551 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
552 << BaseRange))
553 return true;
554
555 if (HasTemplateArgs) {
556 // LookupTemplateName doesn't expect these both to exist simultaneously.
557 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
558
559 bool MOUS;
560 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
561 return false;
562 }
563
564 DeclContext *DC = RDecl;
565 if (SS.isSet()) {
566 // If the member name was a qualified-id, look into the
567 // nested-name-specifier.
568 DC = SemaRef.computeDeclContext(SS, false);
569
570 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
571 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
572 << SS.getRange() << DC;
573 return true;
574 }
575
576 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
577
578 if (!isa<TypeDecl>(DC)) {
579 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
580 << DC << SS.getRange();
581 return true;
582 }
583 }
584
585 // The record definition is complete, now look up the member.
586 SemaRef.LookupQualifiedName(R, DC);
587
588 if (!R.empty())
589 return false;
590
591 // We didn't find anything with the given name, so try to correct
592 // for typos.
593 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000594 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000595 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
596 R.getLookupKind(), NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +0000597 &SS, Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000598 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000599 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000600 std::string CorrectedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000601 Corrected.getAsString(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000602 std::string CorrectedQuotedStr(
David Blaikie4e4d0842012-03-11 07:00:24 +0000603 Corrected.getQuoted(SemaRef.getLangOpts()));
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000604 R.setLookupName(Corrected.getCorrection());
605 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000606 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000607 << Name << DC << CorrectedQuotedStr << SS.getRange()
608 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
609 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
610 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000611 }
612
613 return false;
614}
615
616ExprResult
617Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
618 SourceLocation OpLoc, bool IsArrow,
619 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000620 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000621 NamedDecl *FirstQualifierInScope,
622 const DeclarationNameInfo &NameInfo,
623 const TemplateArgumentListInfo *TemplateArgs) {
624 if (BaseType->isDependentType() ||
625 (SS.isSet() && isDependentScopeSpecifier(SS)))
626 return ActOnDependentMemberExpr(Base, BaseType,
627 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000628 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000629 NameInfo, TemplateArgs);
630
631 LookupResult R(*this, NameInfo, LookupMemberName);
632
633 // Implicit member accesses.
634 if (!Base) {
635 QualType RecordTy = BaseType;
636 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
637 if (LookupMemberExprInRecord(*this, R, SourceRange(),
638 RecordTy->getAs<RecordType>(),
639 OpLoc, SS, TemplateArgs != 0))
640 return ExprError();
641
642 // Explicit member accesses.
643 } else {
644 ExprResult BaseResult = Owned(Base);
645 ExprResult Result =
646 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
647 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
648
649 if (BaseResult.isInvalid())
650 return ExprError();
651 Base = BaseResult.take();
652
653 if (Result.isInvalid()) {
654 Owned(Base);
655 return ExprError();
656 }
657
658 if (Result.get())
659 return move(Result);
660
661 // LookupMemberExpr can modify Base, and thus change BaseType
662 BaseType = Base->getType();
663 }
664
665 return BuildMemberReferenceExpr(Base, BaseType,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000666 OpLoc, IsArrow, SS, TemplateKWLoc,
667 FirstQualifierInScope, R, TemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000668}
669
670static ExprResult
671BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
672 const CXXScopeSpec &SS, FieldDecl *Field,
673 DeclAccessPair FoundDecl,
674 const DeclarationNameInfo &MemberNameInfo);
675
676ExprResult
677Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
678 SourceLocation loc,
679 IndirectFieldDecl *indirectField,
680 Expr *baseObjectExpr,
681 SourceLocation opLoc) {
682 // First, build the expression that refers to the base object.
683
684 bool baseObjectIsPointer = false;
685 Qualifiers baseQuals;
686
687 // Case 1: the base of the indirect field is not a field.
688 VarDecl *baseVariable = indirectField->getVarDecl();
689 CXXScopeSpec EmptySS;
690 if (baseVariable) {
691 assert(baseVariable->getType()->isRecordType());
692
693 // In principle we could have a member access expression that
694 // accesses an anonymous struct/union that's a static member of
695 // the base object's class. However, under the current standard,
696 // static data members cannot be anonymous structs or unions.
697 // Supporting this is as easy as building a MemberExpr here.
698 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
699
700 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
701
702 ExprResult result
703 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
704 if (result.isInvalid()) return ExprError();
705
706 baseObjectExpr = result.take();
707 baseObjectIsPointer = false;
708 baseQuals = baseObjectExpr->getType().getQualifiers();
709
710 // Case 2: the base of the indirect field is a field and the user
711 // wrote a member expression.
712 } else if (baseObjectExpr) {
713 // The caller provided the base object expression. Determine
714 // whether its a pointer and whether it adds any qualifiers to the
715 // anonymous struct/union fields we're looking into.
716 QualType objectType = baseObjectExpr->getType();
717
718 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
719 baseObjectIsPointer = true;
720 objectType = ptr->getPointeeType();
721 } else {
722 baseObjectIsPointer = false;
723 }
724 baseQuals = objectType.getQualifiers();
725
726 // Case 3: the base of the indirect field is a field and we should
727 // build an implicit member access.
728 } else {
729 // We've found a member of an anonymous struct/union that is
730 // inside a non-anonymous struct/union, so in a well-formed
731 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000732 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000733 if (ThisTy.isNull()) {
734 Diag(loc, diag::err_invalid_member_use_in_static_method)
735 << indirectField->getDeclName();
736 return ExprError();
737 }
738
739 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000740 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000741 baseObjectExpr
742 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
743 baseObjectIsPointer = true;
744 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
745 }
746
747 // Build the implicit member references to the field of the
748 // anonymous struct/union.
749 Expr *result = baseObjectExpr;
750 IndirectFieldDecl::chain_iterator
751 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
752
753 // Build the first member access in the chain with full information.
754 if (!baseVariable) {
755 FieldDecl *field = cast<FieldDecl>(*FI);
756
757 // FIXME: use the real found-decl info!
758 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
759
760 // Make a nameInfo that properly uses the anonymous name.
761 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
762
763 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
764 EmptySS, field, foundDecl,
765 memberNameInfo).take();
766 baseObjectIsPointer = false;
767
768 // FIXME: check qualified member access
769 }
770
771 // In all cases, we should now skip the first declaration in the chain.
772 ++FI;
773
774 while (FI != FEnd) {
775 FieldDecl *field = cast<FieldDecl>(*FI++);
776
777 // FIXME: these are somewhat meaningless
778 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
779 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
780
781 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
782 (FI == FEnd? SS : EmptySS), field,
783 foundDecl, memberNameInfo).take();
784 }
785
786 return Owned(result);
787}
788
789/// \brief Build a MemberExpr AST node.
Eli Friedman5f2987c2012-02-02 03:46:19 +0000790static MemberExpr *BuildMemberExpr(Sema &SemaRef,
791 ASTContext &C, Expr *Base, bool isArrow,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000792 const CXXScopeSpec &SS,
793 SourceLocation TemplateKWLoc,
794 ValueDecl *Member,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000795 DeclAccessPair FoundDecl,
796 const DeclarationNameInfo &MemberNameInfo,
797 QualType Ty,
798 ExprValueKind VK, ExprObjectKind OK,
799 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000800 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Eli Friedman5f2987c2012-02-02 03:46:19 +0000801 MemberExpr *E =
802 MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
803 TemplateKWLoc, Member, FoundDecl, MemberNameInfo,
804 TemplateArgs, Ty, VK, OK);
805 SemaRef.MarkMemberReferenced(E);
806 return E;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000807}
808
809ExprResult
810Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
811 SourceLocation OpLoc, bool IsArrow,
812 const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000813 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000814 NamedDecl *FirstQualifierInScope,
815 LookupResult &R,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000816 const TemplateArgumentListInfo *TemplateArgs,
817 bool SuppressQualifierCheck,
818 ActOnMemberAccessExtraArgs *ExtraArgs) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000819 QualType BaseType = BaseExprType;
820 if (IsArrow) {
821 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000822 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000823 }
824 R.setBaseObjectType(BaseType);
825
826 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
827 DeclarationName MemberName = MemberNameInfo.getName();
828 SourceLocation MemberLoc = MemberNameInfo.getLoc();
829
830 if (R.isAmbiguous())
831 return ExprError();
832
833 if (R.empty()) {
834 // Rederive where we looked up.
835 DeclContext *DC = (SS.isSet()
836 ? computeDeclContext(SS, false)
837 : BaseType->getAs<RecordType>()->getDecl());
838
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000839 if (ExtraArgs) {
840 ExprResult RetryExpr;
841 if (!IsArrow && BaseExpr) {
Kaelyn Uhrain111263c2012-05-01 01:17:53 +0000842 SFINAETrap Trap(*this, true);
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +0000843 ParsedType ObjectType;
844 bool MayBePseudoDestructor = false;
845 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
846 OpLoc, tok::arrow, ObjectType,
847 MayBePseudoDestructor);
848 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
849 CXXScopeSpec TempSS(SS);
850 RetryExpr = ActOnMemberAccessExpr(
851 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
852 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl,
853 ExtraArgs->HasTrailingLParen);
854 }
855 if (Trap.hasErrorOccurred())
856 RetryExpr = ExprError();
857 }
858 if (RetryExpr.isUsable()) {
859 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
860 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
861 return RetryExpr;
862 }
863 }
864
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000865 Diag(R.getNameLoc(), diag::err_no_member)
866 << MemberName << DC
867 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
868 return ExprError();
869 }
870
871 // Diagnose lookups that find only declarations from a non-base
872 // type. This is possible for either qualified lookups (which may
873 // have been qualified with an unrelated type) or implicit member
874 // expressions (which were found with unqualified lookup and thus
875 // may have come from an enclosing scope). Note that it's okay for
876 // lookup to find declarations from a non-base type as long as those
877 // aren't the ones picked by overload resolution.
878 if ((SS.isSet() || !BaseExpr ||
879 (isa<CXXThisExpr>(BaseExpr) &&
880 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
881 !SuppressQualifierCheck &&
882 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
883 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000884
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000885 // Construct an unresolved result if we in fact got an unresolved
886 // result.
887 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
888 // Suppress any lookup-related diagnostics; we'll do these when we
889 // pick a member.
890 R.suppressDiagnostics();
891
892 UnresolvedMemberExpr *MemExpr
893 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
894 BaseExpr, BaseExprType,
895 IsArrow, OpLoc,
896 SS.getWithLocInContext(Context),
Abramo Bagnarae4b92762012-01-27 09:46:47 +0000897 TemplateKWLoc, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000898 TemplateArgs, R.begin(), R.end());
899
900 return Owned(MemExpr);
901 }
902
903 assert(R.isSingleResult());
904 DeclAccessPair FoundDecl = R.begin().getPair();
905 NamedDecl *MemberDecl = R.getFoundDecl();
906
907 // FIXME: diagnose the presence of template arguments now.
908
909 // If the decl being referenced had an error, return an error for this
910 // sub-expr without emitting another error, in order to avoid cascading
911 // error cases.
912 if (MemberDecl->isInvalidDecl())
913 return ExprError();
914
915 // Handle the implicit-member-access case.
916 if (!BaseExpr) {
917 // If this is not an instance member, convert to a non-member access.
918 if (!MemberDecl->isCXXInstanceMember())
919 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
920
921 SourceLocation Loc = R.getNameLoc();
922 if (SS.getRange().isValid())
923 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000924 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000925 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
926 }
927
928 bool ShouldCheckUse = true;
929 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
930 // Don't diagnose the use of a virtual member function unless it's
931 // explicitly qualified.
932 if (MD->isVirtual() && !SS.isSet())
933 ShouldCheckUse = false;
934 }
935
936 // Check the use of this member.
937 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
938 Owned(BaseExpr);
939 return ExprError();
940 }
941
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000942 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
943 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
944 SS, FD, FoundDecl, MemberNameInfo);
945
946 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
947 // We may have found a field within an anonymous union or struct
948 // (C++ [class.union]).
949 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
950 BaseExpr, OpLoc);
951
952 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000953 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
954 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000955 Var->getType().getNonReferenceType(),
956 VK_LValue, OK_Ordinary));
957 }
958
959 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
960 ExprValueKind valueKind;
961 QualType type;
962 if (MemberFn->isInstance()) {
963 valueKind = VK_RValue;
964 type = Context.BoundMemberTy;
965 } else {
966 valueKind = VK_LValue;
967 type = MemberFn->getType();
968 }
969
Eli Friedman5f2987c2012-02-02 03:46:19 +0000970 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
971 TemplateKWLoc, MemberFn, FoundDecl,
972 MemberNameInfo, type, valueKind,
973 OK_Ordinary));
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000974 }
975 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
976
977 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
Eli Friedman5f2987c2012-02-02 03:46:19 +0000978 return Owned(BuildMemberExpr(*this, Context, BaseExpr, IsArrow, SS,
979 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000980 Enum->getType(), VK_RValue, OK_Ordinary));
981 }
982
983 Owned(BaseExpr);
984
985 // We found something that we didn't expect. Complain.
986 if (isa<TypeDecl>(MemberDecl))
987 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
988 << MemberName << BaseType << int(IsArrow);
989 else
990 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
991 << MemberName << BaseType << int(IsArrow);
992
993 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
994 << MemberName;
995 R.suppressDiagnostics();
996 return ExprError();
997}
998
999/// Given that normal member access failed on the given expression,
1000/// and given that the expression's type involves builtin-id or
1001/// builtin-Class, decide whether substituting in the redefinition
1002/// types would be profitable. The redefinition type is whatever
1003/// this translation unit tried to typedef to id/Class; we store
1004/// it to the side and then re-use it in places like this.
1005static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1006 const ObjCObjectPointerType *opty
1007 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1008 if (!opty) return false;
1009
1010 const ObjCObjectType *ty = opty->getObjectType();
1011
1012 QualType redef;
1013 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001014 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001015 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001016 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001017 } else {
1018 return false;
1019 }
1020
1021 // Do the substitution as long as the redefinition type isn't just a
1022 // possibly-qualified pointer to builtin-id or builtin-Class again.
1023 opty = redef->getAs<ObjCObjectPointerType>();
1024 if (opty && !opty->getObjectType()->getInterface() != 0)
1025 return false;
1026
1027 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
1028 return true;
1029}
1030
John McCall6dbba4f2011-10-11 23:14:30 +00001031static bool isRecordType(QualType T) {
1032 return T->isRecordType();
1033}
1034static bool isPointerToRecordType(QualType T) {
1035 if (const PointerType *PT = T->getAs<PointerType>())
1036 return PT->getPointeeType()->isRecordType();
1037 return false;
1038}
1039
Richard Smith9138b4e2011-10-26 19:06:56 +00001040/// Perform conversions on the LHS of a member access expression.
1041ExprResult
1042Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +00001043 if (IsArrow && !Base->getType()->isFunctionType())
1044 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001045
Eli Friedman059d5782012-01-13 02:20:01 +00001046 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +00001047}
1048
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001049/// Look up the given member of the given non-type-dependent
1050/// expression. This can return in one of two ways:
1051/// * If it returns a sentinel null-but-valid result, the caller will
1052/// assume that lookup was performed and the results written into
1053/// the provided structure. It will take over from there.
1054/// * Otherwise, the returned expression will be produced in place of
1055/// an ordinary member expression.
1056///
1057/// The ObjCImpDecl bit is a gross hack that will need to be properly
1058/// fixed for ObjC++.
1059ExprResult
1060Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1061 bool &IsArrow, SourceLocation OpLoc,
1062 CXXScopeSpec &SS,
1063 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1064 assert(BaseExpr.get() && "no base expression");
1065
1066 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001067 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001068 if (BaseExpr.isInvalid())
1069 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001070
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001071 QualType BaseType = BaseExpr.get()->getType();
1072 assert(!BaseType->isDependentType());
1073
1074 DeclarationName MemberName = R.getLookupName();
1075 SourceLocation MemberLoc = R.getNameLoc();
1076
1077 // For later type-checking purposes, turn arrow accesses into dot
1078 // accesses. The only access type we support that doesn't follow
1079 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1080 // and those never use arrows, so this is unaffected.
1081 if (IsArrow) {
1082 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1083 BaseType = Ptr->getPointeeType();
1084 else if (const ObjCObjectPointerType *Ptr
1085 = BaseType->getAs<ObjCObjectPointerType>())
1086 BaseType = Ptr->getPointeeType();
1087 else if (BaseType->isRecordType()) {
1088 // Recover from arrow accesses to records, e.g.:
1089 // struct MyRecord foo;
1090 // foo->bar
1091 // This is actually well-formed in C++ if MyRecord has an
1092 // overloaded operator->, but that should have been dealt with
1093 // by now.
1094 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1095 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1096 << FixItHint::CreateReplacement(OpLoc, ".");
1097 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001098 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001099 goto fail;
1100 } else {
1101 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1102 << BaseType << BaseExpr.get()->getSourceRange();
1103 return ExprError();
1104 }
1105 }
1106
1107 // Handle field access to simple records.
1108 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1109 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1110 RTy, OpLoc, SS, HasTemplateArgs))
1111 return ExprError();
1112
1113 // Returning valid-but-null is how we indicate to the caller that
1114 // the lookup result was filled in.
1115 return Owned((Expr*) 0);
1116 }
1117
1118 // Handle ivar access to Objective-C objects.
1119 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001120 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001121 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1122 << 1 << SS.getScopeRep()
1123 << FixItHint::CreateRemoval(SS.getRange());
1124 SS.clear();
1125 }
1126
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001127 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1128
1129 // There are three cases for the base type:
1130 // - builtin id (qualified or unqualified)
1131 // - builtin Class (qualified or unqualified)
1132 // - an interface
1133 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1134 if (!IDecl) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001135 if (getLangOpts().ObjCAutoRefCount &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001136 (OTy->isObjCId() || OTy->isObjCClass()))
1137 goto fail;
1138 // There's an implicit 'isa' ivar on all objects.
1139 // But we only actually find it this way on objects of type 'id',
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001140 // apparently.ghjg
1141 if (OTy->isObjCId() && Member->isStr("isa")) {
1142 Diag(MemberLoc, diag::warn_objc_isa_use);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001143 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1144 Context.getObjCClassType()));
Fariborz Jahanian556b1d02012-01-18 19:08:56 +00001145 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001146
1147 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1148 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1149 ObjCImpDecl, HasTemplateArgs);
1150 goto fail;
1151 }
1152
Douglas Gregord07cc362012-01-02 17:18:37 +00001153 if (RequireCompleteType(OpLoc, BaseType,
1154 PDiag(diag::err_typecheck_incomplete_tag)
1155 << BaseExpr.get()->getSourceRange()))
1156 return ExprError();
1157
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001158 ObjCInterfaceDecl *ClassDeclared = 0;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001159 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1160
1161 if (!IV) {
1162 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001163 DeclFilterCCC<ObjCIvarDecl> Validator;
1164 Validator.IsObjCIvarLookup = IsArrow;
1165 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1166 LookupMemberName, NULL, NULL,
Kaelyn Uhrain16e46dd2012-01-31 23:49:25 +00001167 Validator, IDecl)) {
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001168 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001169 Diag(R.getNameLoc(),
1170 diag::err_typecheck_member_reference_ivar_suggest)
1171 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1172 << FixItHint::CreateReplacement(R.getNameLoc(),
1173 IV->getNameAsString());
1174 Diag(IV->getLocation(), diag::note_previous_decl)
1175 << IV->getDeclName();
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001176
1177 // Figure out the class that declares the ivar.
1178 assert(!ClassDeclared);
1179 Decl *D = cast<Decl>(IV->getDeclContext());
1180 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1181 D = CAT->getClassInterface();
1182 ClassDeclared = cast<ObjCInterfaceDecl>(D);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001183 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001184 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1185 Diag(MemberLoc,
1186 diag::err_property_found_suggest)
1187 << Member << BaseExpr.get()->getType()
1188 << FixItHint::CreateReplacement(OpLoc, ".");
1189 return ExprError();
1190 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001191
1192 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1193 << IDecl->getDeclName() << MemberName
1194 << BaseExpr.get()->getSourceRange();
1195 return ExprError();
1196 }
1197 }
Ted Kremenek2c085ed2012-03-17 00:53:39 +00001198
1199 assert(ClassDeclared);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001200
1201 // If the decl being referenced had an error, return an error for this
1202 // sub-expr without emitting another error, in order to avoid cascading
1203 // error cases.
1204 if (IV->isInvalidDecl())
1205 return ExprError();
1206
1207 // Check whether we can reference this field.
1208 if (DiagnoseUseOfDecl(IV, MemberLoc))
1209 return ExprError();
1210 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1211 IV->getAccessControl() != ObjCIvarDecl::Package) {
1212 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1213 if (ObjCMethodDecl *MD = getCurMethodDecl())
1214 ClassOfMethodDecl = MD->getClassInterface();
1215 else if (ObjCImpDecl && getCurFunctionDecl()) {
1216 // Case of a c-function declared inside an objc implementation.
1217 // FIXME: For a c-style function nested inside an objc implementation
1218 // class, there is no implementation context available, so we pass
1219 // down the context as argument to this routine. Ideally, this context
1220 // need be passed down in the AST node and somehow calculated from the
1221 // AST for a function decl.
1222 if (ObjCImplementationDecl *IMPD =
1223 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1224 ClassOfMethodDecl = IMPD->getClassInterface();
1225 else if (ObjCCategoryImplDecl* CatImplClass =
1226 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1227 ClassOfMethodDecl = CatImplClass->getClassInterface();
1228 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001229 if (!getLangOpts().DebuggerSupport) {
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001230 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1231 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1232 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1233 Diag(MemberLoc, diag::error_private_ivar_access)
1234 << IV->getDeclName();
1235 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1236 // @protected
1237 Diag(MemberLoc, diag::error_protected_ivar_access)
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001238 << IV->getDeclName();
Fariborz Jahanian458a7fb2012-03-07 00:58:41 +00001239 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001240 }
David Blaikie4e4d0842012-03-11 07:00:24 +00001241 if (getLangOpts().ObjCAutoRefCount) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001242 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1243 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1244 if (UO->getOpcode() == UO_Deref)
1245 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1246
1247 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1248 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1249 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1250 }
1251
1252 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1253 MemberLoc, BaseExpr.take(),
1254 IsArrow));
1255 }
1256
1257 // Objective-C property access.
1258 const ObjCObjectPointerType *OPT;
1259 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001260 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001261 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1262 << 0 << SS.getScopeRep()
1263 << FixItHint::CreateRemoval(SS.getRange());
1264 SS.clear();
1265 }
1266
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001267 // This actually uses the base as an r-value.
1268 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1269 if (BaseExpr.isInvalid())
1270 return ExprError();
1271
1272 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1273
1274 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1275
1276 const ObjCObjectType *OT = OPT->getObjectType();
1277
1278 // id, with and without qualifiers.
1279 if (OT->isObjCId()) {
1280 // Check protocols on qualified interfaces.
1281 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1282 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1283 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1284 // Check the use of this declaration
1285 if (DiagnoseUseOfDecl(PD, MemberLoc))
1286 return ExprError();
1287
John McCall3c3b7f92011-10-25 17:37:35 +00001288 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1289 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001290 VK_LValue,
1291 OK_ObjCProperty,
1292 MemberLoc,
1293 BaseExpr.take()));
1294 }
1295
1296 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1297 // Check the use of this method.
1298 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1299 return ExprError();
1300 Selector SetterSel =
1301 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1302 PP.getSelectorTable(), Member);
1303 ObjCMethodDecl *SMD = 0;
1304 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1305 SetterSel, Context))
1306 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001307
John McCall3c3b7f92011-10-25 17:37:35 +00001308 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1309 Context.PseudoObjectTy,
1310 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001311 MemberLoc, BaseExpr.take()));
1312 }
1313 }
1314 // Use of id.member can only be for a property reference. Do not
1315 // use the 'id' redefinition in this case.
1316 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1317 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1318 ObjCImpDecl, HasTemplateArgs);
1319
1320 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1321 << MemberName << BaseType);
1322 }
1323
1324 // 'Class', unqualified only.
1325 if (OT->isObjCClass()) {
1326 // Only works in a method declaration (??!).
1327 ObjCMethodDecl *MD = getCurMethodDecl();
1328 if (!MD) {
1329 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1330 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1331 ObjCImpDecl, HasTemplateArgs);
1332
1333 goto fail;
1334 }
1335
1336 // Also must look for a getter name which uses property syntax.
1337 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1338 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1339 ObjCMethodDecl *Getter;
1340 if ((Getter = IFace->lookupClassMethod(Sel))) {
1341 // Check the use of this method.
1342 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1343 return ExprError();
1344 } else
1345 Getter = IFace->lookupPrivateMethod(Sel, false);
1346 // If we found a getter then this may be a valid dot-reference, we
1347 // will look for the matching setter, in case it is needed.
1348 Selector SetterSel =
1349 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1350 PP.getSelectorTable(), Member);
1351 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1352 if (!Setter) {
1353 // If this reference is in an @implementation, also check for 'private'
1354 // methods.
1355 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1356 }
1357 // Look through local category implementations associated with the class.
1358 if (!Setter)
1359 Setter = IFace->getCategoryClassMethod(SetterSel);
1360
1361 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1362 return ExprError();
1363
1364 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001365 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001366 Context.PseudoObjectTy,
1367 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001368 MemberLoc, BaseExpr.take()));
1369 }
1370
1371 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1372 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1373 ObjCImpDecl, HasTemplateArgs);
1374
1375 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1376 << MemberName << BaseType);
1377 }
1378
1379 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001380 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1381 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001382 SourceLocation(), QualType(), false);
1383 }
1384
1385 // Handle 'field access' to vectors, such as 'V.xx'.
1386 if (BaseType->isExtVectorType()) {
1387 // FIXME: this expr should store IsArrow.
1388 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1389 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1390 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1391 Member, MemberLoc);
1392 if (ret.isNull())
1393 return ExprError();
1394
1395 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1396 *Member, MemberLoc));
1397 }
1398
1399 // Adjust builtin-sel to the appropriate redefinition type if that's
1400 // not just a pointer to builtin-sel again.
1401 if (IsArrow &&
1402 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001403 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1404 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1405 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001406 CK_BitCast);
1407 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1408 ObjCImpDecl, HasTemplateArgs);
1409 }
1410
1411 // Failure cases.
1412 fail:
1413
1414 // Recover from dot accesses to pointers, e.g.:
1415 // type *foo;
1416 // foo.bar
1417 // This is actually well-formed in two cases:
1418 // - 'type' is an Objective C type
1419 // - 'bar' is a pseudo-destructor name which happens to refer to
1420 // the appropriate pointer type
1421 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1422 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1423 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1424 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1425 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1426 << FixItHint::CreateReplacement(OpLoc, "->");
1427
1428 // Recurse as an -> access.
1429 IsArrow = true;
1430 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1431 ObjCImpDecl, HasTemplateArgs);
1432 }
1433 }
1434
1435 // If the user is trying to apply -> or . to a function name, it's probably
1436 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001437 if (tryToRecoverWithCall(BaseExpr,
1438 PDiag(diag::err_member_reference_needs_call),
1439 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001440 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001441 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001442 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001443 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1444 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1445 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001446 }
1447
Matt Beaumont-Gay7d90fe52012-04-21 01:12:48 +00001448 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
Matt Beaumont-Gay73664a42012-04-21 02:13:04 +00001449 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001450
1451 return ExprError();
1452}
1453
1454/// The main callback when the parser finds something like
1455/// expression . [nested-name-specifier] identifier
1456/// expression -> [nested-name-specifier] identifier
1457/// where 'identifier' encompasses a fairly broad spectrum of
1458/// possibilities, including destructor and operator references.
1459///
1460/// \param OpKind either tok::arrow or tok::period
1461/// \param HasTrailingLParen whether the next token is '(', which
1462/// is used to diagnose mis-uses of special members that can
1463/// only be called
1464/// \param ObjCImpDecl the current ObjC @implementation decl;
1465/// this is an ugly hack around the fact that ObjC @implementations
1466/// aren't properly put in the context chain
1467ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1468 SourceLocation OpLoc,
1469 tok::TokenKind OpKind,
1470 CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001471 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001472 UnqualifiedId &Id,
1473 Decl *ObjCImpDecl,
1474 bool HasTrailingLParen) {
1475 if (SS.isSet() && SS.isInvalid())
1476 return ExprError();
1477
1478 // Warn about the explicit constructor calls Microsoft extension.
David Blaikie4e4d0842012-03-11 07:00:24 +00001479 if (getLangOpts().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001480 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1481 Diag(Id.getSourceRange().getBegin(),
1482 diag::ext_ms_explicit_constructor_call);
1483
1484 TemplateArgumentListInfo TemplateArgsBuffer;
1485
1486 // Decompose the name into its component parts.
1487 DeclarationNameInfo NameInfo;
1488 const TemplateArgumentListInfo *TemplateArgs;
1489 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1490 NameInfo, TemplateArgs);
1491
1492 DeclarationName Name = NameInfo.getName();
1493 bool IsArrow = (OpKind == tok::arrow);
1494
1495 NamedDecl *FirstQualifierInScope
1496 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1497 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1498
1499 // This is a postfix expression, so get rid of ParenListExprs.
1500 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1501 if (Result.isInvalid()) return ExprError();
1502 Base = Result.take();
1503
1504 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1505 isDependentScopeSpecifier(SS)) {
1506 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1507 IsArrow, OpLoc,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001508 SS, TemplateKWLoc, FirstQualifierInScope,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001509 NameInfo, TemplateArgs);
1510 } else {
1511 LookupResult R(*this, NameInfo, LookupMemberName);
1512 ExprResult BaseResult = Owned(Base);
1513 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1514 SS, ObjCImpDecl, TemplateArgs != 0);
1515 if (BaseResult.isInvalid())
1516 return ExprError();
1517 Base = BaseResult.take();
1518
1519 if (Result.isInvalid()) {
1520 Owned(Base);
1521 return ExprError();
1522 }
1523
1524 if (Result.get()) {
1525 // The only way a reference to a destructor can be used is to
1526 // immediately call it, which falls into this case. If the
1527 // next token is not a '(', produce a diagnostic and build the
1528 // call now.
1529 if (!HasTrailingLParen &&
1530 Id.getKind() == UnqualifiedId::IK_DestructorName)
1531 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1532
1533 return move(Result);
1534 }
1535
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001536 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl, HasTrailingLParen};
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001537 Result = BuildMemberReferenceExpr(Base, Base->getType(),
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001538 OpLoc, IsArrow, SS, TemplateKWLoc,
Kaelyn Uhrain2b90f762012-04-25 19:49:54 +00001539 FirstQualifierInScope, R, TemplateArgs,
1540 false, &ExtraArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001541 }
1542
1543 return move(Result);
1544}
1545
1546static ExprResult
1547BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1548 const CXXScopeSpec &SS, FieldDecl *Field,
1549 DeclAccessPair FoundDecl,
1550 const DeclarationNameInfo &MemberNameInfo) {
1551 // x.a is an l-value if 'a' has a reference type. Otherwise:
1552 // x.a is an l-value/x-value/pr-value if the base is (and note
1553 // that *x is always an l-value), except that if the base isn't
1554 // an ordinary object then we must have an rvalue.
1555 ExprValueKind VK = VK_LValue;
1556 ExprObjectKind OK = OK_Ordinary;
1557 if (!IsArrow) {
1558 if (BaseExpr->getObjectKind() == OK_Ordinary)
1559 VK = BaseExpr->getValueKind();
1560 else
1561 VK = VK_RValue;
1562 }
1563 if (VK != VK_RValue && Field->isBitField())
1564 OK = OK_BitField;
1565
1566 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1567 QualType MemberType = Field->getType();
1568 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1569 MemberType = Ref->getPointeeType();
1570 VK = VK_LValue;
1571 } else {
1572 QualType BaseType = BaseExpr->getType();
1573 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1574
1575 Qualifiers BaseQuals = BaseType.getQualifiers();
1576
1577 // GC attributes are never picked up by members.
1578 BaseQuals.removeObjCGCAttr();
1579
1580 // CVR attributes from the base are picked up by members,
1581 // except that 'mutable' members don't pick up 'const'.
1582 if (Field->isMutable()) BaseQuals.removeConst();
1583
1584 Qualifiers MemberQuals
1585 = S.Context.getCanonicalType(MemberType).getQualifiers();
1586
1587 // TR 18037 does not allow fields to be declared with address spaces.
1588 assert(!MemberQuals.hasAddressSpace());
1589
1590 Qualifiers Combined = BaseQuals + MemberQuals;
1591 if (Combined != MemberQuals)
1592 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1593 }
1594
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001595 ExprResult Base =
1596 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1597 FoundDecl, Field);
1598 if (Base.isInvalid())
1599 return ExprError();
Eli Friedman5f2987c2012-02-02 03:46:19 +00001600 return S.Owned(BuildMemberExpr(S, S.Context, Base.take(), IsArrow, SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001601 /*TemplateKWLoc=*/SourceLocation(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001602 Field, FoundDecl, MemberNameInfo,
1603 MemberType, VK, OK));
1604}
1605
1606/// Builds an implicit member access expression. The current context
1607/// is known to be an instance method, and the given unqualified lookup
1608/// set is known to contain only instance members, at least one of which
1609/// is from an appropriate type.
1610ExprResult
1611Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001612 SourceLocation TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001613 LookupResult &R,
1614 const TemplateArgumentListInfo *TemplateArgs,
1615 bool IsKnownInstance) {
1616 assert(!R.empty() && !R.isAmbiguous());
1617
1618 SourceLocation loc = R.getNameLoc();
1619
1620 // We may have found a field within an anonymous union or struct
1621 // (C++ [class.union]).
1622 // FIXME: template-ids inside anonymous structs?
1623 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1624 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1625
1626 // If this is known to be an instance access, go ahead and build an
1627 // implicit 'this' expression now.
1628 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001629 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001630 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1631
1632 Expr *baseExpr = 0; // null signifies implicit access
1633 if (IsKnownInstance) {
1634 SourceLocation Loc = R.getNameLoc();
1635 if (SS.getRange().isValid())
1636 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001637 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001638 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1639 }
1640
1641 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1642 /*OpLoc*/ SourceLocation(),
1643 /*IsArrow*/ true,
Abramo Bagnarae4b92762012-01-27 09:46:47 +00001644 SS, TemplateKWLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001645 /*FirstQualifierInScope*/ 0,
1646 R, TemplateArgs);
1647}