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