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