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