1 //===--- 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/Overload.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/DeclTemplate.h"
18 #include "clang/AST/ExprCXX.h"
19 #include "clang/AST/ExprObjC.h"
20 #include "clang/Lex/Preprocessor.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/ScopeInfo.h"
24 #include "clang/Sema/SemaInternal.h"
25
26 using namespace clang;
27 using namespace sema;
28
29 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> BaseSet;
BaseIsNotInSet(const CXXRecordDecl * Base,void * BasesPtr)30 static bool BaseIsNotInSet(const CXXRecordDecl *Base, void *BasesPtr) {
31 const BaseSet &Bases = *reinterpret_cast<const BaseSet*>(BasesPtr);
32 return !Bases.count(Base->getCanonicalDecl());
33 }
34
35 /// Determines if the given class is provably not derived from all of
36 /// the prospective base classes.
isProvablyNotDerivedFrom(Sema & SemaRef,CXXRecordDecl * Record,const BaseSet & Bases)37 static bool isProvablyNotDerivedFrom(Sema &SemaRef, CXXRecordDecl *Record,
38 const BaseSet &Bases) {
39 void *BasesPtr = const_cast<void*>(reinterpret_cast<const void*>(&Bases));
40 return BaseIsNotInSet(Record, BasesPtr) &&
41 Record->forallBases(BaseIsNotInSet, BasesPtr);
42 }
43
44 enum IMAKind {
45 /// The reference is definitely not an instance member access.
46 IMA_Static,
47
48 /// The reference may be an implicit instance member access.
49 IMA_Mixed,
50
51 /// The reference may be to an instance member, but it might be invalid if
52 /// so, because the context is not an instance method.
53 IMA_Mixed_StaticContext,
54
55 /// The reference may be to an instance member, but it is invalid if
56 /// so, because the context is from an unrelated class.
57 IMA_Mixed_Unrelated,
58
59 /// The reference is definitely an implicit instance member access.
60 IMA_Instance,
61
62 /// The reference may be to an unresolved using declaration.
63 IMA_Unresolved,
64
65 /// The reference is a contextually-permitted abstract member reference.
66 IMA_Abstract,
67
68 /// The reference may be to an unresolved using declaration and the
69 /// context is not an instance method.
70 IMA_Unresolved_StaticContext,
71
72 // The reference refers to a field which is not a member of the containing
73 // class, which is allowed because we're in C++11 mode and the context is
74 // unevaluated.
75 IMA_Field_Uneval_Context,
76
77 /// All possible referrents are instance members and the current
78 /// context is not an instance method.
79 IMA_Error_StaticContext,
80
81 /// All possible referrents are instance members of an unrelated
82 /// class.
83 IMA_Error_Unrelated
84 };
85
86 /// The given lookup names class member(s) and is not being used for
87 /// an address-of-member expression. Classify the type of access
88 /// according to whether it's possible that this reference names an
89 /// instance member. This is best-effort in dependent contexts; it is okay to
90 /// conservatively answer "yes", in which case some errors will simply
91 /// not be caught until template-instantiation.
ClassifyImplicitMemberAccess(Sema & SemaRef,const LookupResult & R)92 static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
93 const LookupResult &R) {
94 assert(!R.empty() && (*R.begin())->isCXXClassMember());
95
96 DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
97
98 bool isStaticContext = SemaRef.CXXThisTypeOverride.isNull() &&
99 (!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic());
100
101 if (R.isUnresolvableResult())
102 return isStaticContext ? IMA_Unresolved_StaticContext : IMA_Unresolved;
103
104 // Collect all the declaring classes of instance members we find.
105 bool hasNonInstance = false;
106 bool isField = false;
107 BaseSet Classes;
108 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
109 NamedDecl *D = *I;
110
111 if (D->isCXXInstanceMember()) {
112 isField |= isa<FieldDecl>(D) || isa<MSPropertyDecl>(D) ||
113 isa<IndirectFieldDecl>(D);
114
115 CXXRecordDecl *R = cast<CXXRecordDecl>(D->getDeclContext());
116 Classes.insert(R->getCanonicalDecl());
117 }
118 else
119 hasNonInstance = true;
120 }
121
122 // If we didn't find any instance members, it can't be an implicit
123 // member reference.
124 if (Classes.empty())
125 return IMA_Static;
126
127 // C++11 [expr.prim.general]p12:
128 // An id-expression that denotes a non-static data member or non-static
129 // member function of a class can only be used:
130 // (...)
131 // - if that id-expression denotes a non-static data member and it
132 // appears in an unevaluated operand.
133 //
134 // This rule is specific to C++11. However, we also permit this form
135 // in unevaluated inline assembly operands, like the operand to a SIZE.
136 IMAKind AbstractInstanceResult = IMA_Static; // happens to be 'false'
137 assert(!AbstractInstanceResult);
138 switch (SemaRef.ExprEvalContexts.back().Context) {
139 case Sema::Unevaluated:
140 if (isField && SemaRef.getLangOpts().CPlusPlus11)
141 AbstractInstanceResult = IMA_Field_Uneval_Context;
142 break;
143
144 case Sema::UnevaluatedAbstract:
145 AbstractInstanceResult = IMA_Abstract;
146 break;
147
148 case Sema::ConstantEvaluated:
149 case Sema::PotentiallyEvaluated:
150 case Sema::PotentiallyEvaluatedIfUsed:
151 break;
152 }
153
154 // If the current context is not an instance method, it can't be
155 // an implicit member reference.
156 if (isStaticContext) {
157 if (hasNonInstance)
158 return IMA_Mixed_StaticContext;
159
160 return AbstractInstanceResult ? AbstractInstanceResult
161 : IMA_Error_StaticContext;
162 }
163
164 CXXRecordDecl *contextClass;
165 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC))
166 contextClass = MD->getParent()->getCanonicalDecl();
167 else
168 contextClass = cast<CXXRecordDecl>(DC);
169
170 // [class.mfct.non-static]p3:
171 // ...is used in the body of a non-static member function of class X,
172 // if name lookup (3.4.1) resolves the name in the id-expression to a
173 // non-static non-type member of some class C [...]
174 // ...if C is not X or a base class of X, the class member access expression
175 // is ill-formed.
176 if (R.getNamingClass() &&
177 contextClass->getCanonicalDecl() !=
178 R.getNamingClass()->getCanonicalDecl()) {
179 // If the naming class is not the current context, this was a qualified
180 // member name lookup, and it's sufficient to check that we have the naming
181 // class as a base class.
182 Classes.clear();
183 Classes.insert(R.getNamingClass()->getCanonicalDecl());
184 }
185
186 // If we can prove that the current context is unrelated to all the
187 // declaring classes, it can't be an implicit member reference (in
188 // which case it's an error if any of those members are selected).
189 if (isProvablyNotDerivedFrom(SemaRef, contextClass, Classes))
190 return hasNonInstance ? IMA_Mixed_Unrelated :
191 AbstractInstanceResult ? AbstractInstanceResult :
192 IMA_Error_Unrelated;
193
194 return (hasNonInstance ? IMA_Mixed : IMA_Instance);
195 }
196
197 /// Diagnose a reference to a field with no object available.
diagnoseInstanceReference(Sema & SemaRef,const CXXScopeSpec & SS,NamedDecl * Rep,const DeclarationNameInfo & nameInfo)198 static void diagnoseInstanceReference(Sema &SemaRef,
199 const CXXScopeSpec &SS,
200 NamedDecl *Rep,
201 const DeclarationNameInfo &nameInfo) {
202 SourceLocation Loc = nameInfo.getLoc();
203 SourceRange Range(Loc);
204 if (SS.isSet()) Range.setBegin(SS.getRange().getBegin());
205
206 // Look through using shadow decls and aliases.
207 Rep = Rep->getUnderlyingDecl();
208
209 DeclContext *FunctionLevelDC = SemaRef.getFunctionLevelDeclContext();
210 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(FunctionLevelDC);
211 CXXRecordDecl *ContextClass = Method ? Method->getParent() : nullptr;
212 CXXRecordDecl *RepClass = dyn_cast<CXXRecordDecl>(Rep->getDeclContext());
213
214 bool InStaticMethod = Method && Method->isStatic();
215 bool IsField = isa<FieldDecl>(Rep) || isa<IndirectFieldDecl>(Rep);
216
217 if (IsField && InStaticMethod)
218 // "invalid use of member 'x' in static member function"
219 SemaRef.Diag(Loc, diag::err_invalid_member_use_in_static_method)
220 << Range << nameInfo.getName();
221 else if (ContextClass && RepClass && SS.isEmpty() && !InStaticMethod &&
222 !RepClass->Equals(ContextClass) && RepClass->Encloses(ContextClass))
223 // Unqualified lookup in a non-static member function found a member of an
224 // enclosing class.
225 SemaRef.Diag(Loc, diag::err_nested_non_static_member_use)
226 << IsField << RepClass << nameInfo.getName() << ContextClass << Range;
227 else if (IsField)
228 SemaRef.Diag(Loc, diag::err_invalid_non_static_member_use)
229 << nameInfo.getName() << Range;
230 else
231 SemaRef.Diag(Loc, diag::err_member_call_without_object)
232 << Range;
233 }
234
235 /// Builds an expression which might be an implicit member expression.
236 ExprResult
BuildPossibleImplicitMemberExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,const TemplateArgumentListInfo * TemplateArgs)237 Sema::BuildPossibleImplicitMemberExpr(const CXXScopeSpec &SS,
238 SourceLocation TemplateKWLoc,
239 LookupResult &R,
240 const TemplateArgumentListInfo *TemplateArgs) {
241 switch (ClassifyImplicitMemberAccess(*this, R)) {
242 case IMA_Instance:
243 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true);
244
245 case IMA_Mixed:
246 case IMA_Mixed_Unrelated:
247 case IMA_Unresolved:
248 return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false);
249
250 case IMA_Field_Uneval_Context:
251 Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
252 << R.getLookupNameInfo().getName();
253 // Fall through.
254 case IMA_Static:
255 case IMA_Abstract:
256 case IMA_Mixed_StaticContext:
257 case IMA_Unresolved_StaticContext:
258 if (TemplateArgs || TemplateKWLoc.isValid())
259 return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
260 return BuildDeclarationNameExpr(SS, R, false);
261
262 case IMA_Error_StaticContext:
263 case IMA_Error_Unrelated:
264 diagnoseInstanceReference(*this, SS, R.getRepresentativeDecl(),
265 R.getLookupNameInfo());
266 return ExprError();
267 }
268
269 llvm_unreachable("unexpected instance member access kind");
270 }
271
272 /// Determine whether input char is from rgba component set.
273 static bool
IsRGBA(char c)274 IsRGBA(char c) {
275 switch (c) {
276 case 'r':
277 case 'g':
278 case 'b':
279 case 'a':
280 return true;
281 default:
282 return false;
283 }
284 }
285
286 /// Check an ext-vector component access expression.
287 ///
288 /// VK should be set in advance to the value kind of the base
289 /// expression.
290 static QualType
CheckExtVectorComponent(Sema & S,QualType baseType,ExprValueKind & VK,SourceLocation OpLoc,const IdentifierInfo * CompName,SourceLocation CompLoc)291 CheckExtVectorComponent(Sema &S, QualType baseType, ExprValueKind &VK,
292 SourceLocation OpLoc, const IdentifierInfo *CompName,
293 SourceLocation CompLoc) {
294 // FIXME: Share logic with ExtVectorElementExpr::containsDuplicateElements,
295 // see FIXME there.
296 //
297 // FIXME: This logic can be greatly simplified by splitting it along
298 // halving/not halving and reworking the component checking.
299 const ExtVectorType *vecType = baseType->getAs<ExtVectorType>();
300
301 // The vector accessor can't exceed the number of elements.
302 const char *compStr = CompName->getNameStart();
303
304 // This flag determines whether or not the component is one of the four
305 // special names that indicate a subset of exactly half the elements are
306 // to be selected.
307 bool HalvingSwizzle = false;
308
309 // This flag determines whether or not CompName has an 's' char prefix,
310 // indicating that it is a string of hex values to be used as vector indices.
311 bool HexSwizzle = (*compStr == 's' || *compStr == 'S') && compStr[1];
312
313 bool HasRepeated = false;
314 bool HasIndex[16] = {};
315
316 int Idx;
317
318 // Check that we've found one of the special components, or that the component
319 // names must come from the same set.
320 if (!strcmp(compStr, "hi") || !strcmp(compStr, "lo") ||
321 !strcmp(compStr, "even") || !strcmp(compStr, "odd")) {
322 HalvingSwizzle = true;
323 } else if (!HexSwizzle &&
324 (Idx = vecType->getPointAccessorIdx(*compStr)) != -1) {
325 bool HasRGBA = IsRGBA(*compStr);
326 do {
327 if (HasRGBA != IsRGBA(*compStr))
328 break;
329 if (HasIndex[Idx]) HasRepeated = true;
330 HasIndex[Idx] = true;
331 compStr++;
332 } while (*compStr && (Idx = vecType->getPointAccessorIdx(*compStr)) != -1);
333 } else {
334 if (HexSwizzle) compStr++;
335 while ((Idx = vecType->getNumericAccessorIdx(*compStr)) != -1) {
336 if (HasIndex[Idx]) HasRepeated = true;
337 HasIndex[Idx] = true;
338 compStr++;
339 }
340 }
341
342 if (!HalvingSwizzle && *compStr) {
343 // We didn't get to the end of the string. This means the component names
344 // didn't come from the same set *or* we encountered an illegal name.
345 S.Diag(OpLoc, diag::err_ext_vector_component_name_illegal)
346 << StringRef(compStr, 1) << SourceRange(CompLoc);
347 return QualType();
348 }
349
350 // Ensure no component accessor exceeds the width of the vector type it
351 // operates on.
352 if (!HalvingSwizzle) {
353 compStr = CompName->getNameStart();
354
355 if (HexSwizzle)
356 compStr++;
357
358 while (*compStr) {
359 if (!vecType->isAccessorWithinNumElements(*compStr++)) {
360 S.Diag(OpLoc, diag::err_ext_vector_component_exceeds_length)
361 << baseType << SourceRange(CompLoc);
362 return QualType();
363 }
364 }
365 }
366
367 // The component accessor looks fine - now we need to compute the actual type.
368 // The vector type is implied by the component accessor. For example,
369 // vec4.b is a float, vec4.xy is a vec2, vec4.rgb is a vec3, etc.
370 // vec4.s0 is a float, vec4.s23 is a vec3, etc.
371 // vec4.hi, vec4.lo, vec4.e, and vec4.o all return vec2.
372 unsigned CompSize = HalvingSwizzle ? (vecType->getNumElements() + 1) / 2
373 : CompName->getLength();
374 if (HexSwizzle)
375 CompSize--;
376
377 if (CompSize == 1)
378 return vecType->getElementType();
379
380 if (HasRepeated) VK = VK_RValue;
381
382 QualType VT = S.Context.getExtVectorType(vecType->getElementType(), CompSize);
383 // Now look up the TypeDefDecl from the vector type. Without this,
384 // diagostics look bad. We want extended vector types to appear built-in.
385 for (Sema::ExtVectorDeclsType::iterator
386 I = S.ExtVectorDecls.begin(S.getExternalSource()),
387 E = S.ExtVectorDecls.end();
388 I != E; ++I) {
389 if ((*I)->getUnderlyingType() == VT)
390 return S.Context.getTypedefType(*I);
391 }
392
393 return VT; // should never get here (a typedef type should always be found).
394 }
395
FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl * PDecl,IdentifierInfo * Member,const Selector & Sel,ASTContext & Context)396 static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
397 IdentifierInfo *Member,
398 const Selector &Sel,
399 ASTContext &Context) {
400 if (Member)
401 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
402 return PD;
403 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
404 return OMD;
405
406 for (const auto *I : PDecl->protocols()) {
407 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel,
408 Context))
409 return D;
410 }
411 return nullptr;
412 }
413
FindGetterSetterNameDecl(const ObjCObjectPointerType * QIdTy,IdentifierInfo * Member,const Selector & Sel,ASTContext & Context)414 static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
415 IdentifierInfo *Member,
416 const Selector &Sel,
417 ASTContext &Context) {
418 // Check protocols on qualified interfaces.
419 Decl *GDecl = nullptr;
420 for (const auto *I : QIdTy->quals()) {
421 if (Member)
422 if (ObjCPropertyDecl *PD = I->FindPropertyDeclaration(Member)) {
423 GDecl = PD;
424 break;
425 }
426 // Also must look for a getter or setter name which uses property syntax.
427 if (ObjCMethodDecl *OMD = I->getInstanceMethod(Sel)) {
428 GDecl = OMD;
429 break;
430 }
431 }
432 if (!GDecl) {
433 for (const auto *I : QIdTy->quals()) {
434 // Search in the protocol-qualifier list of current protocol.
435 GDecl = FindGetterSetterNameDeclFromProtocolList(I, Member, Sel, Context);
436 if (GDecl)
437 return GDecl;
438 }
439 }
440 return GDecl;
441 }
442
443 ExprResult
ActOnDependentMemberExpr(Expr * BaseExpr,QualType BaseType,bool IsArrow,SourceLocation OpLoc,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,NamedDecl * FirstQualifierInScope,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs)444 Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
445 bool IsArrow, SourceLocation OpLoc,
446 const CXXScopeSpec &SS,
447 SourceLocation TemplateKWLoc,
448 NamedDecl *FirstQualifierInScope,
449 const DeclarationNameInfo &NameInfo,
450 const TemplateArgumentListInfo *TemplateArgs) {
451 // Even in dependent contexts, try to diagnose base expressions with
452 // obviously wrong types, e.g.:
453 //
454 // T* t;
455 // t.f;
456 //
457 // In Obj-C++, however, the above expression is valid, since it could be
458 // accessing the 'f' property if T is an Obj-C interface. The extra check
459 // allows this, while still reporting an error if T is a struct pointer.
460 if (!IsArrow) {
461 const PointerType *PT = BaseType->getAs<PointerType>();
462 if (PT && (!getLangOpts().ObjC1 ||
463 PT->getPointeeType()->isRecordType())) {
464 assert(BaseExpr && "cannot happen with implicit member accesses");
465 Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
466 << BaseType << BaseExpr->getSourceRange() << NameInfo.getSourceRange();
467 return ExprError();
468 }
469 }
470
471 assert(BaseType->isDependentType() ||
472 NameInfo.getName().isDependentName() ||
473 isDependentScopeSpecifier(SS));
474
475 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
476 // must have pointer type, and the accessed type is the pointee.
477 return CXXDependentScopeMemberExpr::Create(
478 Context, BaseExpr, BaseType, IsArrow, OpLoc,
479 SS.getWithLocInContext(Context), TemplateKWLoc, FirstQualifierInScope,
480 NameInfo, TemplateArgs);
481 }
482
483 /// We know that the given qualified member reference points only to
484 /// declarations which do not belong to the static type of the base
485 /// expression. Diagnose the problem.
DiagnoseQualifiedMemberReference(Sema & SemaRef,Expr * BaseExpr,QualType BaseType,const CXXScopeSpec & SS,NamedDecl * rep,const DeclarationNameInfo & nameInfo)486 static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
487 Expr *BaseExpr,
488 QualType BaseType,
489 const CXXScopeSpec &SS,
490 NamedDecl *rep,
491 const DeclarationNameInfo &nameInfo) {
492 // If this is an implicit member access, use a different set of
493 // diagnostics.
494 if (!BaseExpr)
495 return diagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
496
497 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
498 << SS.getRange() << rep << BaseType;
499 }
500
501 // Check whether the declarations we found through a nested-name
502 // specifier in a member expression are actually members of the base
503 // type. The restriction here is:
504 //
505 // C++ [expr.ref]p2:
506 // ... In these cases, the id-expression shall name a
507 // member of the class or of one of its base classes.
508 //
509 // So it's perfectly legitimate for the nested-name specifier to name
510 // an unrelated class, and for us to find an overload set including
511 // decls from classes which are not superclasses, as long as the decl
512 // we actually pick through overload resolution is from a superclass.
CheckQualifiedMemberReference(Expr * BaseExpr,QualType BaseType,const CXXScopeSpec & SS,const LookupResult & R)513 bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
514 QualType BaseType,
515 const CXXScopeSpec &SS,
516 const LookupResult &R) {
517 CXXRecordDecl *BaseRecord =
518 cast_or_null<CXXRecordDecl>(computeDeclContext(BaseType));
519 if (!BaseRecord) {
520 // We can't check this yet because the base type is still
521 // dependent.
522 assert(BaseType->isDependentType());
523 return false;
524 }
525
526 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
527 // If this is an implicit member reference and we find a
528 // non-instance member, it's not an error.
529 if (!BaseExpr && !(*I)->isCXXInstanceMember())
530 return false;
531
532 // Note that we use the DC of the decl, not the underlying decl.
533 DeclContext *DC = (*I)->getDeclContext();
534 while (DC->isTransparentContext())
535 DC = DC->getParent();
536
537 if (!DC->isRecord())
538 continue;
539
540 CXXRecordDecl *MemberRecord = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
541 if (BaseRecord->getCanonicalDecl() == MemberRecord ||
542 !BaseRecord->isProvablyNotDerivedFrom(MemberRecord))
543 return false;
544 }
545
546 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
547 R.getRepresentativeDecl(),
548 R.getLookupNameInfo());
549 return true;
550 }
551
552 namespace {
553
554 // Callback to only accept typo corrections that are either a ValueDecl or a
555 // FunctionTemplateDecl and are declared in the current record or, for a C++
556 // classes, one of its base classes.
557 class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
558 public:
RecordMemberExprValidatorCCC(const RecordType * RTy)559 explicit RecordMemberExprValidatorCCC(const RecordType *RTy)
560 : Record(RTy->getDecl()) {
561 // Don't add bare keywords to the consumer since they will always fail
562 // validation by virtue of not being associated with any decls.
563 WantTypeSpecifiers = false;
564 WantExpressionKeywords = false;
565 WantCXXNamedCasts = false;
566 WantFunctionLikeCasts = false;
567 WantRemainingKeywords = false;
568 }
569
ValidateCandidate(const TypoCorrection & candidate)570 bool ValidateCandidate(const TypoCorrection &candidate) override {
571 NamedDecl *ND = candidate.getCorrectionDecl();
572 // Don't accept candidates that cannot be member functions, constants,
573 // variables, or templates.
574 if (!ND || !(isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND)))
575 return false;
576
577 // Accept candidates that occur in the current record.
578 if (Record->containsDecl(ND))
579 return true;
580
581 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Record)) {
582 // Accept candidates that occur in any of the current class' base classes.
583 for (const auto &BS : RD->bases()) {
584 if (const RecordType *BSTy =
585 dyn_cast_or_null<RecordType>(BS.getType().getTypePtrOrNull())) {
586 if (BSTy->getDecl()->containsDecl(ND))
587 return true;
588 }
589 }
590 }
591
592 return false;
593 }
594
595 private:
596 const RecordDecl *const Record;
597 };
598
599 }
600
LookupMemberExprInRecord(Sema & SemaRef,LookupResult & R,Expr * BaseExpr,const RecordType * RTy,SourceLocation OpLoc,bool IsArrow,CXXScopeSpec & SS,bool HasTemplateArgs,TypoExpr * & TE)601 static bool LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
602 Expr *BaseExpr,
603 const RecordType *RTy,
604 SourceLocation OpLoc, bool IsArrow,
605 CXXScopeSpec &SS, bool HasTemplateArgs,
606 TypoExpr *&TE) {
607 SourceRange BaseRange = BaseExpr ? BaseExpr->getSourceRange() : SourceRange();
608 RecordDecl *RDecl = RTy->getDecl();
609 if (!SemaRef.isThisOutsideMemberFunctionBody(QualType(RTy, 0)) &&
610 SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
611 diag::err_typecheck_incomplete_tag,
612 BaseRange))
613 return true;
614
615 if (HasTemplateArgs) {
616 // LookupTemplateName doesn't expect these both to exist simultaneously.
617 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
618
619 bool MOUS;
620 SemaRef.LookupTemplateName(R, nullptr, SS, ObjectType, false, MOUS);
621 return false;
622 }
623
624 DeclContext *DC = RDecl;
625 if (SS.isSet()) {
626 // If the member name was a qualified-id, look into the
627 // nested-name-specifier.
628 DC = SemaRef.computeDeclContext(SS, false);
629
630 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
631 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
632 << SS.getRange() << DC;
633 return true;
634 }
635
636 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
637
638 if (!isa<TypeDecl>(DC)) {
639 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
640 << DC << SS.getRange();
641 return true;
642 }
643 }
644
645 // The record definition is complete, now look up the member.
646 SemaRef.LookupQualifiedName(R, DC, SS);
647
648 if (!R.empty())
649 return false;
650
651 DeclarationName Typo = R.getLookupName();
652 SourceLocation TypoLoc = R.getNameLoc();
653 TE = SemaRef.CorrectTypoDelayed(
654 R.getLookupNameInfo(), R.getLookupKind(), nullptr, &SS,
655 llvm::make_unique<RecordMemberExprValidatorCCC>(RTy),
656 [=, &SemaRef](const TypoCorrection &TC) {
657 if (TC) {
658 assert(!TC.isKeyword() &&
659 "Got a keyword as a correction for a member!");
660 bool DroppedSpecifier =
661 TC.WillReplaceSpecifier() &&
662 Typo.getAsString() == TC.getAsString(SemaRef.getLangOpts());
663 SemaRef.diagnoseTypo(TC, SemaRef.PDiag(diag::err_no_member_suggest)
664 << Typo << DC << DroppedSpecifier
665 << SS.getRange());
666 } else {
667 SemaRef.Diag(TypoLoc, diag::err_no_member) << Typo << DC << BaseRange;
668 }
669 },
670 [=](Sema &SemaRef, TypoExpr *TE, TypoCorrection TC) mutable {
671 R.clear(); // Ensure there's no decls lingering in the shared state.
672 R.suppressDiagnostics();
673 R.setLookupName(TC.getCorrection());
674 for (NamedDecl *ND : TC)
675 R.addDecl(ND);
676 R.resolveKind();
677 return SemaRef.BuildMemberReferenceExpr(
678 BaseExpr, BaseExpr->getType(), OpLoc, IsArrow, SS, SourceLocation(),
679 nullptr, R, nullptr);
680 },
681 Sema::CTK_ErrorRecovery, DC);
682
683 return false;
684 }
685
686 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
687 ExprResult &BaseExpr, bool &IsArrow,
688 SourceLocation OpLoc, CXXScopeSpec &SS,
689 Decl *ObjCImpDecl, bool HasTemplateArgs);
690
691 ExprResult
BuildMemberReferenceExpr(Expr * Base,QualType BaseType,SourceLocation OpLoc,bool IsArrow,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,NamedDecl * FirstQualifierInScope,const DeclarationNameInfo & NameInfo,const TemplateArgumentListInfo * TemplateArgs,ActOnMemberAccessExtraArgs * ExtraArgs)692 Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
693 SourceLocation OpLoc, bool IsArrow,
694 CXXScopeSpec &SS,
695 SourceLocation TemplateKWLoc,
696 NamedDecl *FirstQualifierInScope,
697 const DeclarationNameInfo &NameInfo,
698 const TemplateArgumentListInfo *TemplateArgs,
699 ActOnMemberAccessExtraArgs *ExtraArgs) {
700 if (BaseType->isDependentType() ||
701 (SS.isSet() && isDependentScopeSpecifier(SS)))
702 return ActOnDependentMemberExpr(Base, BaseType,
703 IsArrow, OpLoc,
704 SS, TemplateKWLoc, FirstQualifierInScope,
705 NameInfo, TemplateArgs);
706
707 LookupResult R(*this, NameInfo, LookupMemberName);
708
709 // Implicit member accesses.
710 if (!Base) {
711 TypoExpr *TE = nullptr;
712 QualType RecordTy = BaseType;
713 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
714 if (LookupMemberExprInRecord(*this, R, nullptr,
715 RecordTy->getAs<RecordType>(), OpLoc, IsArrow,
716 SS, TemplateArgs != nullptr, TE))
717 return ExprError();
718 if (TE)
719 return TE;
720
721 // Explicit member accesses.
722 } else {
723 ExprResult BaseResult = Base;
724 ExprResult Result = LookupMemberExpr(
725 *this, R, BaseResult, IsArrow, OpLoc, SS,
726 ExtraArgs ? ExtraArgs->ObjCImpDecl : nullptr,
727 TemplateArgs != nullptr);
728
729 if (BaseResult.isInvalid())
730 return ExprError();
731 Base = BaseResult.get();
732
733 if (Result.isInvalid())
734 return ExprError();
735
736 if (Result.get())
737 return Result;
738
739 // LookupMemberExpr can modify Base, and thus change BaseType
740 BaseType = Base->getType();
741 }
742
743 return BuildMemberReferenceExpr(Base, BaseType,
744 OpLoc, IsArrow, SS, TemplateKWLoc,
745 FirstQualifierInScope, R, TemplateArgs,
746 false, ExtraArgs);
747 }
748
749 static ExprResult
750 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
751 SourceLocation OpLoc, const CXXScopeSpec &SS,
752 FieldDecl *Field, DeclAccessPair FoundDecl,
753 const DeclarationNameInfo &MemberNameInfo);
754
755 ExprResult
BuildAnonymousStructUnionMemberReference(const CXXScopeSpec & SS,SourceLocation loc,IndirectFieldDecl * indirectField,DeclAccessPair foundDecl,Expr * baseObjectExpr,SourceLocation opLoc)756 Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
757 SourceLocation loc,
758 IndirectFieldDecl *indirectField,
759 DeclAccessPair foundDecl,
760 Expr *baseObjectExpr,
761 SourceLocation opLoc) {
762 // First, build the expression that refers to the base object.
763
764 bool baseObjectIsPointer = false;
765 Qualifiers baseQuals;
766
767 // Case 1: the base of the indirect field is not a field.
768 VarDecl *baseVariable = indirectField->getVarDecl();
769 CXXScopeSpec EmptySS;
770 if (baseVariable) {
771 assert(baseVariable->getType()->isRecordType());
772
773 // In principle we could have a member access expression that
774 // accesses an anonymous struct/union that's a static member of
775 // the base object's class. However, under the current standard,
776 // static data members cannot be anonymous structs or unions.
777 // Supporting this is as easy as building a MemberExpr here.
778 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
779
780 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
781
782 ExprResult result
783 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
784 if (result.isInvalid()) return ExprError();
785
786 baseObjectExpr = result.get();
787 baseObjectIsPointer = false;
788 baseQuals = baseObjectExpr->getType().getQualifiers();
789
790 // Case 2: the base of the indirect field is a field and the user
791 // wrote a member expression.
792 } else if (baseObjectExpr) {
793 // The caller provided the base object expression. Determine
794 // whether its a pointer and whether it adds any qualifiers to the
795 // anonymous struct/union fields we're looking into.
796 QualType objectType = baseObjectExpr->getType();
797
798 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
799 baseObjectIsPointer = true;
800 objectType = ptr->getPointeeType();
801 } else {
802 baseObjectIsPointer = false;
803 }
804 baseQuals = objectType.getQualifiers();
805
806 // Case 3: the base of the indirect field is a field and we should
807 // build an implicit member access.
808 } else {
809 // We've found a member of an anonymous struct/union that is
810 // inside a non-anonymous struct/union, so in a well-formed
811 // program our base object expression is "this".
812 QualType ThisTy = getCurrentThisType();
813 if (ThisTy.isNull()) {
814 Diag(loc, diag::err_invalid_member_use_in_static_method)
815 << indirectField->getDeclName();
816 return ExprError();
817 }
818
819 // Our base object expression is "this".
820 CheckCXXThisCapture(loc);
821 baseObjectExpr
822 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
823 baseObjectIsPointer = true;
824 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
825 }
826
827 // Build the implicit member references to the field of the
828 // anonymous struct/union.
829 Expr *result = baseObjectExpr;
830 IndirectFieldDecl::chain_iterator
831 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
832
833 // Build the first member access in the chain with full information.
834 if (!baseVariable) {
835 FieldDecl *field = cast<FieldDecl>(*FI);
836
837 // Make a nameInfo that properly uses the anonymous name.
838 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
839
840 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
841 SourceLocation(), EmptySS, field,
842 foundDecl, memberNameInfo).get();
843 if (!result)
844 return ExprError();
845
846 // FIXME: check qualified member access
847 }
848
849 // In all cases, we should now skip the first declaration in the chain.
850 ++FI;
851
852 while (FI != FEnd) {
853 FieldDecl *field = cast<FieldDecl>(*FI++);
854
855 // FIXME: these are somewhat meaningless
856 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
857 DeclAccessPair fakeFoundDecl =
858 DeclAccessPair::make(field, field->getAccess());
859
860 result =
861 BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
862 SourceLocation(), (FI == FEnd ? SS : EmptySS),
863 field, fakeFoundDecl, memberNameInfo).get();
864 }
865
866 return result;
867 }
868
869 static ExprResult
BuildMSPropertyRefExpr(Sema & S,Expr * BaseExpr,bool IsArrow,const CXXScopeSpec & SS,MSPropertyDecl * PD,const DeclarationNameInfo & NameInfo)870 BuildMSPropertyRefExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
871 const CXXScopeSpec &SS,
872 MSPropertyDecl *PD,
873 const DeclarationNameInfo &NameInfo) {
874 // Property names are always simple identifiers and therefore never
875 // require any interesting additional storage.
876 return new (S.Context) MSPropertyRefExpr(BaseExpr, PD, IsArrow,
877 S.Context.PseudoObjectTy, VK_LValue,
878 SS.getWithLocInContext(S.Context),
879 NameInfo.getLoc());
880 }
881
882 /// \brief Build a MemberExpr AST node.
BuildMemberExpr(Sema & SemaRef,ASTContext & C,Expr * Base,bool isArrow,SourceLocation OpLoc,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,ValueDecl * Member,DeclAccessPair FoundDecl,const DeclarationNameInfo & MemberNameInfo,QualType Ty,ExprValueKind VK,ExprObjectKind OK,const TemplateArgumentListInfo * TemplateArgs=nullptr)883 static MemberExpr *BuildMemberExpr(
884 Sema &SemaRef, ASTContext &C, Expr *Base, bool isArrow,
885 SourceLocation OpLoc, const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
886 ValueDecl *Member, DeclAccessPair FoundDecl,
887 const DeclarationNameInfo &MemberNameInfo, QualType Ty, ExprValueKind VK,
888 ExprObjectKind OK, const TemplateArgumentListInfo *TemplateArgs = nullptr) {
889 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
890 MemberExpr *E = MemberExpr::Create(
891 C, Base, isArrow, OpLoc, SS.getWithLocInContext(C), TemplateKWLoc, Member,
892 FoundDecl, MemberNameInfo, TemplateArgs, Ty, VK, OK);
893 SemaRef.MarkMemberReferenced(E);
894 return E;
895 }
896
897 ExprResult
BuildMemberReferenceExpr(Expr * BaseExpr,QualType BaseExprType,SourceLocation OpLoc,bool IsArrow,const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,NamedDecl * FirstQualifierInScope,LookupResult & R,const TemplateArgumentListInfo * TemplateArgs,bool SuppressQualifierCheck,ActOnMemberAccessExtraArgs * ExtraArgs)898 Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
899 SourceLocation OpLoc, bool IsArrow,
900 const CXXScopeSpec &SS,
901 SourceLocation TemplateKWLoc,
902 NamedDecl *FirstQualifierInScope,
903 LookupResult &R,
904 const TemplateArgumentListInfo *TemplateArgs,
905 bool SuppressQualifierCheck,
906 ActOnMemberAccessExtraArgs *ExtraArgs) {
907 QualType BaseType = BaseExprType;
908 if (IsArrow) {
909 assert(BaseType->isPointerType());
910 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
911 }
912 R.setBaseObjectType(BaseType);
913
914 LambdaScopeInfo *const CurLSI = getCurLambda();
915 // If this is an implicit member reference and the overloaded
916 // name refers to both static and non-static member functions
917 // (i.e. BaseExpr is null) and if we are currently processing a lambda,
918 // check if we should/can capture 'this'...
919 // Keep this example in mind:
920 // struct X {
921 // void f(int) { }
922 // static void f(double) { }
923 //
924 // int g() {
925 // auto L = [=](auto a) {
926 // return [](int i) {
927 // return [=](auto b) {
928 // f(b);
929 // //f(decltype(a){});
930 // };
931 // };
932 // };
933 // auto M = L(0.0);
934 // auto N = M(3);
935 // N(5.32); // OK, must not error.
936 // return 0;
937 // }
938 // };
939 //
940 if (!BaseExpr && CurLSI) {
941 SourceLocation Loc = R.getNameLoc();
942 if (SS.getRange().isValid())
943 Loc = SS.getRange().getBegin();
944 DeclContext *EnclosingFunctionCtx = CurContext->getParent()->getParent();
945 // If the enclosing function is not dependent, then this lambda is
946 // capture ready, so if we can capture this, do so.
947 if (!EnclosingFunctionCtx->isDependentContext()) {
948 // If the current lambda and all enclosing lambdas can capture 'this' -
949 // then go ahead and capture 'this' (since our unresolved overload set
950 // contains both static and non-static member functions).
951 if (!CheckCXXThisCapture(Loc, /*Explcit*/false, /*Diagnose*/false))
952 CheckCXXThisCapture(Loc);
953 } else if (CurContext->isDependentContext()) {
954 // ... since this is an implicit member reference, that might potentially
955 // involve a 'this' capture, mark 'this' for potential capture in
956 // enclosing lambdas.
957 if (CurLSI->ImpCaptureStyle != CurLSI->ImpCap_None)
958 CurLSI->addPotentialThisCapture(Loc);
959 }
960 }
961 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
962 DeclarationName MemberName = MemberNameInfo.getName();
963 SourceLocation MemberLoc = MemberNameInfo.getLoc();
964
965 if (R.isAmbiguous())
966 return ExprError();
967
968 if (R.empty()) {
969 // Rederive where we looked up.
970 DeclContext *DC = (SS.isSet()
971 ? computeDeclContext(SS, false)
972 : BaseType->getAs<RecordType>()->getDecl());
973
974 if (ExtraArgs) {
975 ExprResult RetryExpr;
976 if (!IsArrow && BaseExpr) {
977 SFINAETrap Trap(*this, true);
978 ParsedType ObjectType;
979 bool MayBePseudoDestructor = false;
980 RetryExpr = ActOnStartCXXMemberReference(getCurScope(), BaseExpr,
981 OpLoc, tok::arrow, ObjectType,
982 MayBePseudoDestructor);
983 if (RetryExpr.isUsable() && !Trap.hasErrorOccurred()) {
984 CXXScopeSpec TempSS(SS);
985 RetryExpr = ActOnMemberAccessExpr(
986 ExtraArgs->S, RetryExpr.get(), OpLoc, tok::arrow, TempSS,
987 TemplateKWLoc, ExtraArgs->Id, ExtraArgs->ObjCImpDecl);
988 }
989 if (Trap.hasErrorOccurred())
990 RetryExpr = ExprError();
991 }
992 if (RetryExpr.isUsable()) {
993 Diag(OpLoc, diag::err_no_member_overloaded_arrow)
994 << MemberName << DC << FixItHint::CreateReplacement(OpLoc, "->");
995 return RetryExpr;
996 }
997 }
998
999 Diag(R.getNameLoc(), diag::err_no_member)
1000 << MemberName << DC
1001 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
1002 return ExprError();
1003 }
1004
1005 // Diagnose lookups that find only declarations from a non-base
1006 // type. This is possible for either qualified lookups (which may
1007 // have been qualified with an unrelated type) or implicit member
1008 // expressions (which were found with unqualified lookup and thus
1009 // may have come from an enclosing scope). Note that it's okay for
1010 // lookup to find declarations from a non-base type as long as those
1011 // aren't the ones picked by overload resolution.
1012 if ((SS.isSet() || !BaseExpr ||
1013 (isa<CXXThisExpr>(BaseExpr) &&
1014 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
1015 !SuppressQualifierCheck &&
1016 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
1017 return ExprError();
1018
1019 // Construct an unresolved result if we in fact got an unresolved
1020 // result.
1021 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
1022 // Suppress any lookup-related diagnostics; we'll do these when we
1023 // pick a member.
1024 R.suppressDiagnostics();
1025
1026 UnresolvedMemberExpr *MemExpr
1027 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
1028 BaseExpr, BaseExprType,
1029 IsArrow, OpLoc,
1030 SS.getWithLocInContext(Context),
1031 TemplateKWLoc, MemberNameInfo,
1032 TemplateArgs, R.begin(), R.end());
1033
1034 return MemExpr;
1035 }
1036
1037 assert(R.isSingleResult());
1038 DeclAccessPair FoundDecl = R.begin().getPair();
1039 NamedDecl *MemberDecl = R.getFoundDecl();
1040
1041 // FIXME: diagnose the presence of template arguments now.
1042
1043 // If the decl being referenced had an error, return an error for this
1044 // sub-expr without emitting another error, in order to avoid cascading
1045 // error cases.
1046 if (MemberDecl->isInvalidDecl())
1047 return ExprError();
1048
1049 // Handle the implicit-member-access case.
1050 if (!BaseExpr) {
1051 // If this is not an instance member, convert to a non-member access.
1052 if (!MemberDecl->isCXXInstanceMember())
1053 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
1054
1055 SourceLocation Loc = R.getNameLoc();
1056 if (SS.getRange().isValid())
1057 Loc = SS.getRange().getBegin();
1058 CheckCXXThisCapture(Loc);
1059 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
1060 }
1061
1062 bool ShouldCheckUse = true;
1063 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1064 // Don't diagnose the use of a virtual member function unless it's
1065 // explicitly qualified.
1066 if (MD->isVirtual() && !SS.isSet())
1067 ShouldCheckUse = false;
1068 }
1069
1070 // Check the use of this member.
1071 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc))
1072 return ExprError();
1073
1074 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
1075 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow, OpLoc, SS, FD,
1076 FoundDecl, MemberNameInfo);
1077
1078 if (MSPropertyDecl *PD = dyn_cast<MSPropertyDecl>(MemberDecl))
1079 return BuildMSPropertyRefExpr(*this, BaseExpr, IsArrow, SS, PD,
1080 MemberNameInfo);
1081
1082 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
1083 // We may have found a field within an anonymous union or struct
1084 // (C++ [class.union]).
1085 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
1086 FoundDecl, BaseExpr,
1087 OpLoc);
1088
1089 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
1090 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1091 TemplateKWLoc, Var, FoundDecl, MemberNameInfo,
1092 Var->getType().getNonReferenceType(), VK_LValue,
1093 OK_Ordinary);
1094 }
1095
1096 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
1097 ExprValueKind valueKind;
1098 QualType type;
1099 if (MemberFn->isInstance()) {
1100 valueKind = VK_RValue;
1101 type = Context.BoundMemberTy;
1102 } else {
1103 valueKind = VK_LValue;
1104 type = MemberFn->getType();
1105 }
1106
1107 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1108 TemplateKWLoc, MemberFn, FoundDecl, MemberNameInfo,
1109 type, valueKind, OK_Ordinary);
1110 }
1111 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
1112
1113 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
1114 return BuildMemberExpr(*this, Context, BaseExpr, IsArrow, OpLoc, SS,
1115 TemplateKWLoc, Enum, FoundDecl, MemberNameInfo,
1116 Enum->getType(), VK_RValue, OK_Ordinary);
1117 }
1118
1119 // We found something that we didn't expect. Complain.
1120 if (isa<TypeDecl>(MemberDecl))
1121 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
1122 << MemberName << BaseType << int(IsArrow);
1123 else
1124 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
1125 << MemberName << BaseType << int(IsArrow);
1126
1127 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
1128 << MemberName;
1129 R.suppressDiagnostics();
1130 return ExprError();
1131 }
1132
1133 /// Given that normal member access failed on the given expression,
1134 /// and given that the expression's type involves builtin-id or
1135 /// builtin-Class, decide whether substituting in the redefinition
1136 /// types would be profitable. The redefinition type is whatever
1137 /// this translation unit tried to typedef to id/Class; we store
1138 /// it to the side and then re-use it in places like this.
ShouldTryAgainWithRedefinitionType(Sema & S,ExprResult & base)1139 static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
1140 const ObjCObjectPointerType *opty
1141 = base.get()->getType()->getAs<ObjCObjectPointerType>();
1142 if (!opty) return false;
1143
1144 const ObjCObjectType *ty = opty->getObjectType();
1145
1146 QualType redef;
1147 if (ty->isObjCId()) {
1148 redef = S.Context.getObjCIdRedefinitionType();
1149 } else if (ty->isObjCClass()) {
1150 redef = S.Context.getObjCClassRedefinitionType();
1151 } else {
1152 return false;
1153 }
1154
1155 // Do the substitution as long as the redefinition type isn't just a
1156 // possibly-qualified pointer to builtin-id or builtin-Class again.
1157 opty = redef->getAs<ObjCObjectPointerType>();
1158 if (opty && !opty->getObjectType()->getInterface())
1159 return false;
1160
1161 base = S.ImpCastExprToType(base.get(), redef, CK_BitCast);
1162 return true;
1163 }
1164
isRecordType(QualType T)1165 static bool isRecordType(QualType T) {
1166 return T->isRecordType();
1167 }
isPointerToRecordType(QualType T)1168 static bool isPointerToRecordType(QualType T) {
1169 if (const PointerType *PT = T->getAs<PointerType>())
1170 return PT->getPointeeType()->isRecordType();
1171 return false;
1172 }
1173
1174 /// Perform conversions on the LHS of a member access expression.
1175 ExprResult
PerformMemberExprBaseConversion(Expr * Base,bool IsArrow)1176 Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
1177 if (IsArrow && !Base->getType()->isFunctionType())
1178 return DefaultFunctionArrayLvalueConversion(Base);
1179
1180 return CheckPlaceholderExpr(Base);
1181 }
1182
1183 /// Look up the given member of the given non-type-dependent
1184 /// expression. This can return in one of two ways:
1185 /// * If it returns a sentinel null-but-valid result, the caller will
1186 /// assume that lookup was performed and the results written into
1187 /// the provided structure. It will take over from there.
1188 /// * Otherwise, the returned expression will be produced in place of
1189 /// an ordinary member expression.
1190 ///
1191 /// The ObjCImpDecl bit is a gross hack that will need to be properly
1192 /// fixed for ObjC++.
LookupMemberExpr(Sema & S,LookupResult & R,ExprResult & BaseExpr,bool & IsArrow,SourceLocation OpLoc,CXXScopeSpec & SS,Decl * ObjCImpDecl,bool HasTemplateArgs)1193 static ExprResult LookupMemberExpr(Sema &S, LookupResult &R,
1194 ExprResult &BaseExpr, bool &IsArrow,
1195 SourceLocation OpLoc, CXXScopeSpec &SS,
1196 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1197 assert(BaseExpr.get() && "no base expression");
1198
1199 // Perform default conversions.
1200 BaseExpr = S.PerformMemberExprBaseConversion(BaseExpr.get(), IsArrow);
1201 if (BaseExpr.isInvalid())
1202 return ExprError();
1203
1204 QualType BaseType = BaseExpr.get()->getType();
1205 assert(!BaseType->isDependentType());
1206
1207 DeclarationName MemberName = R.getLookupName();
1208 SourceLocation MemberLoc = R.getNameLoc();
1209
1210 // For later type-checking purposes, turn arrow accesses into dot
1211 // accesses. The only access type we support that doesn't follow
1212 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1213 // and those never use arrows, so this is unaffected.
1214 if (IsArrow) {
1215 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1216 BaseType = Ptr->getPointeeType();
1217 else if (const ObjCObjectPointerType *Ptr
1218 = BaseType->getAs<ObjCObjectPointerType>())
1219 BaseType = Ptr->getPointeeType();
1220 else if (BaseType->isRecordType()) {
1221 // Recover from arrow accesses to records, e.g.:
1222 // struct MyRecord foo;
1223 // foo->bar
1224 // This is actually well-formed in C++ if MyRecord has an
1225 // overloaded operator->, but that should have been dealt with
1226 // by now--or a diagnostic message already issued if a problem
1227 // was encountered while looking for the overloaded operator->.
1228 if (!S.getLangOpts().CPlusPlus) {
1229 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1230 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1231 << FixItHint::CreateReplacement(OpLoc, ".");
1232 }
1233 IsArrow = false;
1234 } else if (BaseType->isFunctionType()) {
1235 goto fail;
1236 } else {
1237 S.Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1238 << BaseType << BaseExpr.get()->getSourceRange();
1239 return ExprError();
1240 }
1241 }
1242
1243 // Handle field access to simple records.
1244 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1245 TypoExpr *TE = nullptr;
1246 if (LookupMemberExprInRecord(S, R, BaseExpr.get(), RTy,
1247 OpLoc, IsArrow, SS, HasTemplateArgs, TE))
1248 return ExprError();
1249
1250 // Returning valid-but-null is how we indicate to the caller that
1251 // the lookup result was filled in. If typo correction was attempted and
1252 // failed, the lookup result will have been cleared--that combined with the
1253 // valid-but-null ExprResult will trigger the appropriate diagnostics.
1254 return ExprResult(TE);
1255 }
1256
1257 // Handle ivar access to Objective-C objects.
1258 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
1259 if (!SS.isEmpty() && !SS.isInvalid()) {
1260 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1261 << 1 << SS.getScopeRep()
1262 << FixItHint::CreateRemoval(SS.getRange());
1263 SS.clear();
1264 }
1265
1266 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1267
1268 // There are three cases for the base type:
1269 // - builtin id (qualified or unqualified)
1270 // - builtin Class (qualified or unqualified)
1271 // - an interface
1272 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1273 if (!IDecl) {
1274 if (S.getLangOpts().ObjCAutoRefCount &&
1275 (OTy->isObjCId() || OTy->isObjCClass()))
1276 goto fail;
1277 // There's an implicit 'isa' ivar on all objects.
1278 // But we only actually find it this way on objects of type 'id',
1279 // apparently.
1280 if (OTy->isObjCId() && Member->isStr("isa"))
1281 return new (S.Context) ObjCIsaExpr(BaseExpr.get(), IsArrow, MemberLoc,
1282 OpLoc, S.Context.getObjCClassType());
1283 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1284 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1285 ObjCImpDecl, HasTemplateArgs);
1286 goto fail;
1287 }
1288
1289 if (S.RequireCompleteType(OpLoc, BaseType,
1290 diag::err_typecheck_incomplete_tag,
1291 BaseExpr.get()))
1292 return ExprError();
1293
1294 ObjCInterfaceDecl *ClassDeclared = nullptr;
1295 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1296
1297 if (!IV) {
1298 // Attempt to correct for typos in ivar names.
1299 auto Validator = llvm::make_unique<DeclFilterCCC<ObjCIvarDecl>>();
1300 Validator->IsObjCIvarLookup = IsArrow;
1301 if (TypoCorrection Corrected = S.CorrectTypo(
1302 R.getLookupNameInfo(), Sema::LookupMemberName, nullptr, nullptr,
1303 std::move(Validator), Sema::CTK_ErrorRecovery, IDecl)) {
1304 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
1305 S.diagnoseTypo(
1306 Corrected,
1307 S.PDiag(diag::err_typecheck_member_reference_ivar_suggest)
1308 << IDecl->getDeclName() << MemberName);
1309
1310 // Figure out the class that declares the ivar.
1311 assert(!ClassDeclared);
1312 Decl *D = cast<Decl>(IV->getDeclContext());
1313 if (ObjCCategoryDecl *CAT = dyn_cast<ObjCCategoryDecl>(D))
1314 D = CAT->getClassInterface();
1315 ClassDeclared = cast<ObjCInterfaceDecl>(D);
1316 } else {
1317 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1318 S.Diag(MemberLoc, diag::err_property_found_suggest)
1319 << Member << BaseExpr.get()->getType()
1320 << FixItHint::CreateReplacement(OpLoc, ".");
1321 return ExprError();
1322 }
1323
1324 S.Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1325 << IDecl->getDeclName() << MemberName
1326 << BaseExpr.get()->getSourceRange();
1327 return ExprError();
1328 }
1329 }
1330
1331 assert(ClassDeclared);
1332
1333 // If the decl being referenced had an error, return an error for this
1334 // sub-expr without emitting another error, in order to avoid cascading
1335 // error cases.
1336 if (IV->isInvalidDecl())
1337 return ExprError();
1338
1339 // Check whether we can reference this field.
1340 if (S.DiagnoseUseOfDecl(IV, MemberLoc))
1341 return ExprError();
1342 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1343 IV->getAccessControl() != ObjCIvarDecl::Package) {
1344 ObjCInterfaceDecl *ClassOfMethodDecl = nullptr;
1345 if (ObjCMethodDecl *MD = S.getCurMethodDecl())
1346 ClassOfMethodDecl = MD->getClassInterface();
1347 else if (ObjCImpDecl && S.getCurFunctionDecl()) {
1348 // Case of a c-function declared inside an objc implementation.
1349 // FIXME: For a c-style function nested inside an objc implementation
1350 // class, there is no implementation context available, so we pass
1351 // down the context as argument to this routine. Ideally, this context
1352 // need be passed down in the AST node and somehow calculated from the
1353 // AST for a function decl.
1354 if (ObjCImplementationDecl *IMPD =
1355 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1356 ClassOfMethodDecl = IMPD->getClassInterface();
1357 else if (ObjCCategoryImplDecl* CatImplClass =
1358 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1359 ClassOfMethodDecl = CatImplClass->getClassInterface();
1360 }
1361 if (!S.getLangOpts().DebuggerSupport) {
1362 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1363 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1364 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
1365 S.Diag(MemberLoc, diag::error_private_ivar_access)
1366 << IV->getDeclName();
1367 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1368 // @protected
1369 S.Diag(MemberLoc, diag::error_protected_ivar_access)
1370 << IV->getDeclName();
1371 }
1372 }
1373 bool warn = true;
1374 if (S.getLangOpts().ObjCAutoRefCount) {
1375 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1376 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1377 if (UO->getOpcode() == UO_Deref)
1378 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1379
1380 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1381 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1382 S.Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1383 warn = false;
1384 }
1385 }
1386 if (warn) {
1387 if (ObjCMethodDecl *MD = S.getCurMethodDecl()) {
1388 ObjCMethodFamily MF = MD->getMethodFamily();
1389 warn = (MF != OMF_init && MF != OMF_dealloc &&
1390 MF != OMF_finalize &&
1391 !S.IvarBacksCurrentMethodAccessor(IDecl, MD, IV));
1392 }
1393 if (warn)
1394 S.Diag(MemberLoc, diag::warn_direct_ivar_access) << IV->getDeclName();
1395 }
1396
1397 ObjCIvarRefExpr *Result = new (S.Context) ObjCIvarRefExpr(
1398 IV, IV->getType(), MemberLoc, OpLoc, BaseExpr.get(), IsArrow);
1399
1400 if (S.getLangOpts().ObjCAutoRefCount) {
1401 if (IV->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
1402 if (!S.Diags.isIgnored(diag::warn_arc_repeated_use_of_weak, MemberLoc))
1403 S.recordUseOfEvaluatedWeak(Result);
1404 }
1405 }
1406
1407 return Result;
1408 }
1409
1410 // Objective-C property access.
1411 const ObjCObjectPointerType *OPT;
1412 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1413 if (!SS.isEmpty() && !SS.isInvalid()) {
1414 S.Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1415 << 0 << SS.getScopeRep() << FixItHint::CreateRemoval(SS.getRange());
1416 SS.clear();
1417 }
1418
1419 // This actually uses the base as an r-value.
1420 BaseExpr = S.DefaultLvalueConversion(BaseExpr.get());
1421 if (BaseExpr.isInvalid())
1422 return ExprError();
1423
1424 assert(S.Context.hasSameUnqualifiedType(BaseType,
1425 BaseExpr.get()->getType()));
1426
1427 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1428
1429 const ObjCObjectType *OT = OPT->getObjectType();
1430
1431 // id, with and without qualifiers.
1432 if (OT->isObjCId()) {
1433 // Check protocols on qualified interfaces.
1434 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1435 if (Decl *PMDecl =
1436 FindGetterSetterNameDecl(OPT, Member, Sel, S.Context)) {
1437 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1438 // Check the use of this declaration
1439 if (S.DiagnoseUseOfDecl(PD, MemberLoc))
1440 return ExprError();
1441
1442 return new (S.Context)
1443 ObjCPropertyRefExpr(PD, S.Context.PseudoObjectTy, VK_LValue,
1444 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1445 }
1446
1447 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1448 // Check the use of this method.
1449 if (S.DiagnoseUseOfDecl(OMD, MemberLoc))
1450 return ExprError();
1451 Selector SetterSel =
1452 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1453 S.PP.getSelectorTable(),
1454 Member);
1455 ObjCMethodDecl *SMD = nullptr;
1456 if (Decl *SDecl = FindGetterSetterNameDecl(OPT,
1457 /*Property id*/ nullptr,
1458 SetterSel, S.Context))
1459 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1460
1461 return new (S.Context)
1462 ObjCPropertyRefExpr(OMD, SMD, S.Context.PseudoObjectTy, VK_LValue,
1463 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1464 }
1465 }
1466 // Use of id.member can only be for a property reference. Do not
1467 // use the 'id' redefinition in this case.
1468 if (IsArrow && ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1469 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1470 ObjCImpDecl, HasTemplateArgs);
1471
1472 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1473 << MemberName << BaseType);
1474 }
1475
1476 // 'Class', unqualified only.
1477 if (OT->isObjCClass()) {
1478 // Only works in a method declaration (??!).
1479 ObjCMethodDecl *MD = S.getCurMethodDecl();
1480 if (!MD) {
1481 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1482 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1483 ObjCImpDecl, HasTemplateArgs);
1484
1485 goto fail;
1486 }
1487
1488 // Also must look for a getter name which uses property syntax.
1489 Selector Sel = S.PP.getSelectorTable().getNullarySelector(Member);
1490 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1491 ObjCMethodDecl *Getter;
1492 if ((Getter = IFace->lookupClassMethod(Sel))) {
1493 // Check the use of this method.
1494 if (S.DiagnoseUseOfDecl(Getter, MemberLoc))
1495 return ExprError();
1496 } else
1497 Getter = IFace->lookupPrivateMethod(Sel, false);
1498 // If we found a getter then this may be a valid dot-reference, we
1499 // will look for the matching setter, in case it is needed.
1500 Selector SetterSel =
1501 SelectorTable::constructSetterSelector(S.PP.getIdentifierTable(),
1502 S.PP.getSelectorTable(),
1503 Member);
1504 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1505 if (!Setter) {
1506 // If this reference is in an @implementation, also check for 'private'
1507 // methods.
1508 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1509 }
1510
1511 if (Setter && S.DiagnoseUseOfDecl(Setter, MemberLoc))
1512 return ExprError();
1513
1514 if (Getter || Setter) {
1515 return new (S.Context) ObjCPropertyRefExpr(
1516 Getter, Setter, S.Context.PseudoObjectTy, VK_LValue,
1517 OK_ObjCProperty, MemberLoc, BaseExpr.get());
1518 }
1519
1520 if (ShouldTryAgainWithRedefinitionType(S, BaseExpr))
1521 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1522 ObjCImpDecl, HasTemplateArgs);
1523
1524 return ExprError(S.Diag(MemberLoc, diag::err_property_not_found)
1525 << MemberName << BaseType);
1526 }
1527
1528 // Normal property access.
1529 return S.HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc, MemberName,
1530 MemberLoc, SourceLocation(), QualType(),
1531 false);
1532 }
1533
1534 // Handle 'field access' to vectors, such as 'V.xx'.
1535 if (BaseType->isExtVectorType()) {
1536 // FIXME: this expr should store IsArrow.
1537 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1538 ExprValueKind VK;
1539 if (IsArrow)
1540 VK = VK_LValue;
1541 else {
1542 if (PseudoObjectExpr *POE = dyn_cast<PseudoObjectExpr>(BaseExpr.get()))
1543 VK = POE->getSyntacticForm()->getValueKind();
1544 else
1545 VK = BaseExpr.get()->getValueKind();
1546 }
1547 QualType ret = CheckExtVectorComponent(S, BaseType, VK, OpLoc,
1548 Member, MemberLoc);
1549 if (ret.isNull())
1550 return ExprError();
1551
1552 return new (S.Context)
1553 ExtVectorElementExpr(ret, VK, BaseExpr.get(), *Member, MemberLoc);
1554 }
1555
1556 // Adjust builtin-sel to the appropriate redefinition type if that's
1557 // not just a pointer to builtin-sel again.
1558 if (IsArrow && BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1559 !S.Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1560 BaseExpr = S.ImpCastExprToType(
1561 BaseExpr.get(), S.Context.getObjCSelRedefinitionType(), CK_BitCast);
1562 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1563 ObjCImpDecl, HasTemplateArgs);
1564 }
1565
1566 // Failure cases.
1567 fail:
1568
1569 // Recover from dot accesses to pointers, e.g.:
1570 // type *foo;
1571 // foo.bar
1572 // This is actually well-formed in two cases:
1573 // - 'type' is an Objective C type
1574 // - 'bar' is a pseudo-destructor name which happens to refer to
1575 // the appropriate pointer type
1576 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1577 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1578 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1579 S.Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1580 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1581 << FixItHint::CreateReplacement(OpLoc, "->");
1582
1583 // Recurse as an -> access.
1584 IsArrow = true;
1585 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1586 ObjCImpDecl, HasTemplateArgs);
1587 }
1588 }
1589
1590 // If the user is trying to apply -> or . to a function name, it's probably
1591 // because they forgot parentheses to call that function.
1592 if (S.tryToRecoverWithCall(
1593 BaseExpr, S.PDiag(diag::err_member_reference_needs_call),
1594 /*complain*/ false,
1595 IsArrow ? &isPointerToRecordType : &isRecordType)) {
1596 if (BaseExpr.isInvalid())
1597 return ExprError();
1598 BaseExpr = S.DefaultFunctionArrayConversion(BaseExpr.get());
1599 return LookupMemberExpr(S, R, BaseExpr, IsArrow, OpLoc, SS,
1600 ObjCImpDecl, HasTemplateArgs);
1601 }
1602
1603 S.Diag(OpLoc, diag::err_typecheck_member_reference_struct_union)
1604 << BaseType << BaseExpr.get()->getSourceRange() << MemberLoc;
1605
1606 return ExprError();
1607 }
1608
1609 /// The main callback when the parser finds something like
1610 /// expression . [nested-name-specifier] identifier
1611 /// expression -> [nested-name-specifier] identifier
1612 /// where 'identifier' encompasses a fairly broad spectrum of
1613 /// possibilities, including destructor and operator references.
1614 ///
1615 /// \param OpKind either tok::arrow or tok::period
1616 /// \param ObjCImpDecl the current Objective-C \@implementation
1617 /// decl; this is an ugly hack around the fact that Objective-C
1618 /// \@implementations aren't properly put in the context chain
ActOnMemberAccessExpr(Scope * S,Expr * Base,SourceLocation OpLoc,tok::TokenKind OpKind,CXXScopeSpec & SS,SourceLocation TemplateKWLoc,UnqualifiedId & Id,Decl * ObjCImpDecl)1619 ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1620 SourceLocation OpLoc,
1621 tok::TokenKind OpKind,
1622 CXXScopeSpec &SS,
1623 SourceLocation TemplateKWLoc,
1624 UnqualifiedId &Id,
1625 Decl *ObjCImpDecl) {
1626 if (SS.isSet() && SS.isInvalid())
1627 return ExprError();
1628
1629 // Warn about the explicit constructor calls Microsoft extension.
1630 if (getLangOpts().MicrosoftExt &&
1631 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1632 Diag(Id.getSourceRange().getBegin(),
1633 diag::ext_ms_explicit_constructor_call);
1634
1635 TemplateArgumentListInfo TemplateArgsBuffer;
1636
1637 // Decompose the name into its component parts.
1638 DeclarationNameInfo NameInfo;
1639 const TemplateArgumentListInfo *TemplateArgs;
1640 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1641 NameInfo, TemplateArgs);
1642
1643 DeclarationName Name = NameInfo.getName();
1644 bool IsArrow = (OpKind == tok::arrow);
1645
1646 NamedDecl *FirstQualifierInScope
1647 = (!SS.isSet() ? nullptr : FindFirstQualifierInScope(S, SS.getScopeRep()));
1648
1649 // This is a postfix expression, so get rid of ParenListExprs.
1650 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1651 if (Result.isInvalid()) return ExprError();
1652 Base = Result.get();
1653
1654 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1655 isDependentScopeSpecifier(SS)) {
1656 return ActOnDependentMemberExpr(Base, Base->getType(), IsArrow, OpLoc, SS,
1657 TemplateKWLoc, FirstQualifierInScope,
1658 NameInfo, TemplateArgs);
1659 }
1660
1661 ActOnMemberAccessExtraArgs ExtraArgs = {S, Id, ObjCImpDecl};
1662 return BuildMemberReferenceExpr(Base, Base->getType(), OpLoc, IsArrow, SS,
1663 TemplateKWLoc, FirstQualifierInScope,
1664 NameInfo, TemplateArgs, &ExtraArgs);
1665 }
1666
1667 static ExprResult
BuildFieldReferenceExpr(Sema & S,Expr * BaseExpr,bool IsArrow,SourceLocation OpLoc,const CXXScopeSpec & SS,FieldDecl * Field,DeclAccessPair FoundDecl,const DeclarationNameInfo & MemberNameInfo)1668 BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1669 SourceLocation OpLoc, const CXXScopeSpec &SS,
1670 FieldDecl *Field, DeclAccessPair FoundDecl,
1671 const DeclarationNameInfo &MemberNameInfo) {
1672 // x.a is an l-value if 'a' has a reference type. Otherwise:
1673 // x.a is an l-value/x-value/pr-value if the base is (and note
1674 // that *x is always an l-value), except that if the base isn't
1675 // an ordinary object then we must have an rvalue.
1676 ExprValueKind VK = VK_LValue;
1677 ExprObjectKind OK = OK_Ordinary;
1678 if (!IsArrow) {
1679 if (BaseExpr->getObjectKind() == OK_Ordinary)
1680 VK = BaseExpr->getValueKind();
1681 else
1682 VK = VK_RValue;
1683 }
1684 if (VK != VK_RValue && Field->isBitField())
1685 OK = OK_BitField;
1686
1687 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1688 QualType MemberType = Field->getType();
1689 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1690 MemberType = Ref->getPointeeType();
1691 VK = VK_LValue;
1692 } else {
1693 QualType BaseType = BaseExpr->getType();
1694 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1695
1696 Qualifiers BaseQuals = BaseType.getQualifiers();
1697
1698 // GC attributes are never picked up by members.
1699 BaseQuals.removeObjCGCAttr();
1700
1701 // CVR attributes from the base are picked up by members,
1702 // except that 'mutable' members don't pick up 'const'.
1703 if (Field->isMutable()) BaseQuals.removeConst();
1704
1705 Qualifiers MemberQuals
1706 = S.Context.getCanonicalType(MemberType).getQualifiers();
1707
1708 assert(!MemberQuals.hasAddressSpace());
1709
1710
1711 Qualifiers Combined = BaseQuals + MemberQuals;
1712 if (Combined != MemberQuals)
1713 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1714 }
1715
1716 S.UnusedPrivateFields.remove(Field);
1717
1718 ExprResult Base =
1719 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1720 FoundDecl, Field);
1721 if (Base.isInvalid())
1722 return ExprError();
1723 return BuildMemberExpr(S, S.Context, Base.get(), IsArrow, OpLoc, SS,
1724 /*TemplateKWLoc=*/SourceLocation(), Field, FoundDecl,
1725 MemberNameInfo, MemberType, VK, OK);
1726 }
1727
1728 /// Builds an implicit member access expression. The current context
1729 /// is known to be an instance method, and the given unqualified lookup
1730 /// set is known to contain only instance members, at least one of which
1731 /// is from an appropriate type.
1732 ExprResult
BuildImplicitMemberExpr(const CXXScopeSpec & SS,SourceLocation TemplateKWLoc,LookupResult & R,const TemplateArgumentListInfo * TemplateArgs,bool IsKnownInstance)1733 Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1734 SourceLocation TemplateKWLoc,
1735 LookupResult &R,
1736 const TemplateArgumentListInfo *TemplateArgs,
1737 bool IsKnownInstance) {
1738 assert(!R.empty() && !R.isAmbiguous());
1739
1740 SourceLocation loc = R.getNameLoc();
1741
1742 // If this is known to be an instance access, go ahead and build an
1743 // implicit 'this' expression now.
1744 // 'this' expression now.
1745 QualType ThisTy = getCurrentThisType();
1746 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1747
1748 Expr *baseExpr = nullptr; // null signifies implicit access
1749 if (IsKnownInstance) {
1750 SourceLocation Loc = R.getNameLoc();
1751 if (SS.getRange().isValid())
1752 Loc = SS.getRange().getBegin();
1753 CheckCXXThisCapture(Loc);
1754 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1755 }
1756
1757 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1758 /*OpLoc*/ SourceLocation(),
1759 /*IsArrow*/ true,
1760 SS, TemplateKWLoc,
1761 /*FirstQualifierInScope*/ nullptr,
1762 R, TemplateArgs);
1763 }
1764