blob: 950976820512d14244abed242c445cf621d044bd [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 {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001083 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1084 Diag(MemberLoc,
1085 diag::err_property_found_suggest)
1086 << Member << BaseExpr.get()->getType()
1087 << FixItHint::CreateReplacement(OpLoc, ".");
1088 return ExprError();
1089 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001090 Res.clear();
1091 Res.setLookupName(Member);
1092
1093 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1094 << IDecl->getDeclName() << MemberName
1095 << BaseExpr.get()->getSourceRange();
1096 return ExprError();
1097 }
1098 }
1099
1100 // If the decl being referenced had an error, return an error for this
1101 // sub-expr without emitting another error, in order to avoid cascading
1102 // error cases.
1103 if (IV->isInvalidDecl())
1104 return ExprError();
1105
1106 // Check whether we can reference this field.
1107 if (DiagnoseUseOfDecl(IV, MemberLoc))
1108 return ExprError();
1109 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1110 IV->getAccessControl() != ObjCIvarDecl::Package) {
1111 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1112 if (ObjCMethodDecl *MD = getCurMethodDecl())
1113 ClassOfMethodDecl = MD->getClassInterface();
1114 else if (ObjCImpDecl && getCurFunctionDecl()) {
1115 // Case of a c-function declared inside an objc implementation.
1116 // FIXME: For a c-style function nested inside an objc implementation
1117 // class, there is no implementation context available, so we pass
1118 // down the context as argument to this routine. Ideally, this context
1119 // need be passed down in the AST node and somehow calculated from the
1120 // AST for a function decl.
1121 if (ObjCImplementationDecl *IMPD =
1122 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1123 ClassOfMethodDecl = IMPD->getClassInterface();
1124 else if (ObjCCategoryImplDecl* CatImplClass =
1125 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1126 ClassOfMethodDecl = CatImplClass->getClassInterface();
1127 }
1128
1129 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
1130 if (ClassDeclared != IDecl ||
1131 ClassOfMethodDecl != ClassDeclared)
1132 Diag(MemberLoc, diag::error_private_ivar_access)
1133 << IV->getDeclName();
1134 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1135 // @protected
1136 Diag(MemberLoc, diag::error_protected_ivar_access)
1137 << IV->getDeclName();
1138 }
1139 if (getLangOptions().ObjCAutoRefCount) {
1140 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1141 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1142 if (UO->getOpcode() == UO_Deref)
1143 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1144
1145 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1146 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1147 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1148 }
1149
1150 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1151 MemberLoc, BaseExpr.take(),
1152 IsArrow));
1153 }
1154
1155 // Objective-C property access.
1156 const ObjCObjectPointerType *OPT;
1157 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
1158 // This actually uses the base as an r-value.
1159 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1160 if (BaseExpr.isInvalid())
1161 return ExprError();
1162
1163 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1164
1165 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1166
1167 const ObjCObjectType *OT = OPT->getObjectType();
1168
1169 // id, with and without qualifiers.
1170 if (OT->isObjCId()) {
1171 // Check protocols on qualified interfaces.
1172 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1173 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1174 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1175 // Check the use of this declaration
1176 if (DiagnoseUseOfDecl(PD, MemberLoc))
1177 return ExprError();
1178
1179 QualType T = PD->getType();
1180 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
1181 T = getMessageSendResultType(BaseType, Getter, false, false);
1182
1183 return Owned(new (Context) ObjCPropertyRefExpr(PD, T,
1184 VK_LValue,
1185 OK_ObjCProperty,
1186 MemberLoc,
1187 BaseExpr.take()));
1188 }
1189
1190 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1191 // Check the use of this method.
1192 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1193 return ExprError();
1194 Selector SetterSel =
1195 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1196 PP.getSelectorTable(), Member);
1197 ObjCMethodDecl *SMD = 0;
1198 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1199 SetterSel, Context))
1200 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
1201 QualType PType = getMessageSendResultType(BaseType, OMD, false,
1202 false);
1203
1204 ExprValueKind VK = VK_LValue;
1205 if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType())
1206 VK = VK_RValue;
1207 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
1208
1209 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD, PType,
1210 VK, OK,
1211 MemberLoc, BaseExpr.take()));
1212 }
1213 }
1214 // Use of id.member can only be for a property reference. Do not
1215 // use the 'id' redefinition in this case.
1216 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1217 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1218 ObjCImpDecl, HasTemplateArgs);
1219
1220 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1221 << MemberName << BaseType);
1222 }
1223
1224 // 'Class', unqualified only.
1225 if (OT->isObjCClass()) {
1226 // Only works in a method declaration (??!).
1227 ObjCMethodDecl *MD = getCurMethodDecl();
1228 if (!MD) {
1229 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1230 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1231 ObjCImpDecl, HasTemplateArgs);
1232
1233 goto fail;
1234 }
1235
1236 // Also must look for a getter name which uses property syntax.
1237 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1238 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1239 ObjCMethodDecl *Getter;
1240 if ((Getter = IFace->lookupClassMethod(Sel))) {
1241 // Check the use of this method.
1242 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1243 return ExprError();
1244 } else
1245 Getter = IFace->lookupPrivateMethod(Sel, false);
1246 // If we found a getter then this may be a valid dot-reference, we
1247 // will look for the matching setter, in case it is needed.
1248 Selector SetterSel =
1249 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1250 PP.getSelectorTable(), Member);
1251 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1252 if (!Setter) {
1253 // If this reference is in an @implementation, also check for 'private'
1254 // methods.
1255 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1256 }
1257 // Look through local category implementations associated with the class.
1258 if (!Setter)
1259 Setter = IFace->getCategoryClassMethod(SetterSel);
1260
1261 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1262 return ExprError();
1263
1264 if (Getter || Setter) {
1265 QualType PType;
1266
1267 ExprValueKind VK = VK_LValue;
1268 if (Getter) {
1269 PType = getMessageSendResultType(QualType(OT, 0), Getter, true,
1270 false);
1271 if (!getLangOptions().CPlusPlus && PType.isCForbiddenLValueType())
1272 VK = VK_RValue;
1273 } else {
1274 // Get the expression type from Setter's incoming parameter.
1275 PType = (*(Setter->param_end() -1))->getType();
1276 }
1277 ExprObjectKind OK = (VK == VK_RValue ? OK_Ordinary : OK_ObjCProperty);
1278
1279 // FIXME: we must check that the setter has property type.
1280 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
1281 PType, VK, OK,
1282 MemberLoc, BaseExpr.take()));
1283 }
1284
1285 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1286 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1287 ObjCImpDecl, HasTemplateArgs);
1288
1289 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1290 << MemberName << BaseType);
1291 }
1292
1293 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001294 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1295 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001296 SourceLocation(), QualType(), false);
1297 }
1298
1299 // Handle 'field access' to vectors, such as 'V.xx'.
1300 if (BaseType->isExtVectorType()) {
1301 // FIXME: this expr should store IsArrow.
1302 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1303 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1304 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1305 Member, MemberLoc);
1306 if (ret.isNull())
1307 return ExprError();
1308
1309 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1310 *Member, MemberLoc));
1311 }
1312
1313 // Adjust builtin-sel to the appropriate redefinition type if that's
1314 // not just a pointer to builtin-sel again.
1315 if (IsArrow &&
1316 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
1317 !Context.ObjCSelRedefinitionType->isObjCSelType()) {
1318 BaseExpr = ImpCastExprToType(BaseExpr.take(), Context.ObjCSelRedefinitionType,
1319 CK_BitCast);
1320 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1321 ObjCImpDecl, HasTemplateArgs);
1322 }
1323
1324 // Failure cases.
1325 fail:
1326
1327 // Recover from dot accesses to pointers, e.g.:
1328 // type *foo;
1329 // foo.bar
1330 // This is actually well-formed in two cases:
1331 // - 'type' is an Objective C type
1332 // - 'bar' is a pseudo-destructor name which happens to refer to
1333 // the appropriate pointer type
1334 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1335 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1336 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1337 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1338 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1339 << FixItHint::CreateReplacement(OpLoc, "->");
1340
1341 // Recurse as an -> access.
1342 IsArrow = true;
1343 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1344 ObjCImpDecl, HasTemplateArgs);
1345 }
1346 }
1347
1348 // If the user is trying to apply -> or . to a function name, it's probably
1349 // because they forgot parentheses to call that function.
1350 QualType ZeroArgCallTy;
1351 UnresolvedSet<4> Overloads;
1352 if (isExprCallable(*BaseExpr.get(), ZeroArgCallTy, Overloads)) {
1353 if (ZeroArgCallTy.isNull()) {
1354 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
1355 << (Overloads.size() > 1) << 0 << BaseExpr.get()->getSourceRange();
1356 UnresolvedSet<2> PlausibleOverloads;
1357 for (OverloadExpr::decls_iterator It = Overloads.begin(),
1358 DeclsEnd = Overloads.end(); It != DeclsEnd; ++It) {
1359 const FunctionDecl *OverloadDecl = cast<FunctionDecl>(*It);
1360 QualType OverloadResultTy = OverloadDecl->getResultType();
1361 if ((!IsArrow && OverloadResultTy->isRecordType()) ||
1362 (IsArrow && OverloadResultTy->isPointerType() &&
1363 OverloadResultTy->getPointeeType()->isRecordType()))
1364 PlausibleOverloads.addDecl(It.getDecl());
1365 }
1366 NoteOverloads(PlausibleOverloads, BaseExpr.get()->getExprLoc());
1367 return ExprError();
1368 }
1369 if ((!IsArrow && ZeroArgCallTy->isRecordType()) ||
1370 (IsArrow && ZeroArgCallTy->isPointerType() &&
1371 ZeroArgCallTy->getPointeeType()->isRecordType())) {
1372 // At this point, we know BaseExpr looks like it's potentially callable
1373 // with 0 arguments, and that it returns something of a reasonable type,
1374 // so we can emit a fixit and carry on pretending that BaseExpr was
1375 // actually a CallExpr.
1376 SourceLocation ParenInsertionLoc =
1377 PP.getLocForEndOfToken(BaseExpr.get()->getLocEnd());
1378 Diag(BaseExpr.get()->getExprLoc(), diag::err_member_reference_needs_call)
1379 << (Overloads.size() > 1) << 1 << BaseExpr.get()->getSourceRange()
1380 << FixItHint::CreateInsertion(ParenInsertionLoc, "()");
1381 // FIXME: Try this before emitting the fixit, and suppress diagnostics
1382 // while doing so.
1383 ExprResult NewBase =
1384 ActOnCallExpr(0, BaseExpr.take(), ParenInsertionLoc,
1385 MultiExprArg(*this, 0, 0),
1386 ParenInsertionLoc.getFileLocWithOffset(1));
1387 if (NewBase.isInvalid())
1388 return ExprError();
1389 BaseExpr = NewBase;
1390 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1391 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1392 ObjCImpDecl, HasTemplateArgs);
1393 }
1394 }
1395
1396 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1397 << BaseType << BaseExpr.get()->getSourceRange();
1398
1399 return ExprError();
1400}
1401
1402/// The main callback when the parser finds something like
1403/// expression . [nested-name-specifier] identifier
1404/// expression -> [nested-name-specifier] identifier
1405/// where 'identifier' encompasses a fairly broad spectrum of
1406/// possibilities, including destructor and operator references.
1407///
1408/// \param OpKind either tok::arrow or tok::period
1409/// \param HasTrailingLParen whether the next token is '(', which
1410/// is used to diagnose mis-uses of special members that can
1411/// only be called
1412/// \param ObjCImpDecl the current ObjC @implementation decl;
1413/// this is an ugly hack around the fact that ObjC @implementations
1414/// aren't properly put in the context chain
1415ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1416 SourceLocation OpLoc,
1417 tok::TokenKind OpKind,
1418 CXXScopeSpec &SS,
1419 UnqualifiedId &Id,
1420 Decl *ObjCImpDecl,
1421 bool HasTrailingLParen) {
1422 if (SS.isSet() && SS.isInvalid())
1423 return ExprError();
1424
1425 // Warn about the explicit constructor calls Microsoft extension.
1426 if (getLangOptions().Microsoft &&
1427 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1428 Diag(Id.getSourceRange().getBegin(),
1429 diag::ext_ms_explicit_constructor_call);
1430
1431 TemplateArgumentListInfo TemplateArgsBuffer;
1432
1433 // Decompose the name into its component parts.
1434 DeclarationNameInfo NameInfo;
1435 const TemplateArgumentListInfo *TemplateArgs;
1436 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1437 NameInfo, TemplateArgs);
1438
1439 DeclarationName Name = NameInfo.getName();
1440 bool IsArrow = (OpKind == tok::arrow);
1441
1442 NamedDecl *FirstQualifierInScope
1443 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1444 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1445
1446 // This is a postfix expression, so get rid of ParenListExprs.
1447 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1448 if (Result.isInvalid()) return ExprError();
1449 Base = Result.take();
1450
1451 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1452 isDependentScopeSpecifier(SS)) {
1453 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1454 IsArrow, OpLoc,
1455 SS, FirstQualifierInScope,
1456 NameInfo, TemplateArgs);
1457 } else {
1458 LookupResult R(*this, NameInfo, LookupMemberName);
1459 ExprResult BaseResult = Owned(Base);
1460 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1461 SS, ObjCImpDecl, TemplateArgs != 0);
1462 if (BaseResult.isInvalid())
1463 return ExprError();
1464 Base = BaseResult.take();
1465
1466 if (Result.isInvalid()) {
1467 Owned(Base);
1468 return ExprError();
1469 }
1470
1471 if (Result.get()) {
1472 // The only way a reference to a destructor can be used is to
1473 // immediately call it, which falls into this case. If the
1474 // next token is not a '(', produce a diagnostic and build the
1475 // call now.
1476 if (!HasTrailingLParen &&
1477 Id.getKind() == UnqualifiedId::IK_DestructorName)
1478 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1479
1480 return move(Result);
1481 }
1482
1483 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1484 OpLoc, IsArrow, SS, FirstQualifierInScope,
1485 R, TemplateArgs);
1486 }
1487
1488 return move(Result);
1489}
1490
1491static ExprResult
1492BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1493 const CXXScopeSpec &SS, FieldDecl *Field,
1494 DeclAccessPair FoundDecl,
1495 const DeclarationNameInfo &MemberNameInfo) {
1496 // x.a is an l-value if 'a' has a reference type. Otherwise:
1497 // x.a is an l-value/x-value/pr-value if the base is (and note
1498 // that *x is always an l-value), except that if the base isn't
1499 // an ordinary object then we must have an rvalue.
1500 ExprValueKind VK = VK_LValue;
1501 ExprObjectKind OK = OK_Ordinary;
1502 if (!IsArrow) {
1503 if (BaseExpr->getObjectKind() == OK_Ordinary)
1504 VK = BaseExpr->getValueKind();
1505 else
1506 VK = VK_RValue;
1507 }
1508 if (VK != VK_RValue && Field->isBitField())
1509 OK = OK_BitField;
1510
1511 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1512 QualType MemberType = Field->getType();
1513 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1514 MemberType = Ref->getPointeeType();
1515 VK = VK_LValue;
1516 } else {
1517 QualType BaseType = BaseExpr->getType();
1518 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1519
1520 Qualifiers BaseQuals = BaseType.getQualifiers();
1521
1522 // GC attributes are never picked up by members.
1523 BaseQuals.removeObjCGCAttr();
1524
1525 // CVR attributes from the base are picked up by members,
1526 // except that 'mutable' members don't pick up 'const'.
1527 if (Field->isMutable()) BaseQuals.removeConst();
1528
1529 Qualifiers MemberQuals
1530 = S.Context.getCanonicalType(MemberType).getQualifiers();
1531
1532 // TR 18037 does not allow fields to be declared with address spaces.
1533 assert(!MemberQuals.hasAddressSpace());
1534
1535 Qualifiers Combined = BaseQuals + MemberQuals;
1536 if (Combined != MemberQuals)
1537 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1538 }
1539
1540 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1541 ExprResult Base =
1542 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1543 FoundDecl, Field);
1544 if (Base.isInvalid())
1545 return ExprError();
1546 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
1547 Field, FoundDecl, MemberNameInfo,
1548 MemberType, VK, OK));
1549}
1550
1551/// Builds an implicit member access expression. The current context
1552/// is known to be an instance method, and the given unqualified lookup
1553/// set is known to contain only instance members, at least one of which
1554/// is from an appropriate type.
1555ExprResult
1556Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1557 LookupResult &R,
1558 const TemplateArgumentListInfo *TemplateArgs,
1559 bool IsKnownInstance) {
1560 assert(!R.empty() && !R.isAmbiguous());
1561
1562 SourceLocation loc = R.getNameLoc();
1563
1564 // We may have found a field within an anonymous union or struct
1565 // (C++ [class.union]).
1566 // FIXME: template-ids inside anonymous structs?
1567 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1568 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1569
1570 // If this is known to be an instance access, go ahead and build an
1571 // implicit 'this' expression now.
1572 // 'this' expression now.
1573 QualType ThisTy = getAndCaptureCurrentThisType();
1574 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1575
1576 Expr *baseExpr = 0; // null signifies implicit access
1577 if (IsKnownInstance) {
1578 SourceLocation Loc = R.getNameLoc();
1579 if (SS.getRange().isValid())
1580 Loc = SS.getRange().getBegin();
1581 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1582 }
1583
1584 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1585 /*OpLoc*/ SourceLocation(),
1586 /*IsArrow*/ true,
1587 SS,
1588 /*FirstQualifierInScope*/ 0,
1589 R, TemplateArgs);
1590}