blob: e05360b87ed72253c23302ce20f8e8d370770929 [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) {
Richard Smithf6702a32011-12-20 02:08:33 +0000143 // C++11 [expr.prim.general]p12:
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000144 // 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)
Chris Lattner5f9e2722011-07-23 10:55:15 +0000301 << StringRef(compStr, 1) << SourceRange(CompLoc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000302 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.
Douglas Gregord58a0a52011-07-28 00:39:29 +0000340 for (Sema::ExtVectorDeclsType::iterator
341 I = S.ExtVectorDecls.begin(S.ExternalSource),
342 E = S.ExtVectorDecls.end();
343 I != E; ++I) {
344 if ((*I)->getUnderlyingType() == VT)
345 return S.Context.getTypedefType(*I);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000346 }
Douglas Gregord58a0a52011-07-28 00:39:29 +0000347
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000348 return VT; // should never get here (a typedef type should always be found).
349}
350
351static Decl *FindGetterSetterNameDeclFromProtocolList(const ObjCProtocolDecl*PDecl,
352 IdentifierInfo *Member,
353 const Selector &Sel,
354 ASTContext &Context) {
355 if (Member)
356 if (ObjCPropertyDecl *PD = PDecl->FindPropertyDeclaration(Member))
357 return PD;
358 if (ObjCMethodDecl *OMD = PDecl->getInstanceMethod(Sel))
359 return OMD;
360
361 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
362 E = PDecl->protocol_end(); I != E; ++I) {
363 if (Decl *D = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
364 Context))
365 return D;
366 }
367 return 0;
368}
369
370static Decl *FindGetterSetterNameDecl(const ObjCObjectPointerType *QIdTy,
371 IdentifierInfo *Member,
372 const Selector &Sel,
373 ASTContext &Context) {
374 // Check protocols on qualified interfaces.
375 Decl *GDecl = 0;
376 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
377 E = QIdTy->qual_end(); I != E; ++I) {
378 if (Member)
379 if (ObjCPropertyDecl *PD = (*I)->FindPropertyDeclaration(Member)) {
380 GDecl = PD;
381 break;
382 }
383 // Also must look for a getter or setter name which uses property syntax.
384 if (ObjCMethodDecl *OMD = (*I)->getInstanceMethod(Sel)) {
385 GDecl = OMD;
386 break;
387 }
388 }
389 if (!GDecl) {
390 for (ObjCObjectPointerType::qual_iterator I = QIdTy->qual_begin(),
391 E = QIdTy->qual_end(); I != E; ++I) {
392 // Search in the protocol-qualifier list of current protocol.
393 GDecl = FindGetterSetterNameDeclFromProtocolList(*I, Member, Sel,
394 Context);
395 if (GDecl)
396 return GDecl;
397 }
398 }
399 return GDecl;
400}
401
402ExprResult
403Sema::ActOnDependentMemberExpr(Expr *BaseExpr, QualType BaseType,
404 bool IsArrow, SourceLocation OpLoc,
405 const CXXScopeSpec &SS,
406 NamedDecl *FirstQualifierInScope,
407 const DeclarationNameInfo &NameInfo,
408 const TemplateArgumentListInfo *TemplateArgs) {
409 // Even in dependent contexts, try to diagnose base expressions with
410 // obviously wrong types, e.g.:
411 //
412 // T* t;
413 // t.f;
414 //
415 // In Obj-C++, however, the above expression is valid, since it could be
416 // accessing the 'f' property if T is an Obj-C interface. The extra check
417 // allows this, while still reporting an error if T is a struct pointer.
418 if (!IsArrow) {
419 const PointerType *PT = BaseType->getAs<PointerType>();
420 if (PT && (!getLangOptions().ObjC1 ||
421 PT->getPointeeType()->isRecordType())) {
422 assert(BaseExpr && "cannot happen with implicit member accesses");
423 Diag(NameInfo.getLoc(), diag::err_typecheck_member_reference_struct_union)
424 << BaseType << BaseExpr->getSourceRange();
425 return ExprError();
426 }
427 }
428
429 assert(BaseType->isDependentType() ||
430 NameInfo.getName().isDependentName() ||
431 isDependentScopeSpecifier(SS));
432
433 // Get the type being accessed in BaseType. If this is an arrow, the BaseExpr
434 // must have pointer type, and the accessed type is the pointee.
435 return Owned(CXXDependentScopeMemberExpr::Create(Context, BaseExpr, BaseType,
436 IsArrow, OpLoc,
437 SS.getWithLocInContext(Context),
438 FirstQualifierInScope,
439 NameInfo, TemplateArgs));
440}
441
442/// We know that the given qualified member reference points only to
443/// declarations which do not belong to the static type of the base
444/// expression. Diagnose the problem.
445static void DiagnoseQualifiedMemberReference(Sema &SemaRef,
446 Expr *BaseExpr,
447 QualType BaseType,
448 const CXXScopeSpec &SS,
449 NamedDecl *rep,
450 const DeclarationNameInfo &nameInfo) {
451 // If this is an implicit member access, use a different set of
452 // diagnostics.
453 if (!BaseExpr)
454 return DiagnoseInstanceReference(SemaRef, SS, rep, nameInfo);
455
456 SemaRef.Diag(nameInfo.getLoc(), diag::err_qualified_member_of_unrelated)
457 << SS.getRange() << rep << BaseType;
458}
459
460// Check whether the declarations we found through a nested-name
461// specifier in a member expression are actually members of the base
462// type. The restriction here is:
463//
464// C++ [expr.ref]p2:
465// ... In these cases, the id-expression shall name a
466// member of the class or of one of its base classes.
467//
468// So it's perfectly legitimate for the nested-name specifier to name
469// an unrelated class, and for us to find an overload set including
470// decls from classes which are not superclasses, as long as the decl
471// we actually pick through overload resolution is from a superclass.
472bool Sema::CheckQualifiedMemberReference(Expr *BaseExpr,
473 QualType BaseType,
474 const CXXScopeSpec &SS,
475 const LookupResult &R) {
476 const RecordType *BaseRT = BaseType->getAs<RecordType>();
477 if (!BaseRT) {
478 // We can't check this yet because the base type is still
479 // dependent.
480 assert(BaseType->isDependentType());
481 return false;
482 }
483 CXXRecordDecl *BaseRecord = cast<CXXRecordDecl>(BaseRT->getDecl());
484
485 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
486 // If this is an implicit member reference and we find a
487 // non-instance member, it's not an error.
488 if (!BaseExpr && !(*I)->isCXXInstanceMember())
489 return false;
490
491 // Note that we use the DC of the decl, not the underlying decl.
492 DeclContext *DC = (*I)->getDeclContext();
493 while (DC->isTransparentContext())
494 DC = DC->getParent();
495
496 if (!DC->isRecord())
497 continue;
498
499 llvm::SmallPtrSet<CXXRecordDecl*,4> MemberRecord;
500 MemberRecord.insert(cast<CXXRecordDecl>(DC)->getCanonicalDecl());
501
502 if (!IsProvablyNotDerivedFrom(*this, BaseRecord, MemberRecord))
503 return false;
504 }
505
506 DiagnoseQualifiedMemberReference(*this, BaseExpr, BaseType, SS,
507 R.getRepresentativeDecl(),
508 R.getLookupNameInfo());
509 return true;
510}
511
512static bool
513LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
514 SourceRange BaseRange, const RecordType *RTy,
515 SourceLocation OpLoc, CXXScopeSpec &SS,
516 bool HasTemplateArgs) {
517 RecordDecl *RDecl = RTy->getDecl();
518 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
519 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
520 << BaseRange))
521 return true;
522
523 if (HasTemplateArgs) {
524 // LookupTemplateName doesn't expect these both to exist simultaneously.
525 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
526
527 bool MOUS;
528 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
529 return false;
530 }
531
532 DeclContext *DC = RDecl;
533 if (SS.isSet()) {
534 // If the member name was a qualified-id, look into the
535 // nested-name-specifier.
536 DC = SemaRef.computeDeclContext(SS, false);
537
538 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
539 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
540 << SS.getRange() << DC;
541 return true;
542 }
543
544 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
545
546 if (!isa<TypeDecl>(DC)) {
547 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
548 << DC << SS.getRange();
549 return true;
550 }
551 }
552
553 // The record definition is complete, now look up the member.
554 SemaRef.LookupQualifiedName(R, DC);
555
556 if (!R.empty())
557 return false;
558
559 // We didn't find anything with the given name, so try to correct
560 // for typos.
561 DeclarationName Name = R.getLookupName();
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000562 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
563 R.getLookupKind(), NULL,
564 &SS, DC, false,
565 Sema::CTC_MemberLookup);
566 NamedDecl *ND = Corrected.getCorrectionDecl();
567 R.clear();
568 if (ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND))) {
569 std::string CorrectedStr(
570 Corrected.getAsString(SemaRef.getLangOptions()));
571 std::string CorrectedQuotedStr(
572 Corrected.getQuoted(SemaRef.getLangOptions()));
573 R.setLookupName(Corrected.getCorrection());
574 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000575 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000576 << Name << DC << CorrectedQuotedStr << SS.getRange()
577 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
578 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
579 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000580 }
581
582 return false;
583}
584
585ExprResult
586Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
587 SourceLocation OpLoc, bool IsArrow,
588 CXXScopeSpec &SS,
589 NamedDecl *FirstQualifierInScope,
590 const DeclarationNameInfo &NameInfo,
591 const TemplateArgumentListInfo *TemplateArgs) {
592 if (BaseType->isDependentType() ||
593 (SS.isSet() && isDependentScopeSpecifier(SS)))
594 return ActOnDependentMemberExpr(Base, BaseType,
595 IsArrow, OpLoc,
596 SS, FirstQualifierInScope,
597 NameInfo, TemplateArgs);
598
599 LookupResult R(*this, NameInfo, LookupMemberName);
600
601 // Implicit member accesses.
602 if (!Base) {
603 QualType RecordTy = BaseType;
604 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
605 if (LookupMemberExprInRecord(*this, R, SourceRange(),
606 RecordTy->getAs<RecordType>(),
607 OpLoc, SS, TemplateArgs != 0))
608 return ExprError();
609
610 // Explicit member accesses.
611 } else {
612 ExprResult BaseResult = Owned(Base);
613 ExprResult Result =
614 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
615 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
616
617 if (BaseResult.isInvalid())
618 return ExprError();
619 Base = BaseResult.take();
620
621 if (Result.isInvalid()) {
622 Owned(Base);
623 return ExprError();
624 }
625
626 if (Result.get())
627 return move(Result);
628
629 // LookupMemberExpr can modify Base, and thus change BaseType
630 BaseType = Base->getType();
631 }
632
633 return BuildMemberReferenceExpr(Base, BaseType,
634 OpLoc, IsArrow, SS, FirstQualifierInScope,
635 R, TemplateArgs);
636}
637
638static ExprResult
639BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
640 const CXXScopeSpec &SS, FieldDecl *Field,
641 DeclAccessPair FoundDecl,
642 const DeclarationNameInfo &MemberNameInfo);
643
644ExprResult
645Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
646 SourceLocation loc,
647 IndirectFieldDecl *indirectField,
648 Expr *baseObjectExpr,
649 SourceLocation opLoc) {
650 // First, build the expression that refers to the base object.
651
652 bool baseObjectIsPointer = false;
653 Qualifiers baseQuals;
654
655 // Case 1: the base of the indirect field is not a field.
656 VarDecl *baseVariable = indirectField->getVarDecl();
657 CXXScopeSpec EmptySS;
658 if (baseVariable) {
659 assert(baseVariable->getType()->isRecordType());
660
661 // In principle we could have a member access expression that
662 // accesses an anonymous struct/union that's a static member of
663 // the base object's class. However, under the current standard,
664 // static data members cannot be anonymous structs or unions.
665 // Supporting this is as easy as building a MemberExpr here.
666 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
667
668 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
669
670 ExprResult result
671 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
672 if (result.isInvalid()) return ExprError();
673
674 baseObjectExpr = result.take();
675 baseObjectIsPointer = false;
676 baseQuals = baseObjectExpr->getType().getQualifiers();
677
678 // Case 2: the base of the indirect field is a field and the user
679 // wrote a member expression.
680 } else if (baseObjectExpr) {
681 // The caller provided the base object expression. Determine
682 // whether its a pointer and whether it adds any qualifiers to the
683 // anonymous struct/union fields we're looking into.
684 QualType objectType = baseObjectExpr->getType();
685
686 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
687 baseObjectIsPointer = true;
688 objectType = ptr->getPointeeType();
689 } else {
690 baseObjectIsPointer = false;
691 }
692 baseQuals = objectType.getQualifiers();
693
694 // Case 3: the base of the indirect field is a field and we should
695 // build an implicit member access.
696 } else {
697 // We've found a member of an anonymous struct/union that is
698 // inside a non-anonymous struct/union, so in a well-formed
699 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000700 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000701 if (ThisTy.isNull()) {
702 Diag(loc, diag::err_invalid_member_use_in_static_method)
703 << indirectField->getDeclName();
704 return ExprError();
705 }
706
707 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000708 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000709 baseObjectExpr
710 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
711 baseObjectIsPointer = true;
712 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
713 }
714
715 // Build the implicit member references to the field of the
716 // anonymous struct/union.
717 Expr *result = baseObjectExpr;
718 IndirectFieldDecl::chain_iterator
719 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
720
721 // Build the first member access in the chain with full information.
722 if (!baseVariable) {
723 FieldDecl *field = cast<FieldDecl>(*FI);
724
725 // FIXME: use the real found-decl info!
726 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
727
728 // Make a nameInfo that properly uses the anonymous name.
729 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
730
731 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
732 EmptySS, field, foundDecl,
733 memberNameInfo).take();
734 baseObjectIsPointer = false;
735
736 // FIXME: check qualified member access
737 }
738
739 // In all cases, we should now skip the first declaration in the chain.
740 ++FI;
741
742 while (FI != FEnd) {
743 FieldDecl *field = cast<FieldDecl>(*FI++);
744
745 // FIXME: these are somewhat meaningless
746 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
747 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
748
749 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
750 (FI == FEnd? SS : EmptySS), field,
751 foundDecl, memberNameInfo).take();
752 }
753
754 return Owned(result);
755}
756
757/// \brief Build a MemberExpr AST node.
758static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
759 const CXXScopeSpec &SS, ValueDecl *Member,
760 DeclAccessPair FoundDecl,
761 const DeclarationNameInfo &MemberNameInfo,
762 QualType Ty,
763 ExprValueKind VK, ExprObjectKind OK,
764 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000765 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000766 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
767 Member, FoundDecl, MemberNameInfo,
768 TemplateArgs, Ty, VK, OK);
769}
770
771ExprResult
772Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
773 SourceLocation OpLoc, bool IsArrow,
774 const CXXScopeSpec &SS,
775 NamedDecl *FirstQualifierInScope,
776 LookupResult &R,
777 const TemplateArgumentListInfo *TemplateArgs,
778 bool SuppressQualifierCheck) {
779 QualType BaseType = BaseExprType;
780 if (IsArrow) {
781 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000782 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000783 }
784 R.setBaseObjectType(BaseType);
785
786 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
787 DeclarationName MemberName = MemberNameInfo.getName();
788 SourceLocation MemberLoc = MemberNameInfo.getLoc();
789
790 if (R.isAmbiguous())
791 return ExprError();
792
793 if (R.empty()) {
794 // Rederive where we looked up.
795 DeclContext *DC = (SS.isSet()
796 ? computeDeclContext(SS, false)
797 : BaseType->getAs<RecordType>()->getDecl());
798
799 Diag(R.getNameLoc(), diag::err_no_member)
800 << MemberName << DC
801 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
802 return ExprError();
803 }
804
805 // Diagnose lookups that find only declarations from a non-base
806 // type. This is possible for either qualified lookups (which may
807 // have been qualified with an unrelated type) or implicit member
808 // expressions (which were found with unqualified lookup and thus
809 // may have come from an enclosing scope). Note that it's okay for
810 // lookup to find declarations from a non-base type as long as those
811 // aren't the ones picked by overload resolution.
812 if ((SS.isSet() || !BaseExpr ||
813 (isa<CXXThisExpr>(BaseExpr) &&
814 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
815 !SuppressQualifierCheck &&
816 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
817 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000818
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000819 // Construct an unresolved result if we in fact got an unresolved
820 // result.
821 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
822 // Suppress any lookup-related diagnostics; we'll do these when we
823 // pick a member.
824 R.suppressDiagnostics();
825
826 UnresolvedMemberExpr *MemExpr
827 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
828 BaseExpr, BaseExprType,
829 IsArrow, OpLoc,
830 SS.getWithLocInContext(Context),
831 MemberNameInfo,
832 TemplateArgs, R.begin(), R.end());
833
834 return Owned(MemExpr);
835 }
836
837 assert(R.isSingleResult());
838 DeclAccessPair FoundDecl = R.begin().getPair();
839 NamedDecl *MemberDecl = R.getFoundDecl();
840
841 // FIXME: diagnose the presence of template arguments now.
842
843 // If the decl being referenced had an error, return an error for this
844 // sub-expr without emitting another error, in order to avoid cascading
845 // error cases.
846 if (MemberDecl->isInvalidDecl())
847 return ExprError();
848
849 // Handle the implicit-member-access case.
850 if (!BaseExpr) {
851 // If this is not an instance member, convert to a non-member access.
852 if (!MemberDecl->isCXXInstanceMember())
853 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
854
855 SourceLocation Loc = R.getNameLoc();
856 if (SS.getRange().isValid())
857 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000858 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000859 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
860 }
861
862 bool ShouldCheckUse = true;
863 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
864 // Don't diagnose the use of a virtual member function unless it's
865 // explicitly qualified.
866 if (MD->isVirtual() && !SS.isSet())
867 ShouldCheckUse = false;
868 }
869
870 // Check the use of this member.
871 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
872 Owned(BaseExpr);
873 return ExprError();
874 }
875
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000876 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
877 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
878 SS, FD, FoundDecl, MemberNameInfo);
879
880 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
881 // We may have found a field within an anonymous union or struct
882 // (C++ [class.union]).
883 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
884 BaseExpr, OpLoc);
885
886 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
887 MarkDeclarationReferenced(MemberLoc, Var);
888 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
889 Var, FoundDecl, MemberNameInfo,
890 Var->getType().getNonReferenceType(),
891 VK_LValue, OK_Ordinary));
892 }
893
894 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
895 ExprValueKind valueKind;
896 QualType type;
897 if (MemberFn->isInstance()) {
898 valueKind = VK_RValue;
899 type = Context.BoundMemberTy;
900 } else {
901 valueKind = VK_LValue;
902 type = MemberFn->getType();
903 }
904
905 MarkDeclarationReferenced(MemberLoc, MemberDecl);
906 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
907 MemberFn, FoundDecl, MemberNameInfo,
908 type, valueKind, OK_Ordinary));
909 }
910 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
911
912 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
913 MarkDeclarationReferenced(MemberLoc, MemberDecl);
914 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
915 Enum, FoundDecl, MemberNameInfo,
916 Enum->getType(), VK_RValue, OK_Ordinary));
917 }
918
919 Owned(BaseExpr);
920
921 // We found something that we didn't expect. Complain.
922 if (isa<TypeDecl>(MemberDecl))
923 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
924 << MemberName << BaseType << int(IsArrow);
925 else
926 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
927 << MemberName << BaseType << int(IsArrow);
928
929 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
930 << MemberName;
931 R.suppressDiagnostics();
932 return ExprError();
933}
934
935/// Given that normal member access failed on the given expression,
936/// and given that the expression's type involves builtin-id or
937/// builtin-Class, decide whether substituting in the redefinition
938/// types would be profitable. The redefinition type is whatever
939/// this translation unit tried to typedef to id/Class; we store
940/// it to the side and then re-use it in places like this.
941static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
942 const ObjCObjectPointerType *opty
943 = base.get()->getType()->getAs<ObjCObjectPointerType>();
944 if (!opty) return false;
945
946 const ObjCObjectType *ty = opty->getObjectType();
947
948 QualType redef;
949 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000950 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000951 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000952 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000953 } else {
954 return false;
955 }
956
957 // Do the substitution as long as the redefinition type isn't just a
958 // possibly-qualified pointer to builtin-id or builtin-Class again.
959 opty = redef->getAs<ObjCObjectPointerType>();
960 if (opty && !opty->getObjectType()->getInterface() != 0)
961 return false;
962
963 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
964 return true;
965}
966
John McCall6dbba4f2011-10-11 23:14:30 +0000967static bool isRecordType(QualType T) {
968 return T->isRecordType();
969}
970static bool isPointerToRecordType(QualType T) {
971 if (const PointerType *PT = T->getAs<PointerType>())
972 return PT->getPointeeType()->isRecordType();
973 return false;
974}
975
Richard Smith9138b4e2011-10-26 19:06:56 +0000976/// Perform conversions on the LHS of a member access expression.
977ExprResult
978Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
979 ExprResult BaseResult = DefaultFunctionArrayConversion(Base);
980
981 if (!BaseResult.isInvalid() && IsArrow)
982 BaseResult = DefaultLvalueConversion(BaseResult.take());
983
984 return BaseResult;
985}
986
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000987/// Look up the given member of the given non-type-dependent
988/// expression. This can return in one of two ways:
989/// * If it returns a sentinel null-but-valid result, the caller will
990/// assume that lookup was performed and the results written into
991/// the provided structure. It will take over from there.
992/// * Otherwise, the returned expression will be produced in place of
993/// an ordinary member expression.
994///
995/// The ObjCImpDecl bit is a gross hack that will need to be properly
996/// fixed for ObjC++.
997ExprResult
998Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
999 bool &IsArrow, SourceLocation OpLoc,
1000 CXXScopeSpec &SS,
1001 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1002 assert(BaseExpr.get() && "no base expression");
1003
1004 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001005 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001006 if (BaseExpr.isInvalid())
1007 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001008
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001009 QualType BaseType = BaseExpr.get()->getType();
1010 assert(!BaseType->isDependentType());
1011
1012 DeclarationName MemberName = R.getLookupName();
1013 SourceLocation MemberLoc = R.getNameLoc();
1014
1015 // For later type-checking purposes, turn arrow accesses into dot
1016 // accesses. The only access type we support that doesn't follow
1017 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1018 // and those never use arrows, so this is unaffected.
1019 if (IsArrow) {
1020 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1021 BaseType = Ptr->getPointeeType();
1022 else if (const ObjCObjectPointerType *Ptr
1023 = BaseType->getAs<ObjCObjectPointerType>())
1024 BaseType = Ptr->getPointeeType();
1025 else if (BaseType->isRecordType()) {
1026 // Recover from arrow accesses to records, e.g.:
1027 // struct MyRecord foo;
1028 // foo->bar
1029 // This is actually well-formed in C++ if MyRecord has an
1030 // overloaded operator->, but that should have been dealt with
1031 // by now.
1032 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1033 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1034 << FixItHint::CreateReplacement(OpLoc, ".");
1035 IsArrow = false;
1036 } else if (BaseType == Context.BoundMemberTy) {
1037 goto fail;
1038 } else {
1039 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1040 << BaseType << BaseExpr.get()->getSourceRange();
1041 return ExprError();
1042 }
1043 }
1044
1045 // Handle field access to simple records.
1046 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1047 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1048 RTy, OpLoc, SS, HasTemplateArgs))
1049 return ExprError();
1050
1051 // Returning valid-but-null is how we indicate to the caller that
1052 // the lookup result was filled in.
1053 return Owned((Expr*) 0);
1054 }
1055
1056 // Handle ivar access to Objective-C objects.
1057 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001058 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001059 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1060 << 1 << SS.getScopeRep()
1061 << FixItHint::CreateRemoval(SS.getRange());
1062 SS.clear();
1063 }
1064
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001065 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1066
1067 // There are three cases for the base type:
1068 // - builtin id (qualified or unqualified)
1069 // - builtin Class (qualified or unqualified)
1070 // - an interface
1071 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1072 if (!IDecl) {
1073 if (getLangOptions().ObjCAutoRefCount &&
1074 (OTy->isObjCId() || OTy->isObjCClass()))
1075 goto fail;
1076 // There's an implicit 'isa' ivar on all objects.
1077 // But we only actually find it this way on objects of type 'id',
1078 // apparently.
1079 if (OTy->isObjCId() && Member->isStr("isa"))
1080 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1081 Context.getObjCClassType()));
1082
1083 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1084 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1085 ObjCImpDecl, HasTemplateArgs);
1086 goto fail;
1087 }
1088
Douglas Gregord07cc362012-01-02 17:18:37 +00001089 if (RequireCompleteType(OpLoc, BaseType,
1090 PDiag(diag::err_typecheck_incomplete_tag)
1091 << BaseExpr.get()->getSourceRange()))
1092 return ExprError();
1093
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001094 ObjCInterfaceDecl *ClassDeclared;
1095 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1096
1097 if (!IV) {
1098 // Attempt to correct for typos in ivar names.
1099 LookupResult Res(*this, R.getLookupName(), R.getNameLoc(),
1100 LookupMemberName);
Douglas Gregord8bba9c2011-06-28 16:20:02 +00001101 TypoCorrection Corrected = CorrectTypo(
1102 R.getLookupNameInfo(), LookupMemberName, NULL, NULL, IDecl, false,
1103 IsArrow ? CTC_ObjCIvarLookup : CTC_ObjCPropertyLookup);
1104 if ((IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>())) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001105 Diag(R.getNameLoc(),
1106 diag::err_typecheck_member_reference_ivar_suggest)
1107 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1108 << FixItHint::CreateReplacement(R.getNameLoc(),
1109 IV->getNameAsString());
1110 Diag(IV->getLocation(), diag::note_previous_decl)
1111 << IV->getDeclName();
1112 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001113 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1114 Diag(MemberLoc,
1115 diag::err_property_found_suggest)
1116 << Member << BaseExpr.get()->getType()
1117 << FixItHint::CreateReplacement(OpLoc, ".");
1118 return ExprError();
1119 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001120 Res.clear();
1121 Res.setLookupName(Member);
1122
1123 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1124 << IDecl->getDeclName() << MemberName
1125 << BaseExpr.get()->getSourceRange();
1126 return ExprError();
1127 }
1128 }
1129
1130 // If the decl being referenced had an error, return an error for this
1131 // sub-expr without emitting another error, in order to avoid cascading
1132 // error cases.
1133 if (IV->isInvalidDecl())
1134 return ExprError();
1135
1136 // Check whether we can reference this field.
1137 if (DiagnoseUseOfDecl(IV, MemberLoc))
1138 return ExprError();
1139 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1140 IV->getAccessControl() != ObjCIvarDecl::Package) {
1141 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1142 if (ObjCMethodDecl *MD = getCurMethodDecl())
1143 ClassOfMethodDecl = MD->getClassInterface();
1144 else if (ObjCImpDecl && getCurFunctionDecl()) {
1145 // Case of a c-function declared inside an objc implementation.
1146 // FIXME: For a c-style function nested inside an objc implementation
1147 // class, there is no implementation context available, so we pass
1148 // down the context as argument to this routine. Ideally, this context
1149 // need be passed down in the AST node and somehow calculated from the
1150 // AST for a function decl.
1151 if (ObjCImplementationDecl *IMPD =
1152 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1153 ClassOfMethodDecl = IMPD->getClassInterface();
1154 else if (ObjCCategoryImplDecl* CatImplClass =
1155 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1156 ClassOfMethodDecl = CatImplClass->getClassInterface();
1157 }
1158
1159 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Douglas Gregor60ef3082011-12-15 00:29:59 +00001160 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1161 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001162 Diag(MemberLoc, diag::error_private_ivar_access)
1163 << IV->getDeclName();
1164 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1165 // @protected
1166 Diag(MemberLoc, diag::error_protected_ivar_access)
1167 << IV->getDeclName();
1168 }
1169 if (getLangOptions().ObjCAutoRefCount) {
1170 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1171 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1172 if (UO->getOpcode() == UO_Deref)
1173 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1174
1175 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1176 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1177 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1178 }
1179
1180 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1181 MemberLoc, BaseExpr.take(),
1182 IsArrow));
1183 }
1184
1185 // Objective-C property access.
1186 const ObjCObjectPointerType *OPT;
1187 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001188 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001189 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1190 << 0 << SS.getScopeRep()
1191 << FixItHint::CreateRemoval(SS.getRange());
1192 SS.clear();
1193 }
1194
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001195 // This actually uses the base as an r-value.
1196 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1197 if (BaseExpr.isInvalid())
1198 return ExprError();
1199
1200 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1201
1202 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1203
1204 const ObjCObjectType *OT = OPT->getObjectType();
1205
1206 // id, with and without qualifiers.
1207 if (OT->isObjCId()) {
1208 // Check protocols on qualified interfaces.
1209 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1210 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1211 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1212 // Check the use of this declaration
1213 if (DiagnoseUseOfDecl(PD, MemberLoc))
1214 return ExprError();
1215
John McCall3c3b7f92011-10-25 17:37:35 +00001216 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1217 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001218 VK_LValue,
1219 OK_ObjCProperty,
1220 MemberLoc,
1221 BaseExpr.take()));
1222 }
1223
1224 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1225 // Check the use of this method.
1226 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1227 return ExprError();
1228 Selector SetterSel =
1229 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1230 PP.getSelectorTable(), Member);
1231 ObjCMethodDecl *SMD = 0;
1232 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1233 SetterSel, Context))
1234 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001235
John McCall3c3b7f92011-10-25 17:37:35 +00001236 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1237 Context.PseudoObjectTy,
1238 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001239 MemberLoc, BaseExpr.take()));
1240 }
1241 }
1242 // Use of id.member can only be for a property reference. Do not
1243 // use the 'id' redefinition in this case.
1244 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1245 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1246 ObjCImpDecl, HasTemplateArgs);
1247
1248 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1249 << MemberName << BaseType);
1250 }
1251
1252 // 'Class', unqualified only.
1253 if (OT->isObjCClass()) {
1254 // Only works in a method declaration (??!).
1255 ObjCMethodDecl *MD = getCurMethodDecl();
1256 if (!MD) {
1257 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1258 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1259 ObjCImpDecl, HasTemplateArgs);
1260
1261 goto fail;
1262 }
1263
1264 // Also must look for a getter name which uses property syntax.
1265 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1266 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1267 ObjCMethodDecl *Getter;
1268 if ((Getter = IFace->lookupClassMethod(Sel))) {
1269 // Check the use of this method.
1270 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1271 return ExprError();
1272 } else
1273 Getter = IFace->lookupPrivateMethod(Sel, false);
1274 // If we found a getter then this may be a valid dot-reference, we
1275 // will look for the matching setter, in case it is needed.
1276 Selector SetterSel =
1277 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1278 PP.getSelectorTable(), Member);
1279 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1280 if (!Setter) {
1281 // If this reference is in an @implementation, also check for 'private'
1282 // methods.
1283 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1284 }
1285 // Look through local category implementations associated with the class.
1286 if (!Setter)
1287 Setter = IFace->getCategoryClassMethod(SetterSel);
1288
1289 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1290 return ExprError();
1291
1292 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001293 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001294 Context.PseudoObjectTy,
1295 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001296 MemberLoc, BaseExpr.take()));
1297 }
1298
1299 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1300 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1301 ObjCImpDecl, HasTemplateArgs);
1302
1303 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1304 << MemberName << BaseType);
1305 }
1306
1307 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001308 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1309 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001310 SourceLocation(), QualType(), false);
1311 }
1312
1313 // Handle 'field access' to vectors, such as 'V.xx'.
1314 if (BaseType->isExtVectorType()) {
1315 // FIXME: this expr should store IsArrow.
1316 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1317 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1318 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1319 Member, MemberLoc);
1320 if (ret.isNull())
1321 return ExprError();
1322
1323 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1324 *Member, MemberLoc));
1325 }
1326
1327 // Adjust builtin-sel to the appropriate redefinition type if that's
1328 // not just a pointer to builtin-sel again.
1329 if (IsArrow &&
1330 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001331 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1332 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1333 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001334 CK_BitCast);
1335 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1336 ObjCImpDecl, HasTemplateArgs);
1337 }
1338
1339 // Failure cases.
1340 fail:
1341
1342 // Recover from dot accesses to pointers, e.g.:
1343 // type *foo;
1344 // foo.bar
1345 // This is actually well-formed in two cases:
1346 // - 'type' is an Objective C type
1347 // - 'bar' is a pseudo-destructor name which happens to refer to
1348 // the appropriate pointer type
1349 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1350 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1351 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1352 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1353 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1354 << FixItHint::CreateReplacement(OpLoc, "->");
1355
1356 // Recurse as an -> access.
1357 IsArrow = true;
1358 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1359 ObjCImpDecl, HasTemplateArgs);
1360 }
1361 }
1362
1363 // If the user is trying to apply -> or . to a function name, it's probably
1364 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001365 if (tryToRecoverWithCall(BaseExpr,
1366 PDiag(diag::err_member_reference_needs_call),
1367 /*complain*/ false,
1368 IsArrow ? &isRecordType : &isPointerToRecordType)) {
1369 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001370 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001371 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1372 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1373 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001374 }
1375
1376 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1377 << BaseType << BaseExpr.get()->getSourceRange();
1378
1379 return ExprError();
1380}
1381
1382/// The main callback when the parser finds something like
1383/// expression . [nested-name-specifier] identifier
1384/// expression -> [nested-name-specifier] identifier
1385/// where 'identifier' encompasses a fairly broad spectrum of
1386/// possibilities, including destructor and operator references.
1387///
1388/// \param OpKind either tok::arrow or tok::period
1389/// \param HasTrailingLParen whether the next token is '(', which
1390/// is used to diagnose mis-uses of special members that can
1391/// only be called
1392/// \param ObjCImpDecl the current ObjC @implementation decl;
1393/// this is an ugly hack around the fact that ObjC @implementations
1394/// aren't properly put in the context chain
1395ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1396 SourceLocation OpLoc,
1397 tok::TokenKind OpKind,
1398 CXXScopeSpec &SS,
1399 UnqualifiedId &Id,
1400 Decl *ObjCImpDecl,
1401 bool HasTrailingLParen) {
1402 if (SS.isSet() && SS.isInvalid())
1403 return ExprError();
1404
1405 // Warn about the explicit constructor calls Microsoft extension.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001406 if (getLangOptions().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001407 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1408 Diag(Id.getSourceRange().getBegin(),
1409 diag::ext_ms_explicit_constructor_call);
1410
1411 TemplateArgumentListInfo TemplateArgsBuffer;
1412
1413 // Decompose the name into its component parts.
1414 DeclarationNameInfo NameInfo;
1415 const TemplateArgumentListInfo *TemplateArgs;
1416 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1417 NameInfo, TemplateArgs);
1418
1419 DeclarationName Name = NameInfo.getName();
1420 bool IsArrow = (OpKind == tok::arrow);
1421
1422 NamedDecl *FirstQualifierInScope
1423 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1424 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1425
1426 // This is a postfix expression, so get rid of ParenListExprs.
1427 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1428 if (Result.isInvalid()) return ExprError();
1429 Base = Result.take();
1430
1431 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1432 isDependentScopeSpecifier(SS)) {
1433 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1434 IsArrow, OpLoc,
1435 SS, FirstQualifierInScope,
1436 NameInfo, TemplateArgs);
1437 } else {
1438 LookupResult R(*this, NameInfo, LookupMemberName);
1439 ExprResult BaseResult = Owned(Base);
1440 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1441 SS, ObjCImpDecl, TemplateArgs != 0);
1442 if (BaseResult.isInvalid())
1443 return ExprError();
1444 Base = BaseResult.take();
1445
1446 if (Result.isInvalid()) {
1447 Owned(Base);
1448 return ExprError();
1449 }
1450
1451 if (Result.get()) {
1452 // The only way a reference to a destructor can be used is to
1453 // immediately call it, which falls into this case. If the
1454 // next token is not a '(', produce a diagnostic and build the
1455 // call now.
1456 if (!HasTrailingLParen &&
1457 Id.getKind() == UnqualifiedId::IK_DestructorName)
1458 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1459
1460 return move(Result);
1461 }
1462
1463 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1464 OpLoc, IsArrow, SS, FirstQualifierInScope,
1465 R, TemplateArgs);
1466 }
1467
1468 return move(Result);
1469}
1470
1471static ExprResult
1472BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1473 const CXXScopeSpec &SS, FieldDecl *Field,
1474 DeclAccessPair FoundDecl,
1475 const DeclarationNameInfo &MemberNameInfo) {
1476 // x.a is an l-value if 'a' has a reference type. Otherwise:
1477 // x.a is an l-value/x-value/pr-value if the base is (and note
1478 // that *x is always an l-value), except that if the base isn't
1479 // an ordinary object then we must have an rvalue.
1480 ExprValueKind VK = VK_LValue;
1481 ExprObjectKind OK = OK_Ordinary;
1482 if (!IsArrow) {
1483 if (BaseExpr->getObjectKind() == OK_Ordinary)
1484 VK = BaseExpr->getValueKind();
1485 else
1486 VK = VK_RValue;
1487 }
1488 if (VK != VK_RValue && Field->isBitField())
1489 OK = OK_BitField;
1490
1491 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1492 QualType MemberType = Field->getType();
1493 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1494 MemberType = Ref->getPointeeType();
1495 VK = VK_LValue;
1496 } else {
1497 QualType BaseType = BaseExpr->getType();
1498 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1499
1500 Qualifiers BaseQuals = BaseType.getQualifiers();
1501
1502 // GC attributes are never picked up by members.
1503 BaseQuals.removeObjCGCAttr();
1504
1505 // CVR attributes from the base are picked up by members,
1506 // except that 'mutable' members don't pick up 'const'.
1507 if (Field->isMutable()) BaseQuals.removeConst();
1508
1509 Qualifiers MemberQuals
1510 = S.Context.getCanonicalType(MemberType).getQualifiers();
1511
1512 // TR 18037 does not allow fields to be declared with address spaces.
1513 assert(!MemberQuals.hasAddressSpace());
1514
1515 Qualifiers Combined = BaseQuals + MemberQuals;
1516 if (Combined != MemberQuals)
1517 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1518 }
1519
1520 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1521 ExprResult Base =
1522 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1523 FoundDecl, Field);
1524 if (Base.isInvalid())
1525 return ExprError();
1526 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
1527 Field, FoundDecl, MemberNameInfo,
1528 MemberType, VK, OK));
1529}
1530
1531/// Builds an implicit member access expression. The current context
1532/// is known to be an instance method, and the given unqualified lookup
1533/// set is known to contain only instance members, at least one of which
1534/// is from an appropriate type.
1535ExprResult
1536Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1537 LookupResult &R,
1538 const TemplateArgumentListInfo *TemplateArgs,
1539 bool IsKnownInstance) {
1540 assert(!R.empty() && !R.isAmbiguous());
1541
1542 SourceLocation loc = R.getNameLoc();
1543
1544 // We may have found a field within an anonymous union or struct
1545 // (C++ [class.union]).
1546 // FIXME: template-ids inside anonymous structs?
1547 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1548 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1549
1550 // If this is known to be an instance access, go ahead and build an
1551 // implicit 'this' expression now.
1552 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001553 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001554 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1555
1556 Expr *baseExpr = 0; // null signifies implicit access
1557 if (IsKnownInstance) {
1558 SourceLocation Loc = R.getNameLoc();
1559 if (SS.getRange().isValid())
1560 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001561 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001562 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1563 }
1564
1565 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1566 /*OpLoc*/ SourceLocation(),
1567 /*IsArrow*/ true,
1568 SS,
1569 /*FirstQualifierInScope*/ 0,
1570 R, TemplateArgs);
1571}