blob: 0080156376ef95297578d15fa8db18fe015e255d [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
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000512namespace {
513
514// Callback to only accept typo corrections that are either a ValueDecl or a
515// FunctionTemplateDecl.
516class RecordMemberExprValidatorCCC : public CorrectionCandidateCallback {
517 public:
518 virtual bool ValidateCandidate(const TypoCorrection &candidate) {
519 NamedDecl *ND = candidate.getCorrectionDecl();
520 return ND && (isa<ValueDecl>(ND) || isa<FunctionTemplateDecl>(ND));
521 }
522};
523
524}
525
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000526static bool
527LookupMemberExprInRecord(Sema &SemaRef, LookupResult &R,
528 SourceRange BaseRange, const RecordType *RTy,
529 SourceLocation OpLoc, CXXScopeSpec &SS,
530 bool HasTemplateArgs) {
531 RecordDecl *RDecl = RTy->getDecl();
532 if (SemaRef.RequireCompleteType(OpLoc, QualType(RTy, 0),
533 SemaRef.PDiag(diag::err_typecheck_incomplete_tag)
534 << BaseRange))
535 return true;
536
537 if (HasTemplateArgs) {
538 // LookupTemplateName doesn't expect these both to exist simultaneously.
539 QualType ObjectType = SS.isSet() ? QualType() : QualType(RTy, 0);
540
541 bool MOUS;
542 SemaRef.LookupTemplateName(R, 0, SS, ObjectType, false, MOUS);
543 return false;
544 }
545
546 DeclContext *DC = RDecl;
547 if (SS.isSet()) {
548 // If the member name was a qualified-id, look into the
549 // nested-name-specifier.
550 DC = SemaRef.computeDeclContext(SS, false);
551
552 if (SemaRef.RequireCompleteDeclContext(SS, DC)) {
553 SemaRef.Diag(SS.getRange().getEnd(), diag::err_typecheck_incomplete_tag)
554 << SS.getRange() << DC;
555 return true;
556 }
557
558 assert(DC && "Cannot handle non-computable dependent contexts in lookup");
559
560 if (!isa<TypeDecl>(DC)) {
561 SemaRef.Diag(R.getNameLoc(), diag::err_qualified_member_nonclass)
562 << DC << SS.getRange();
563 return true;
564 }
565 }
566
567 // The record definition is complete, now look up the member.
568 SemaRef.LookupQualifiedName(R, DC);
569
570 if (!R.empty())
571 return false;
572
573 // We didn't find anything with the given name, so try to correct
574 // for typos.
575 DeclarationName Name = R.getLookupName();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000576 RecordMemberExprValidatorCCC Validator;
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000577 TypoCorrection Corrected = SemaRef.CorrectTypo(R.getLookupNameInfo(),
578 R.getLookupKind(), NULL,
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000579 &SS, &Validator, DC);
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000580 R.clear();
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +0000581 if (NamedDecl *ND = Corrected.getCorrectionDecl()) {
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000582 std::string CorrectedStr(
583 Corrected.getAsString(SemaRef.getLangOptions()));
584 std::string CorrectedQuotedStr(
585 Corrected.getQuoted(SemaRef.getLangOptions()));
586 R.setLookupName(Corrected.getCorrection());
587 R.addDecl(ND);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000588 SemaRef.Diag(R.getNameLoc(), diag::err_no_member_suggest)
Douglas Gregord8bba9c2011-06-28 16:20:02 +0000589 << Name << DC << CorrectedQuotedStr << SS.getRange()
590 << FixItHint::CreateReplacement(R.getNameLoc(), CorrectedStr);
591 SemaRef.Diag(ND->getLocation(), diag::note_previous_decl)
592 << ND->getDeclName();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000593 }
594
595 return false;
596}
597
598ExprResult
599Sema::BuildMemberReferenceExpr(Expr *Base, QualType BaseType,
600 SourceLocation OpLoc, bool IsArrow,
601 CXXScopeSpec &SS,
602 NamedDecl *FirstQualifierInScope,
603 const DeclarationNameInfo &NameInfo,
604 const TemplateArgumentListInfo *TemplateArgs) {
605 if (BaseType->isDependentType() ||
606 (SS.isSet() && isDependentScopeSpecifier(SS)))
607 return ActOnDependentMemberExpr(Base, BaseType,
608 IsArrow, OpLoc,
609 SS, FirstQualifierInScope,
610 NameInfo, TemplateArgs);
611
612 LookupResult R(*this, NameInfo, LookupMemberName);
613
614 // Implicit member accesses.
615 if (!Base) {
616 QualType RecordTy = BaseType;
617 if (IsArrow) RecordTy = RecordTy->getAs<PointerType>()->getPointeeType();
618 if (LookupMemberExprInRecord(*this, R, SourceRange(),
619 RecordTy->getAs<RecordType>(),
620 OpLoc, SS, TemplateArgs != 0))
621 return ExprError();
622
623 // Explicit member accesses.
624 } else {
625 ExprResult BaseResult = Owned(Base);
626 ExprResult Result =
627 LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
628 SS, /*ObjCImpDecl*/ 0, TemplateArgs != 0);
629
630 if (BaseResult.isInvalid())
631 return ExprError();
632 Base = BaseResult.take();
633
634 if (Result.isInvalid()) {
635 Owned(Base);
636 return ExprError();
637 }
638
639 if (Result.get())
640 return move(Result);
641
642 // LookupMemberExpr can modify Base, and thus change BaseType
643 BaseType = Base->getType();
644 }
645
646 return BuildMemberReferenceExpr(Base, BaseType,
647 OpLoc, IsArrow, SS, FirstQualifierInScope,
648 R, TemplateArgs);
649}
650
651static ExprResult
652BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
653 const CXXScopeSpec &SS, FieldDecl *Field,
654 DeclAccessPair FoundDecl,
655 const DeclarationNameInfo &MemberNameInfo);
656
657ExprResult
658Sema::BuildAnonymousStructUnionMemberReference(const CXXScopeSpec &SS,
659 SourceLocation loc,
660 IndirectFieldDecl *indirectField,
661 Expr *baseObjectExpr,
662 SourceLocation opLoc) {
663 // First, build the expression that refers to the base object.
664
665 bool baseObjectIsPointer = false;
666 Qualifiers baseQuals;
667
668 // Case 1: the base of the indirect field is not a field.
669 VarDecl *baseVariable = indirectField->getVarDecl();
670 CXXScopeSpec EmptySS;
671 if (baseVariable) {
672 assert(baseVariable->getType()->isRecordType());
673
674 // In principle we could have a member access expression that
675 // accesses an anonymous struct/union that's a static member of
676 // the base object's class. However, under the current standard,
677 // static data members cannot be anonymous structs or unions.
678 // Supporting this is as easy as building a MemberExpr here.
679 assert(!baseObjectExpr && "anonymous struct/union is static data member?");
680
681 DeclarationNameInfo baseNameInfo(DeclarationName(), loc);
682
683 ExprResult result
684 = BuildDeclarationNameExpr(EmptySS, baseNameInfo, baseVariable);
685 if (result.isInvalid()) return ExprError();
686
687 baseObjectExpr = result.take();
688 baseObjectIsPointer = false;
689 baseQuals = baseObjectExpr->getType().getQualifiers();
690
691 // Case 2: the base of the indirect field is a field and the user
692 // wrote a member expression.
693 } else if (baseObjectExpr) {
694 // The caller provided the base object expression. Determine
695 // whether its a pointer and whether it adds any qualifiers to the
696 // anonymous struct/union fields we're looking into.
697 QualType objectType = baseObjectExpr->getType();
698
699 if (const PointerType *ptr = objectType->getAs<PointerType>()) {
700 baseObjectIsPointer = true;
701 objectType = ptr->getPointeeType();
702 } else {
703 baseObjectIsPointer = false;
704 }
705 baseQuals = objectType.getQualifiers();
706
707 // Case 3: the base of the indirect field is a field and we should
708 // build an implicit member access.
709 } else {
710 // We've found a member of an anonymous struct/union that is
711 // inside a non-anonymous struct/union, so in a well-formed
712 // program our base object expression is "this".
Douglas Gregor341350e2011-10-18 16:47:30 +0000713 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000714 if (ThisTy.isNull()) {
715 Diag(loc, diag::err_invalid_member_use_in_static_method)
716 << indirectField->getDeclName();
717 return ExprError();
718 }
719
720 // Our base object expression is "this".
Eli Friedman72899c32012-01-07 04:59:52 +0000721 CheckCXXThisCapture(loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000722 baseObjectExpr
723 = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/ true);
724 baseObjectIsPointer = true;
725 baseQuals = ThisTy->castAs<PointerType>()->getPointeeType().getQualifiers();
726 }
727
728 // Build the implicit member references to the field of the
729 // anonymous struct/union.
730 Expr *result = baseObjectExpr;
731 IndirectFieldDecl::chain_iterator
732 FI = indirectField->chain_begin(), FEnd = indirectField->chain_end();
733
734 // Build the first member access in the chain with full information.
735 if (!baseVariable) {
736 FieldDecl *field = cast<FieldDecl>(*FI);
737
738 // FIXME: use the real found-decl info!
739 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
740
741 // Make a nameInfo that properly uses the anonymous name.
742 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
743
744 result = BuildFieldReferenceExpr(*this, result, baseObjectIsPointer,
745 EmptySS, field, foundDecl,
746 memberNameInfo).take();
747 baseObjectIsPointer = false;
748
749 // FIXME: check qualified member access
750 }
751
752 // In all cases, we should now skip the first declaration in the chain.
753 ++FI;
754
755 while (FI != FEnd) {
756 FieldDecl *field = cast<FieldDecl>(*FI++);
757
758 // FIXME: these are somewhat meaningless
759 DeclarationNameInfo memberNameInfo(field->getDeclName(), loc);
760 DeclAccessPair foundDecl = DeclAccessPair::make(field, field->getAccess());
761
762 result = BuildFieldReferenceExpr(*this, result, /*isarrow*/ false,
763 (FI == FEnd? SS : EmptySS), field,
764 foundDecl, memberNameInfo).take();
765 }
766
767 return Owned(result);
768}
769
770/// \brief Build a MemberExpr AST node.
771static MemberExpr *BuildMemberExpr(ASTContext &C, Expr *Base, bool isArrow,
772 const CXXScopeSpec &SS, ValueDecl *Member,
773 DeclAccessPair FoundDecl,
774 const DeclarationNameInfo &MemberNameInfo,
775 QualType Ty,
776 ExprValueKind VK, ExprObjectKind OK,
777 const TemplateArgumentListInfo *TemplateArgs = 0) {
Richard Smith4f870622011-10-27 22:11:44 +0000778 assert((!isArrow || Base->isRValue()) && "-> base must be a pointer rvalue");
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000779 return MemberExpr::Create(C, Base, isArrow, SS.getWithLocInContext(C),
780 Member, FoundDecl, MemberNameInfo,
781 TemplateArgs, Ty, VK, OK);
782}
783
784ExprResult
785Sema::BuildMemberReferenceExpr(Expr *BaseExpr, QualType BaseExprType,
786 SourceLocation OpLoc, bool IsArrow,
787 const CXXScopeSpec &SS,
788 NamedDecl *FirstQualifierInScope,
789 LookupResult &R,
790 const TemplateArgumentListInfo *TemplateArgs,
791 bool SuppressQualifierCheck) {
792 QualType BaseType = BaseExprType;
793 if (IsArrow) {
794 assert(BaseType->isPointerType());
John McCall3c3b7f92011-10-25 17:37:35 +0000795 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000796 }
797 R.setBaseObjectType(BaseType);
798
799 const DeclarationNameInfo &MemberNameInfo = R.getLookupNameInfo();
800 DeclarationName MemberName = MemberNameInfo.getName();
801 SourceLocation MemberLoc = MemberNameInfo.getLoc();
802
803 if (R.isAmbiguous())
804 return ExprError();
805
806 if (R.empty()) {
807 // Rederive where we looked up.
808 DeclContext *DC = (SS.isSet()
809 ? computeDeclContext(SS, false)
810 : BaseType->getAs<RecordType>()->getDecl());
811
812 Diag(R.getNameLoc(), diag::err_no_member)
813 << MemberName << DC
814 << (BaseExpr ? BaseExpr->getSourceRange() : SourceRange());
815 return ExprError();
816 }
817
818 // Diagnose lookups that find only declarations from a non-base
819 // type. This is possible for either qualified lookups (which may
820 // have been qualified with an unrelated type) or implicit member
821 // expressions (which were found with unqualified lookup and thus
822 // may have come from an enclosing scope). Note that it's okay for
823 // lookup to find declarations from a non-base type as long as those
824 // aren't the ones picked by overload resolution.
825 if ((SS.isSet() || !BaseExpr ||
826 (isa<CXXThisExpr>(BaseExpr) &&
827 cast<CXXThisExpr>(BaseExpr)->isImplicit())) &&
828 !SuppressQualifierCheck &&
829 CheckQualifiedMemberReference(BaseExpr, BaseType, SS, R))
830 return ExprError();
Fariborz Jahaniand1250502011-10-17 21:00:22 +0000831
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000832 // Construct an unresolved result if we in fact got an unresolved
833 // result.
834 if (R.isOverloadedResult() || R.isUnresolvableResult()) {
835 // Suppress any lookup-related diagnostics; we'll do these when we
836 // pick a member.
837 R.suppressDiagnostics();
838
839 UnresolvedMemberExpr *MemExpr
840 = UnresolvedMemberExpr::Create(Context, R.isUnresolvableResult(),
841 BaseExpr, BaseExprType,
842 IsArrow, OpLoc,
843 SS.getWithLocInContext(Context),
844 MemberNameInfo,
845 TemplateArgs, R.begin(), R.end());
846
847 return Owned(MemExpr);
848 }
849
850 assert(R.isSingleResult());
851 DeclAccessPair FoundDecl = R.begin().getPair();
852 NamedDecl *MemberDecl = R.getFoundDecl();
853
854 // FIXME: diagnose the presence of template arguments now.
855
856 // If the decl being referenced had an error, return an error for this
857 // sub-expr without emitting another error, in order to avoid cascading
858 // error cases.
859 if (MemberDecl->isInvalidDecl())
860 return ExprError();
861
862 // Handle the implicit-member-access case.
863 if (!BaseExpr) {
864 // If this is not an instance member, convert to a non-member access.
865 if (!MemberDecl->isCXXInstanceMember())
866 return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), MemberDecl);
867
868 SourceLocation Loc = R.getNameLoc();
869 if (SS.getRange().isValid())
870 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +0000871 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000872 BaseExpr = new (Context) CXXThisExpr(Loc, BaseExprType,/*isImplicit=*/true);
873 }
874
875 bool ShouldCheckUse = true;
876 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MemberDecl)) {
877 // Don't diagnose the use of a virtual member function unless it's
878 // explicitly qualified.
879 if (MD->isVirtual() && !SS.isSet())
880 ShouldCheckUse = false;
881 }
882
883 // Check the use of this member.
884 if (ShouldCheckUse && DiagnoseUseOfDecl(MemberDecl, MemberLoc)) {
885 Owned(BaseExpr);
886 return ExprError();
887 }
888
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000889 if (FieldDecl *FD = dyn_cast<FieldDecl>(MemberDecl))
890 return BuildFieldReferenceExpr(*this, BaseExpr, IsArrow,
891 SS, FD, FoundDecl, MemberNameInfo);
892
893 if (IndirectFieldDecl *FD = dyn_cast<IndirectFieldDecl>(MemberDecl))
894 // We may have found a field within an anonymous union or struct
895 // (C++ [class.union]).
896 return BuildAnonymousStructUnionMemberReference(SS, MemberLoc, FD,
897 BaseExpr, OpLoc);
898
899 if (VarDecl *Var = dyn_cast<VarDecl>(MemberDecl)) {
900 MarkDeclarationReferenced(MemberLoc, Var);
901 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
902 Var, FoundDecl, MemberNameInfo,
903 Var->getType().getNonReferenceType(),
904 VK_LValue, OK_Ordinary));
905 }
906
907 if (CXXMethodDecl *MemberFn = dyn_cast<CXXMethodDecl>(MemberDecl)) {
908 ExprValueKind valueKind;
909 QualType type;
910 if (MemberFn->isInstance()) {
911 valueKind = VK_RValue;
912 type = Context.BoundMemberTy;
913 } else {
914 valueKind = VK_LValue;
915 type = MemberFn->getType();
916 }
917
918 MarkDeclarationReferenced(MemberLoc, MemberDecl);
919 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
920 MemberFn, FoundDecl, MemberNameInfo,
921 type, valueKind, OK_Ordinary));
922 }
923 assert(!isa<FunctionDecl>(MemberDecl) && "member function not C++ method?");
924
925 if (EnumConstantDecl *Enum = dyn_cast<EnumConstantDecl>(MemberDecl)) {
926 MarkDeclarationReferenced(MemberLoc, MemberDecl);
927 return Owned(BuildMemberExpr(Context, BaseExpr, IsArrow, SS,
928 Enum, FoundDecl, MemberNameInfo,
929 Enum->getType(), VK_RValue, OK_Ordinary));
930 }
931
932 Owned(BaseExpr);
933
934 // We found something that we didn't expect. Complain.
935 if (isa<TypeDecl>(MemberDecl))
936 Diag(MemberLoc, diag::err_typecheck_member_reference_type)
937 << MemberName << BaseType << int(IsArrow);
938 else
939 Diag(MemberLoc, diag::err_typecheck_member_reference_unknown)
940 << MemberName << BaseType << int(IsArrow);
941
942 Diag(MemberDecl->getLocation(), diag::note_member_declared_here)
943 << MemberName;
944 R.suppressDiagnostics();
945 return ExprError();
946}
947
948/// Given that normal member access failed on the given expression,
949/// and given that the expression's type involves builtin-id or
950/// builtin-Class, decide whether substituting in the redefinition
951/// types would be profitable. The redefinition type is whatever
952/// this translation unit tried to typedef to id/Class; we store
953/// it to the side and then re-use it in places like this.
954static bool ShouldTryAgainWithRedefinitionType(Sema &S, ExprResult &base) {
955 const ObjCObjectPointerType *opty
956 = base.get()->getType()->getAs<ObjCObjectPointerType>();
957 if (!opty) return false;
958
959 const ObjCObjectType *ty = opty->getObjectType();
960
961 QualType redef;
962 if (ty->isObjCId()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000963 redef = S.Context.getObjCIdRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000964 } else if (ty->isObjCClass()) {
Douglas Gregor01a4cf12011-08-11 20:58:55 +0000965 redef = S.Context.getObjCClassRedefinitionType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000966 } else {
967 return false;
968 }
969
970 // Do the substitution as long as the redefinition type isn't just a
971 // possibly-qualified pointer to builtin-id or builtin-Class again.
972 opty = redef->getAs<ObjCObjectPointerType>();
973 if (opty && !opty->getObjectType()->getInterface() != 0)
974 return false;
975
976 base = S.ImpCastExprToType(base.take(), redef, CK_BitCast);
977 return true;
978}
979
John McCall6dbba4f2011-10-11 23:14:30 +0000980static bool isRecordType(QualType T) {
981 return T->isRecordType();
982}
983static bool isPointerToRecordType(QualType T) {
984 if (const PointerType *PT = T->getAs<PointerType>())
985 return PT->getPointeeType()->isRecordType();
986 return false;
987}
988
Richard Smith9138b4e2011-10-26 19:06:56 +0000989/// Perform conversions on the LHS of a member access expression.
990ExprResult
991Sema::PerformMemberExprBaseConversion(Expr *Base, bool IsArrow) {
Eli Friedman059d5782012-01-13 02:20:01 +0000992 if (IsArrow && !Base->getType()->isFunctionType())
993 return DefaultFunctionArrayLvalueConversion(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +0000994
Eli Friedman059d5782012-01-13 02:20:01 +0000995 return CheckPlaceholderExpr(Base);
Richard Smith9138b4e2011-10-26 19:06:56 +0000996}
997
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +0000998/// Look up the given member of the given non-type-dependent
999/// expression. This can return in one of two ways:
1000/// * If it returns a sentinel null-but-valid result, the caller will
1001/// assume that lookup was performed and the results written into
1002/// the provided structure. It will take over from there.
1003/// * Otherwise, the returned expression will be produced in place of
1004/// an ordinary member expression.
1005///
1006/// The ObjCImpDecl bit is a gross hack that will need to be properly
1007/// fixed for ObjC++.
1008ExprResult
1009Sema::LookupMemberExpr(LookupResult &R, ExprResult &BaseExpr,
1010 bool &IsArrow, SourceLocation OpLoc,
1011 CXXScopeSpec &SS,
1012 Decl *ObjCImpDecl, bool HasTemplateArgs) {
1013 assert(BaseExpr.get() && "no base expression");
1014
1015 // Perform default conversions.
Richard Smith9138b4e2011-10-26 19:06:56 +00001016 BaseExpr = PerformMemberExprBaseConversion(BaseExpr.take(), IsArrow);
John McCall6dbba4f2011-10-11 23:14:30 +00001017 if (BaseExpr.isInvalid())
1018 return ExprError();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001019
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001020 QualType BaseType = BaseExpr.get()->getType();
1021 assert(!BaseType->isDependentType());
1022
1023 DeclarationName MemberName = R.getLookupName();
1024 SourceLocation MemberLoc = R.getNameLoc();
1025
1026 // For later type-checking purposes, turn arrow accesses into dot
1027 // accesses. The only access type we support that doesn't follow
1028 // the C equivalence "a->b === (*a).b" is ObjC property accesses,
1029 // and those never use arrows, so this is unaffected.
1030 if (IsArrow) {
1031 if (const PointerType *Ptr = BaseType->getAs<PointerType>())
1032 BaseType = Ptr->getPointeeType();
1033 else if (const ObjCObjectPointerType *Ptr
1034 = BaseType->getAs<ObjCObjectPointerType>())
1035 BaseType = Ptr->getPointeeType();
1036 else if (BaseType->isRecordType()) {
1037 // Recover from arrow accesses to records, e.g.:
1038 // struct MyRecord foo;
1039 // foo->bar
1040 // This is actually well-formed in C++ if MyRecord has an
1041 // overloaded operator->, but that should have been dealt with
1042 // by now.
1043 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1044 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1045 << FixItHint::CreateReplacement(OpLoc, ".");
1046 IsArrow = false;
Eli Friedman059d5782012-01-13 02:20:01 +00001047 } else if (BaseType->isFunctionType()) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001048 goto fail;
1049 } else {
1050 Diag(MemberLoc, diag::err_typecheck_member_reference_arrow)
1051 << BaseType << BaseExpr.get()->getSourceRange();
1052 return ExprError();
1053 }
1054 }
1055
1056 // Handle field access to simple records.
1057 if (const RecordType *RTy = BaseType->getAs<RecordType>()) {
1058 if (LookupMemberExprInRecord(*this, R, BaseExpr.get()->getSourceRange(),
1059 RTy, OpLoc, SS, HasTemplateArgs))
1060 return ExprError();
1061
1062 // Returning valid-but-null is how we indicate to the caller that
1063 // the lookup result was filled in.
1064 return Owned((Expr*) 0);
1065 }
1066
1067 // Handle ivar access to Objective-C objects.
1068 if (const ObjCObjectType *OTy = BaseType->getAs<ObjCObjectType>()) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001069 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001070 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1071 << 1 << SS.getScopeRep()
1072 << FixItHint::CreateRemoval(SS.getRange());
1073 SS.clear();
1074 }
1075
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001076 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1077
1078 // There are three cases for the base type:
1079 // - builtin id (qualified or unqualified)
1080 // - builtin Class (qualified or unqualified)
1081 // - an interface
1082 ObjCInterfaceDecl *IDecl = OTy->getInterface();
1083 if (!IDecl) {
1084 if (getLangOptions().ObjCAutoRefCount &&
1085 (OTy->isObjCId() || OTy->isObjCClass()))
1086 goto fail;
1087 // There's an implicit 'isa' ivar on all objects.
1088 // But we only actually find it this way on objects of type 'id',
1089 // apparently.
1090 if (OTy->isObjCId() && Member->isStr("isa"))
1091 return Owned(new (Context) ObjCIsaExpr(BaseExpr.take(), IsArrow, MemberLoc,
1092 Context.getObjCClassType()));
1093
1094 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1095 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1096 ObjCImpDecl, HasTemplateArgs);
1097 goto fail;
1098 }
1099
Douglas Gregord07cc362012-01-02 17:18:37 +00001100 if (RequireCompleteType(OpLoc, BaseType,
1101 PDiag(diag::err_typecheck_incomplete_tag)
1102 << BaseExpr.get()->getSourceRange()))
1103 return ExprError();
1104
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001105 ObjCInterfaceDecl *ClassDeclared;
1106 ObjCIvarDecl *IV = IDecl->lookupInstanceVariable(Member, ClassDeclared);
1107
1108 if (!IV) {
1109 // Attempt to correct for typos in ivar names.
Kaelyn Uhraine4c7f902012-01-13 21:28:55 +00001110 DeclFilterCCC<ObjCIvarDecl> Validator;
1111 Validator.IsObjCIvarLookup = IsArrow;
1112 if (TypoCorrection Corrected = CorrectTypo(R.getLookupNameInfo(),
1113 LookupMemberName, NULL, NULL,
1114 &Validator, IDecl)) {
1115 IV = Corrected.getCorrectionDeclAs<ObjCIvarDecl>();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001116 Diag(R.getNameLoc(),
1117 diag::err_typecheck_member_reference_ivar_suggest)
1118 << IDecl->getDeclName() << MemberName << IV->getDeclName()
1119 << FixItHint::CreateReplacement(R.getNameLoc(),
1120 IV->getNameAsString());
1121 Diag(IV->getLocation(), diag::note_previous_decl)
1122 << IV->getDeclName();
1123 } else {
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001124 if (IsArrow && IDecl->FindPropertyDeclaration(Member)) {
1125 Diag(MemberLoc,
1126 diag::err_property_found_suggest)
1127 << Member << BaseExpr.get()->getType()
1128 << FixItHint::CreateReplacement(OpLoc, ".");
1129 return ExprError();
1130 }
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001131
1132 Diag(MemberLoc, diag::err_typecheck_member_reference_ivar)
1133 << IDecl->getDeclName() << MemberName
1134 << BaseExpr.get()->getSourceRange();
1135 return ExprError();
1136 }
1137 }
1138
1139 // If the decl being referenced had an error, return an error for this
1140 // sub-expr without emitting another error, in order to avoid cascading
1141 // error cases.
1142 if (IV->isInvalidDecl())
1143 return ExprError();
1144
1145 // Check whether we can reference this field.
1146 if (DiagnoseUseOfDecl(IV, MemberLoc))
1147 return ExprError();
1148 if (IV->getAccessControl() != ObjCIvarDecl::Public &&
1149 IV->getAccessControl() != ObjCIvarDecl::Package) {
1150 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1151 if (ObjCMethodDecl *MD = getCurMethodDecl())
1152 ClassOfMethodDecl = MD->getClassInterface();
1153 else if (ObjCImpDecl && getCurFunctionDecl()) {
1154 // Case of a c-function declared inside an objc implementation.
1155 // FIXME: For a c-style function nested inside an objc implementation
1156 // class, there is no implementation context available, so we pass
1157 // down the context as argument to this routine. Ideally, this context
1158 // need be passed down in the AST node and somehow calculated from the
1159 // AST for a function decl.
1160 if (ObjCImplementationDecl *IMPD =
1161 dyn_cast<ObjCImplementationDecl>(ObjCImpDecl))
1162 ClassOfMethodDecl = IMPD->getClassInterface();
1163 else if (ObjCCategoryImplDecl* CatImplClass =
1164 dyn_cast<ObjCCategoryImplDecl>(ObjCImpDecl))
1165 ClassOfMethodDecl = CatImplClass->getClassInterface();
1166 }
1167
1168 if (IV->getAccessControl() == ObjCIvarDecl::Private) {
Douglas Gregor60ef3082011-12-15 00:29:59 +00001169 if (!declaresSameEntity(ClassDeclared, IDecl) ||
1170 !declaresSameEntity(ClassOfMethodDecl, ClassDeclared))
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001171 Diag(MemberLoc, diag::error_private_ivar_access)
1172 << IV->getDeclName();
1173 } else if (!IDecl->isSuperClassOf(ClassOfMethodDecl))
1174 // @protected
1175 Diag(MemberLoc, diag::error_protected_ivar_access)
1176 << IV->getDeclName();
1177 }
1178 if (getLangOptions().ObjCAutoRefCount) {
1179 Expr *BaseExp = BaseExpr.get()->IgnoreParenImpCasts();
1180 if (UnaryOperator *UO = dyn_cast<UnaryOperator>(BaseExp))
1181 if (UO->getOpcode() == UO_Deref)
1182 BaseExp = UO->getSubExpr()->IgnoreParenCasts();
1183
1184 if (DeclRefExpr *DE = dyn_cast<DeclRefExpr>(BaseExp))
1185 if (DE->getType().getObjCLifetime() == Qualifiers::OCL_Weak)
1186 Diag(DE->getLocation(), diag::error_arc_weak_ivar_access);
1187 }
1188
1189 return Owned(new (Context) ObjCIvarRefExpr(IV, IV->getType(),
1190 MemberLoc, BaseExpr.take(),
1191 IsArrow));
1192 }
1193
1194 // Objective-C property access.
1195 const ObjCObjectPointerType *OPT;
1196 if (!IsArrow && (OPT = BaseType->getAs<ObjCObjectPointerType>())) {
Douglas Gregor5a706dc2011-10-10 16:09:49 +00001197 if (!SS.isEmpty() && !SS.isInvalid()) {
Douglas Gregorb5ae92f2011-10-09 23:22:49 +00001198 Diag(SS.getRange().getBegin(), diag::err_qualified_objc_access)
1199 << 0 << SS.getScopeRep()
1200 << FixItHint::CreateRemoval(SS.getRange());
1201 SS.clear();
1202 }
1203
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001204 // This actually uses the base as an r-value.
1205 BaseExpr = DefaultLvalueConversion(BaseExpr.take());
1206 if (BaseExpr.isInvalid())
1207 return ExprError();
1208
1209 assert(Context.hasSameUnqualifiedType(BaseType, BaseExpr.get()->getType()));
1210
1211 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1212
1213 const ObjCObjectType *OT = OPT->getObjectType();
1214
1215 // id, with and without qualifiers.
1216 if (OT->isObjCId()) {
1217 // Check protocols on qualified interfaces.
1218 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1219 if (Decl *PMDecl = FindGetterSetterNameDecl(OPT, Member, Sel, Context)) {
1220 if (ObjCPropertyDecl *PD = dyn_cast<ObjCPropertyDecl>(PMDecl)) {
1221 // Check the use of this declaration
1222 if (DiagnoseUseOfDecl(PD, MemberLoc))
1223 return ExprError();
1224
John McCall3c3b7f92011-10-25 17:37:35 +00001225 return Owned(new (Context) ObjCPropertyRefExpr(PD,
1226 Context.PseudoObjectTy,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001227 VK_LValue,
1228 OK_ObjCProperty,
1229 MemberLoc,
1230 BaseExpr.take()));
1231 }
1232
1233 if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(PMDecl)) {
1234 // Check the use of this method.
1235 if (DiagnoseUseOfDecl(OMD, MemberLoc))
1236 return ExprError();
1237 Selector SetterSel =
1238 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1239 PP.getSelectorTable(), Member);
1240 ObjCMethodDecl *SMD = 0;
1241 if (Decl *SDecl = FindGetterSetterNameDecl(OPT, /*Property id*/0,
1242 SetterSel, Context))
1243 SMD = dyn_cast<ObjCMethodDecl>(SDecl);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001244
John McCall3c3b7f92011-10-25 17:37:35 +00001245 return Owned(new (Context) ObjCPropertyRefExpr(OMD, SMD,
1246 Context.PseudoObjectTy,
1247 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001248 MemberLoc, BaseExpr.take()));
1249 }
1250 }
1251 // Use of id.member can only be for a property reference. Do not
1252 // use the 'id' redefinition in this case.
1253 if (IsArrow && ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1254 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1255 ObjCImpDecl, HasTemplateArgs);
1256
1257 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1258 << MemberName << BaseType);
1259 }
1260
1261 // 'Class', unqualified only.
1262 if (OT->isObjCClass()) {
1263 // Only works in a method declaration (??!).
1264 ObjCMethodDecl *MD = getCurMethodDecl();
1265 if (!MD) {
1266 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1267 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1268 ObjCImpDecl, HasTemplateArgs);
1269
1270 goto fail;
1271 }
1272
1273 // Also must look for a getter name which uses property syntax.
1274 Selector Sel = PP.getSelectorTable().getNullarySelector(Member);
1275 ObjCInterfaceDecl *IFace = MD->getClassInterface();
1276 ObjCMethodDecl *Getter;
1277 if ((Getter = IFace->lookupClassMethod(Sel))) {
1278 // Check the use of this method.
1279 if (DiagnoseUseOfDecl(Getter, MemberLoc))
1280 return ExprError();
1281 } else
1282 Getter = IFace->lookupPrivateMethod(Sel, false);
1283 // If we found a getter then this may be a valid dot-reference, we
1284 // will look for the matching setter, in case it is needed.
1285 Selector SetterSel =
1286 SelectorTable::constructSetterName(PP.getIdentifierTable(),
1287 PP.getSelectorTable(), Member);
1288 ObjCMethodDecl *Setter = IFace->lookupClassMethod(SetterSel);
1289 if (!Setter) {
1290 // If this reference is in an @implementation, also check for 'private'
1291 // methods.
1292 Setter = IFace->lookupPrivateMethod(SetterSel, false);
1293 }
1294 // Look through local category implementations associated with the class.
1295 if (!Setter)
1296 Setter = IFace->getCategoryClassMethod(SetterSel);
1297
1298 if (Setter && DiagnoseUseOfDecl(Setter, MemberLoc))
1299 return ExprError();
1300
1301 if (Getter || Setter) {
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001302 return Owned(new (Context) ObjCPropertyRefExpr(Getter, Setter,
John McCall3c3b7f92011-10-25 17:37:35 +00001303 Context.PseudoObjectTy,
1304 VK_LValue, OK_ObjCProperty,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001305 MemberLoc, BaseExpr.take()));
1306 }
1307
1308 if (ShouldTryAgainWithRedefinitionType(*this, BaseExpr))
1309 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1310 ObjCImpDecl, HasTemplateArgs);
1311
1312 return ExprError(Diag(MemberLoc, diag::err_property_not_found)
1313 << MemberName << BaseType);
1314 }
1315
1316 // Normal property access.
Fariborz Jahanian6326e052011-06-28 00:00:52 +00001317 return HandleExprPropertyRefExpr(OPT, BaseExpr.get(), OpLoc,
1318 MemberName, MemberLoc,
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001319 SourceLocation(), QualType(), false);
1320 }
1321
1322 // Handle 'field access' to vectors, such as 'V.xx'.
1323 if (BaseType->isExtVectorType()) {
1324 // FIXME: this expr should store IsArrow.
1325 IdentifierInfo *Member = MemberName.getAsIdentifierInfo();
1326 ExprValueKind VK = (IsArrow ? VK_LValue : BaseExpr.get()->getValueKind());
1327 QualType ret = CheckExtVectorComponent(*this, BaseType, VK, OpLoc,
1328 Member, MemberLoc);
1329 if (ret.isNull())
1330 return ExprError();
1331
1332 return Owned(new (Context) ExtVectorElementExpr(ret, VK, BaseExpr.take(),
1333 *Member, MemberLoc));
1334 }
1335
1336 // Adjust builtin-sel to the appropriate redefinition type if that's
1337 // not just a pointer to builtin-sel again.
1338 if (IsArrow &&
1339 BaseType->isSpecificBuiltinType(BuiltinType::ObjCSel) &&
Douglas Gregor01a4cf12011-08-11 20:58:55 +00001340 !Context.getObjCSelRedefinitionType()->isObjCSelType()) {
1341 BaseExpr = ImpCastExprToType(BaseExpr.take(),
1342 Context.getObjCSelRedefinitionType(),
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001343 CK_BitCast);
1344 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1345 ObjCImpDecl, HasTemplateArgs);
1346 }
1347
1348 // Failure cases.
1349 fail:
1350
1351 // Recover from dot accesses to pointers, e.g.:
1352 // type *foo;
1353 // foo.bar
1354 // This is actually well-formed in two cases:
1355 // - 'type' is an Objective C type
1356 // - 'bar' is a pseudo-destructor name which happens to refer to
1357 // the appropriate pointer type
1358 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
1359 if (!IsArrow && Ptr->getPointeeType()->isRecordType() &&
1360 MemberName.getNameKind() != DeclarationName::CXXDestructorName) {
1361 Diag(OpLoc, diag::err_typecheck_member_reference_suggestion)
1362 << BaseType << int(IsArrow) << BaseExpr.get()->getSourceRange()
1363 << FixItHint::CreateReplacement(OpLoc, "->");
1364
1365 // Recurse as an -> access.
1366 IsArrow = true;
1367 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1368 ObjCImpDecl, HasTemplateArgs);
1369 }
1370 }
1371
1372 // If the user is trying to apply -> or . to a function name, it's probably
1373 // because they forgot parentheses to call that function.
John McCall6dbba4f2011-10-11 23:14:30 +00001374 if (tryToRecoverWithCall(BaseExpr,
1375 PDiag(diag::err_member_reference_needs_call),
1376 /*complain*/ false,
Eli Friedman059d5782012-01-13 02:20:01 +00001377 IsArrow ? &isPointerToRecordType : &isRecordType)) {
John McCall6dbba4f2011-10-11 23:14:30 +00001378 if (BaseExpr.isInvalid())
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001379 return ExprError();
John McCall6dbba4f2011-10-11 23:14:30 +00001380 BaseExpr = DefaultFunctionArrayConversion(BaseExpr.take());
1381 return LookupMemberExpr(R, BaseExpr, IsArrow, OpLoc, SS,
1382 ObjCImpDecl, HasTemplateArgs);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001383 }
1384
1385 Diag(MemberLoc, diag::err_typecheck_member_reference_struct_union)
1386 << BaseType << BaseExpr.get()->getSourceRange();
1387
1388 return ExprError();
1389}
1390
1391/// The main callback when the parser finds something like
1392/// expression . [nested-name-specifier] identifier
1393/// expression -> [nested-name-specifier] identifier
1394/// where 'identifier' encompasses a fairly broad spectrum of
1395/// possibilities, including destructor and operator references.
1396///
1397/// \param OpKind either tok::arrow or tok::period
1398/// \param HasTrailingLParen whether the next token is '(', which
1399/// is used to diagnose mis-uses of special members that can
1400/// only be called
1401/// \param ObjCImpDecl the current ObjC @implementation decl;
1402/// this is an ugly hack around the fact that ObjC @implementations
1403/// aren't properly put in the context chain
1404ExprResult Sema::ActOnMemberAccessExpr(Scope *S, Expr *Base,
1405 SourceLocation OpLoc,
1406 tok::TokenKind OpKind,
1407 CXXScopeSpec &SS,
1408 UnqualifiedId &Id,
1409 Decl *ObjCImpDecl,
1410 bool HasTrailingLParen) {
1411 if (SS.isSet() && SS.isInvalid())
1412 return ExprError();
1413
1414 // Warn about the explicit constructor calls Microsoft extension.
Francois Pichet62ec1f22011-09-17 17:15:52 +00001415 if (getLangOptions().MicrosoftExt &&
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001416 Id.getKind() == UnqualifiedId::IK_ConstructorName)
1417 Diag(Id.getSourceRange().getBegin(),
1418 diag::ext_ms_explicit_constructor_call);
1419
1420 TemplateArgumentListInfo TemplateArgsBuffer;
1421
1422 // Decompose the name into its component parts.
1423 DeclarationNameInfo NameInfo;
1424 const TemplateArgumentListInfo *TemplateArgs;
1425 DecomposeUnqualifiedId(Id, TemplateArgsBuffer,
1426 NameInfo, TemplateArgs);
1427
1428 DeclarationName Name = NameInfo.getName();
1429 bool IsArrow = (OpKind == tok::arrow);
1430
1431 NamedDecl *FirstQualifierInScope
1432 = (!SS.isSet() ? 0 : FindFirstQualifierInScope(S,
1433 static_cast<NestedNameSpecifier*>(SS.getScopeRep())));
1434
1435 // This is a postfix expression, so get rid of ParenListExprs.
1436 ExprResult Result = MaybeConvertParenListExprToParenExpr(S, Base);
1437 if (Result.isInvalid()) return ExprError();
1438 Base = Result.take();
1439
1440 if (Base->getType()->isDependentType() || Name.isDependentName() ||
1441 isDependentScopeSpecifier(SS)) {
1442 Result = ActOnDependentMemberExpr(Base, Base->getType(),
1443 IsArrow, OpLoc,
1444 SS, FirstQualifierInScope,
1445 NameInfo, TemplateArgs);
1446 } else {
1447 LookupResult R(*this, NameInfo, LookupMemberName);
1448 ExprResult BaseResult = Owned(Base);
1449 Result = LookupMemberExpr(R, BaseResult, IsArrow, OpLoc,
1450 SS, ObjCImpDecl, TemplateArgs != 0);
1451 if (BaseResult.isInvalid())
1452 return ExprError();
1453 Base = BaseResult.take();
1454
1455 if (Result.isInvalid()) {
1456 Owned(Base);
1457 return ExprError();
1458 }
1459
1460 if (Result.get()) {
1461 // The only way a reference to a destructor can be used is to
1462 // immediately call it, which falls into this case. If the
1463 // next token is not a '(', produce a diagnostic and build the
1464 // call now.
1465 if (!HasTrailingLParen &&
1466 Id.getKind() == UnqualifiedId::IK_DestructorName)
1467 return DiagnoseDtorReference(NameInfo.getLoc(), Result.get());
1468
1469 return move(Result);
1470 }
1471
1472 Result = BuildMemberReferenceExpr(Base, Base->getType(),
1473 OpLoc, IsArrow, SS, FirstQualifierInScope,
1474 R, TemplateArgs);
1475 }
1476
1477 return move(Result);
1478}
1479
1480static ExprResult
1481BuildFieldReferenceExpr(Sema &S, Expr *BaseExpr, bool IsArrow,
1482 const CXXScopeSpec &SS, FieldDecl *Field,
1483 DeclAccessPair FoundDecl,
1484 const DeclarationNameInfo &MemberNameInfo) {
1485 // x.a is an l-value if 'a' has a reference type. Otherwise:
1486 // x.a is an l-value/x-value/pr-value if the base is (and note
1487 // that *x is always an l-value), except that if the base isn't
1488 // an ordinary object then we must have an rvalue.
1489 ExprValueKind VK = VK_LValue;
1490 ExprObjectKind OK = OK_Ordinary;
1491 if (!IsArrow) {
1492 if (BaseExpr->getObjectKind() == OK_Ordinary)
1493 VK = BaseExpr->getValueKind();
1494 else
1495 VK = VK_RValue;
1496 }
1497 if (VK != VK_RValue && Field->isBitField())
1498 OK = OK_BitField;
1499
1500 // Figure out the type of the member; see C99 6.5.2.3p3, C++ [expr.ref]
1501 QualType MemberType = Field->getType();
1502 if (const ReferenceType *Ref = MemberType->getAs<ReferenceType>()) {
1503 MemberType = Ref->getPointeeType();
1504 VK = VK_LValue;
1505 } else {
1506 QualType BaseType = BaseExpr->getType();
1507 if (IsArrow) BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1508
1509 Qualifiers BaseQuals = BaseType.getQualifiers();
1510
1511 // GC attributes are never picked up by members.
1512 BaseQuals.removeObjCGCAttr();
1513
1514 // CVR attributes from the base are picked up by members,
1515 // except that 'mutable' members don't pick up 'const'.
1516 if (Field->isMutable()) BaseQuals.removeConst();
1517
1518 Qualifiers MemberQuals
1519 = S.Context.getCanonicalType(MemberType).getQualifiers();
1520
1521 // TR 18037 does not allow fields to be declared with address spaces.
1522 assert(!MemberQuals.hasAddressSpace());
1523
1524 Qualifiers Combined = BaseQuals + MemberQuals;
1525 if (Combined != MemberQuals)
1526 MemberType = S.Context.getQualifiedType(MemberType, Combined);
1527 }
1528
1529 S.MarkDeclarationReferenced(MemberNameInfo.getLoc(), Field);
1530 ExprResult Base =
1531 S.PerformObjectMemberConversion(BaseExpr, SS.getScopeRep(),
1532 FoundDecl, Field);
1533 if (Base.isInvalid())
1534 return ExprError();
1535 return S.Owned(BuildMemberExpr(S.Context, Base.take(), IsArrow, SS,
1536 Field, FoundDecl, MemberNameInfo,
1537 MemberType, VK, OK));
1538}
1539
1540/// Builds an implicit member access expression. The current context
1541/// is known to be an instance method, and the given unqualified lookup
1542/// set is known to contain only instance members, at least one of which
1543/// is from an appropriate type.
1544ExprResult
1545Sema::BuildImplicitMemberExpr(const CXXScopeSpec &SS,
1546 LookupResult &R,
1547 const TemplateArgumentListInfo *TemplateArgs,
1548 bool IsKnownInstance) {
1549 assert(!R.empty() && !R.isAmbiguous());
1550
1551 SourceLocation loc = R.getNameLoc();
1552
1553 // We may have found a field within an anonymous union or struct
1554 // (C++ [class.union]).
1555 // FIXME: template-ids inside anonymous structs?
1556 if (IndirectFieldDecl *FD = R.getAsSingle<IndirectFieldDecl>())
1557 return BuildAnonymousStructUnionMemberReference(SS, R.getNameLoc(), FD);
1558
1559 // If this is known to be an instance access, go ahead and build an
1560 // implicit 'this' expression now.
1561 // 'this' expression now.
Douglas Gregor341350e2011-10-18 16:47:30 +00001562 QualType ThisTy = getCurrentThisType();
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001563 assert(!ThisTy.isNull() && "didn't correctly pre-flight capture of 'this'");
1564
1565 Expr *baseExpr = 0; // null signifies implicit access
1566 if (IsKnownInstance) {
1567 SourceLocation Loc = R.getNameLoc();
1568 if (SS.getRange().isValid())
1569 Loc = SS.getRange().getBegin();
Eli Friedman72899c32012-01-07 04:59:52 +00001570 CheckCXXThisCapture(Loc);
Douglas Gregor2b1ad8b2011-06-23 00:49:38 +00001571 baseExpr = new (Context) CXXThisExpr(loc, ThisTy, /*isImplicit=*/true);
1572 }
1573
1574 return BuildMemberReferenceExpr(baseExpr, ThisTy,
1575 /*OpLoc*/ SourceLocation(),
1576 /*IsArrow*/ true,
1577 SS,
1578 /*FirstQualifierInScope*/ 0,
1579 R, TemplateArgs);
1580}