blob: 57d5e43f96844dd05241ef4d91f5aa14f9cd5f0f [file] [log] [blame]
Anders Carlsson29f006b2009-03-27 05:05:05 +00001//===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
Anders Carlsson60d6b0d2009-03-27 04:43:36 +00002//
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 provides Sema routines for C++ access control semantics.
11//
12//===----------------------------------------------------------------------===//
Anders Carlssonc60e8882009-03-27 04:54:36 +000013
John McCall2d887082010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
John McCall9c3087b2010-08-26 02:13:20 +000015#include "clang/Sema/DelayedDiagnostic.h"
Douglas Gregore737f502010-08-12 20:07:10 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Anders Carlssonc4f1e872009-03-27 06:03:27 +000018#include "clang/AST/ASTContext.h"
Douglas Gregora8f32e02009-10-06 17:59:45 +000019#include "clang/AST/CXXInheritance.h"
20#include "clang/AST/DeclCXX.h"
John McCalld60e22e2010-03-12 01:19:31 +000021#include "clang/AST/DeclFriend.h"
Douglas Gregorf3c02862011-11-03 19:00:24 +000022#include "clang/AST/DeclObjC.h"
John McCall0c01d182010-03-24 05:22:00 +000023#include "clang/AST/DependentDiagnostic.h"
John McCallc373d482010-01-27 01:50:18 +000024#include "clang/AST/ExprCXX.h"
25
Anders Carlssonc60e8882009-03-27 04:54:36 +000026using namespace clang;
John McCall9c3087b2010-08-26 02:13:20 +000027using namespace sema;
Anders Carlssonc60e8882009-03-27 04:54:36 +000028
John McCall161755a2010-04-06 21:38:20 +000029/// A copy of Sema's enum without AR_delayed.
30enum AccessResult {
31 AR_accessible,
32 AR_inaccessible,
33 AR_dependent
34};
35
Anders Carlsson29f006b2009-03-27 05:05:05 +000036/// SetMemberAccessSpecifier - Set the access specifier of a member.
37/// Returns true on error (when the previous member decl access specifier
38/// is different from the new member decl access specifier).
Mike Stump1eb44332009-09-09 15:08:12 +000039bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
Anders Carlssonc60e8882009-03-27 04:54:36 +000040 NamedDecl *PrevMemberDecl,
41 AccessSpecifier LexicalAS) {
42 if (!PrevMemberDecl) {
43 // Use the lexical access specifier.
44 MemberDecl->setAccess(LexicalAS);
45 return false;
46 }
Mike Stump1eb44332009-09-09 15:08:12 +000047
Anders Carlssonc60e8882009-03-27 04:54:36 +000048 // C++ [class.access.spec]p3: When a member is redeclared its access
49 // specifier must be same as its initial declaration.
50 if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) {
Mike Stump1eb44332009-09-09 15:08:12 +000051 Diag(MemberDecl->getLocation(),
52 diag::err_class_redeclared_with_different_access)
Anders Carlssonc60e8882009-03-27 04:54:36 +000053 << MemberDecl << LexicalAS;
54 Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
55 << PrevMemberDecl << PrevMemberDecl->getAccess();
John McCall44e067b2009-12-23 00:37:40 +000056
57 MemberDecl->setAccess(LexicalAS);
Anders Carlssonc60e8882009-03-27 04:54:36 +000058 return true;
59 }
Mike Stump1eb44332009-09-09 15:08:12 +000060
Anders Carlssonc60e8882009-03-27 04:54:36 +000061 MemberDecl->setAccess(PrevMemberDecl->getAccess());
62 return false;
63}
Anders Carlsson29f006b2009-03-27 05:05:05 +000064
John McCall161755a2010-04-06 21:38:20 +000065static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
66 DeclContext *DC = D->getDeclContext();
67
68 // This can only happen at top: enum decls only "publish" their
69 // immediate members.
70 if (isa<EnumDecl>(DC))
71 DC = cast<EnumDecl>(DC)->getDeclContext();
72
73 CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
74 while (DeclaringClass->isAnonymousStructOrUnion())
75 DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
76 return DeclaringClass;
77}
78
John McCall6b2accb2010-02-10 09:31:12 +000079namespace {
80struct EffectiveContext {
John McCall2cc26752010-03-27 06:55:49 +000081 EffectiveContext() : Inner(0), Dependent(false) {}
Anders Carlssonc4f1e872009-03-27 06:03:27 +000082
John McCall7ad650f2010-03-24 07:46:06 +000083 explicit EffectiveContext(DeclContext *DC)
84 : Inner(DC),
85 Dependent(DC->isDependentContext()) {
John McCall0c01d182010-03-24 05:22:00 +000086
John McCall88b6c712010-03-17 04:58:56 +000087 // C++ [class.access.nest]p1:
88 // A nested class is a member and as such has the same access
89 // rights as any other member.
90 // C++ [class.access]p2:
91 // A member of a class can also access all the names to which
John McCall2cc26752010-03-27 06:55:49 +000092 // the class has access. A local class of a member function
93 // may access the same names that the member function itself
94 // may access.
95 // This almost implies that the privileges of nesting are transitive.
96 // Technically it says nothing about the local classes of non-member
97 // functions (which can gain privileges through friendship), but we
98 // take that as an oversight.
99 while (true) {
100 if (isa<CXXRecordDecl>(DC)) {
101 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC)->getCanonicalDecl();
102 Records.push_back(Record);
103 DC = Record->getDeclContext();
104 } else if (isa<FunctionDecl>(DC)) {
105 FunctionDecl *Function = cast<FunctionDecl>(DC)->getCanonicalDecl();
106 Functions.push_back(Function);
Douglas Gregorac57f0b2011-10-09 22:38:36 +0000107
108 if (Function->getFriendObjectKind())
109 DC = Function->getLexicalDeclContext();
110 else
111 DC = Function->getDeclContext();
John McCall2cc26752010-03-27 06:55:49 +0000112 } else if (DC->isFileContext()) {
113 break;
114 } else {
115 DC = DC->getParent();
116 }
John McCall88b6c712010-03-17 04:58:56 +0000117 }
Anders Carlssonc4f1e872009-03-27 06:03:27 +0000118 }
Sebastian Redl726212f2009-07-18 14:32:15 +0000119
John McCall0c01d182010-03-24 05:22:00 +0000120 bool isDependent() const { return Dependent; }
121
John McCall88b6c712010-03-17 04:58:56 +0000122 bool includesClass(const CXXRecordDecl *R) const {
123 R = R->getCanonicalDecl();
124 return std::find(Records.begin(), Records.end(), R)
125 != Records.end();
John McCall6b2accb2010-02-10 09:31:12 +0000126 }
127
John McCall7ad650f2010-03-24 07:46:06 +0000128 /// Retrieves the innermost "useful" context. Can be null if we're
129 /// doing access-control without privileges.
130 DeclContext *getInnerContext() const {
131 return Inner;
John McCall0c01d182010-03-24 05:22:00 +0000132 }
133
Chris Lattner5f9e2722011-07-23 10:55:15 +0000134 typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
John McCall0c01d182010-03-24 05:22:00 +0000135
John McCall7ad650f2010-03-24 07:46:06 +0000136 DeclContext *Inner;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000137 SmallVector<FunctionDecl*, 4> Functions;
138 SmallVector<CXXRecordDecl*, 4> Records;
John McCall0c01d182010-03-24 05:22:00 +0000139 bool Dependent;
John McCall6b2accb2010-02-10 09:31:12 +0000140};
John McCall161755a2010-04-06 21:38:20 +0000141
Nico Weber6bb4dcb2010-11-28 22:53:37 +0000142/// Like sema::AccessedEntity, but kindly lets us scribble all over
John McCall161755a2010-04-06 21:38:20 +0000143/// it.
John McCall9c3087b2010-08-26 02:13:20 +0000144struct AccessTarget : public AccessedEntity {
145 AccessTarget(const AccessedEntity &Entity)
John McCall161755a2010-04-06 21:38:20 +0000146 : AccessedEntity(Entity) {
147 initialize();
148 }
149
150 AccessTarget(ASTContext &Context,
151 MemberNonce _,
152 CXXRecordDecl *NamingClass,
153 DeclAccessPair FoundDecl,
Erik Verbruggen24dd9ad2011-09-19 15:10:40 +0000154 QualType BaseObjectType)
155 : AccessedEntity(Context, Member, NamingClass, FoundDecl, BaseObjectType) {
John McCall161755a2010-04-06 21:38:20 +0000156 initialize();
157 }
158
159 AccessTarget(ASTContext &Context,
160 BaseNonce _,
161 CXXRecordDecl *BaseClass,
162 CXXRecordDecl *DerivedClass,
163 AccessSpecifier Access)
164 : AccessedEntity(Context, Base, BaseClass, DerivedClass, Access) {
165 initialize();
166 }
167
168 bool hasInstanceContext() const {
169 return HasInstanceContext;
170 }
171
172 class SavedInstanceContext {
173 public:
174 ~SavedInstanceContext() {
175 Target.HasInstanceContext = Has;
176 }
177
178 private:
John McCallc91cc662010-04-07 00:41:46 +0000179 friend struct AccessTarget;
John McCall161755a2010-04-06 21:38:20 +0000180 explicit SavedInstanceContext(AccessTarget &Target)
181 : Target(Target), Has(Target.HasInstanceContext) {}
182 AccessTarget &Target;
183 bool Has;
184 };
185
186 SavedInstanceContext saveInstanceContext() {
187 return SavedInstanceContext(*this);
188 }
189
190 void suppressInstanceContext() {
191 HasInstanceContext = false;
192 }
193
194 const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
195 assert(HasInstanceContext);
196 if (CalculatedInstanceContext)
197 return InstanceContext;
198
199 CalculatedInstanceContext = true;
200 DeclContext *IC = S.computeDeclContext(getBaseObjectType());
201 InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl() : 0);
202 return InstanceContext;
203 }
204
205 const CXXRecordDecl *getDeclaringClass() const {
206 return DeclaringClass;
207 }
208
209private:
210 void initialize() {
211 HasInstanceContext = (isMemberAccess() &&
212 !getBaseObjectType().isNull() &&
213 getTargetDecl()->isCXXInstanceMember());
214 CalculatedInstanceContext = false;
215 InstanceContext = 0;
216
217 if (isMemberAccess())
218 DeclaringClass = FindDeclaringClass(getTargetDecl());
219 else
220 DeclaringClass = getBaseClass();
221 DeclaringClass = DeclaringClass->getCanonicalDecl();
222 }
223
224 bool HasInstanceContext : 1;
225 mutable bool CalculatedInstanceContext : 1;
226 mutable const CXXRecordDecl *InstanceContext;
227 const CXXRecordDecl *DeclaringClass;
228};
229
Anders Carlsson29f006b2009-03-27 05:05:05 +0000230}
John McCall92f88312010-01-23 00:46:32 +0000231
John McCall01ebd9d2010-05-04 05:11:27 +0000232/// Checks whether one class might instantiate to the other.
233static bool MightInstantiateTo(const CXXRecordDecl *From,
234 const CXXRecordDecl *To) {
235 // Declaration names are always preserved by instantiation.
236 if (From->getDeclName() != To->getDeclName())
237 return false;
238
239 const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
240 const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
241 if (FromDC == ToDC) return true;
242 if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
243
244 // Be conservative.
245 return true;
246}
247
John McCall161755a2010-04-06 21:38:20 +0000248/// Checks whether one class is derived from another, inclusively.
249/// Properly indicates when it couldn't be determined due to
250/// dependence.
251///
252/// This should probably be donated to AST or at least Sema.
253static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
254 const CXXRecordDecl *Target) {
255 assert(Derived->getCanonicalDecl() == Derived);
256 assert(Target->getCanonicalDecl() == Target);
John McCallc1b621d2010-03-24 09:04:37 +0000257
John McCall161755a2010-04-06 21:38:20 +0000258 if (Derived == Target) return AR_accessible;
John McCallc1b621d2010-03-24 09:04:37 +0000259
John McCall01ebd9d2010-05-04 05:11:27 +0000260 bool CheckDependent = Derived->isDependentContext();
261 if (CheckDependent && MightInstantiateTo(Derived, Target))
262 return AR_dependent;
263
John McCall161755a2010-04-06 21:38:20 +0000264 AccessResult OnFailure = AR_inaccessible;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000265 SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
John McCall161755a2010-04-06 21:38:20 +0000266
267 while (true) {
Douglas Gregor7432b902011-11-14 23:00:43 +0000268 if (Derived->isDependentContext() && !Derived->hasDefinition())
269 return AR_dependent;
270
John McCall161755a2010-04-06 21:38:20 +0000271 for (CXXRecordDecl::base_class_const_iterator
272 I = Derived->bases_begin(), E = Derived->bases_end(); I != E; ++I) {
273
274 const CXXRecordDecl *RD;
275
276 QualType T = I->getType();
277 if (const RecordType *RT = T->getAs<RecordType>()) {
278 RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall01ebd9d2010-05-04 05:11:27 +0000279 } else if (const InjectedClassNameType *IT
280 = T->getAs<InjectedClassNameType>()) {
281 RD = IT->getDecl();
John McCall161755a2010-04-06 21:38:20 +0000282 } else {
John McCall161755a2010-04-06 21:38:20 +0000283 assert(T->isDependentType() && "non-dependent base wasn't a record?");
284 OnFailure = AR_dependent;
285 continue;
286 }
287
288 RD = RD->getCanonicalDecl();
289 if (RD == Target) return AR_accessible;
John McCall01ebd9d2010-05-04 05:11:27 +0000290 if (CheckDependent && MightInstantiateTo(RD, Target))
291 OnFailure = AR_dependent;
292
John McCall161755a2010-04-06 21:38:20 +0000293 Queue.push_back(RD);
294 }
295
296 if (Queue.empty()) break;
297
298 Derived = Queue.back();
299 Queue.pop_back();
300 }
301
302 return OnFailure;
John McCall6b2accb2010-02-10 09:31:12 +0000303}
304
John McCall161755a2010-04-06 21:38:20 +0000305
John McCall0c01d182010-03-24 05:22:00 +0000306static bool MightInstantiateTo(Sema &S, DeclContext *Context,
307 DeclContext *Friend) {
308 if (Friend == Context)
309 return true;
310
311 assert(!Friend->isDependentContext() &&
312 "can't handle friends with dependent contexts here");
313
314 if (!Context->isDependentContext())
315 return false;
316
317 if (Friend->isFileContext())
318 return false;
319
320 // TODO: this is very conservative
321 return true;
322}
323
324// Asks whether the type in 'context' can ever instantiate to the type
325// in 'friend'.
326static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
327 if (Friend == Context)
328 return true;
329
330 if (!Friend->isDependentType() && !Context->isDependentType())
331 return false;
332
333 // TODO: this is very conservative.
334 return true;
335}
336
337static bool MightInstantiateTo(Sema &S,
338 FunctionDecl *Context,
339 FunctionDecl *Friend) {
340 if (Context->getDeclName() != Friend->getDeclName())
341 return false;
342
343 if (!MightInstantiateTo(S,
344 Context->getDeclContext(),
345 Friend->getDeclContext()))
346 return false;
347
348 CanQual<FunctionProtoType> FriendTy
349 = S.Context.getCanonicalType(Friend->getType())
350 ->getAs<FunctionProtoType>();
351 CanQual<FunctionProtoType> ContextTy
352 = S.Context.getCanonicalType(Context->getType())
353 ->getAs<FunctionProtoType>();
354
355 // There isn't any way that I know of to add qualifiers
356 // during instantiation.
357 if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
358 return false;
359
360 if (FriendTy->getNumArgs() != ContextTy->getNumArgs())
361 return false;
362
363 if (!MightInstantiateTo(S,
364 ContextTy->getResultType(),
365 FriendTy->getResultType()))
366 return false;
367
368 for (unsigned I = 0, E = FriendTy->getNumArgs(); I != E; ++I)
369 if (!MightInstantiateTo(S,
370 ContextTy->getArgType(I),
371 FriendTy->getArgType(I)))
372 return false;
373
374 return true;
375}
376
377static bool MightInstantiateTo(Sema &S,
378 FunctionTemplateDecl *Context,
379 FunctionTemplateDecl *Friend) {
380 return MightInstantiateTo(S,
381 Context->getTemplatedDecl(),
382 Friend->getTemplatedDecl());
383}
384
John McCall161755a2010-04-06 21:38:20 +0000385static AccessResult MatchesFriend(Sema &S,
386 const EffectiveContext &EC,
387 const CXXRecordDecl *Friend) {
John McCalla742db02010-03-17 20:01:29 +0000388 if (EC.includesClass(Friend))
John McCall161755a2010-04-06 21:38:20 +0000389 return AR_accessible;
John McCalla742db02010-03-17 20:01:29 +0000390
John McCall0c01d182010-03-24 05:22:00 +0000391 if (EC.isDependent()) {
392 CanQualType FriendTy
393 = S.Context.getCanonicalType(S.Context.getTypeDeclType(Friend));
394
395 for (EffectiveContext::record_iterator
396 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
397 CanQualType ContextTy
398 = S.Context.getCanonicalType(S.Context.getTypeDeclType(*I));
399 if (MightInstantiateTo(S, ContextTy, FriendTy))
John McCall161755a2010-04-06 21:38:20 +0000400 return AR_dependent;
John McCall0c01d182010-03-24 05:22:00 +0000401 }
402 }
403
John McCall161755a2010-04-06 21:38:20 +0000404 return AR_inaccessible;
John McCalla742db02010-03-17 20:01:29 +0000405}
406
John McCall161755a2010-04-06 21:38:20 +0000407static AccessResult MatchesFriend(Sema &S,
408 const EffectiveContext &EC,
409 CanQualType Friend) {
John McCall0c01d182010-03-24 05:22:00 +0000410 if (const RecordType *RT = Friend->getAs<RecordType>())
411 return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
John McCalla742db02010-03-17 20:01:29 +0000412
John McCall0c01d182010-03-24 05:22:00 +0000413 // TODO: we can do better than this
414 if (Friend->isDependentType())
John McCall161755a2010-04-06 21:38:20 +0000415 return AR_dependent;
John McCalla742db02010-03-17 20:01:29 +0000416
John McCall161755a2010-04-06 21:38:20 +0000417 return AR_inaccessible;
John McCall0c01d182010-03-24 05:22:00 +0000418}
419
420/// Determines whether the given friend class template matches
421/// anything in the effective context.
John McCall161755a2010-04-06 21:38:20 +0000422static AccessResult MatchesFriend(Sema &S,
423 const EffectiveContext &EC,
424 ClassTemplateDecl *Friend) {
425 AccessResult OnFailure = AR_inaccessible;
John McCall0c01d182010-03-24 05:22:00 +0000426
John McCall93ba8572010-03-25 06:39:04 +0000427 // Check whether the friend is the template of a class in the
428 // context chain.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000429 for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
John McCall0c01d182010-03-24 05:22:00 +0000430 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
431 CXXRecordDecl *Record = *I;
432
John McCall93ba8572010-03-25 06:39:04 +0000433 // Figure out whether the current class has a template:
John McCall0c01d182010-03-24 05:22:00 +0000434 ClassTemplateDecl *CTD;
435
436 // A specialization of the template...
437 if (isa<ClassTemplateSpecializationDecl>(Record)) {
438 CTD = cast<ClassTemplateSpecializationDecl>(Record)
439 ->getSpecializedTemplate();
440
441 // ... or the template pattern itself.
442 } else {
443 CTD = Record->getDescribedClassTemplate();
444 if (!CTD) continue;
445 }
446
447 // It's a match.
448 if (Friend == CTD->getCanonicalDecl())
John McCall161755a2010-04-06 21:38:20 +0000449 return AR_accessible;
John McCall0c01d182010-03-24 05:22:00 +0000450
John McCall93ba8572010-03-25 06:39:04 +0000451 // If the context isn't dependent, it can't be a dependent match.
452 if (!EC.isDependent())
453 continue;
454
John McCall0c01d182010-03-24 05:22:00 +0000455 // If the template names don't match, it can't be a dependent
Richard Smith3e4c6c42011-05-05 21:57:07 +0000456 // match.
457 if (CTD->getDeclName() != Friend->getDeclName())
John McCall0c01d182010-03-24 05:22:00 +0000458 continue;
459
460 // If the class's context can't instantiate to the friend's
461 // context, it can't be a dependent match.
462 if (!MightInstantiateTo(S, CTD->getDeclContext(),
463 Friend->getDeclContext()))
464 continue;
465
466 // Otherwise, it's a dependent match.
John McCall161755a2010-04-06 21:38:20 +0000467 OnFailure = AR_dependent;
John McCalla742db02010-03-17 20:01:29 +0000468 }
469
John McCall0c01d182010-03-24 05:22:00 +0000470 return OnFailure;
471}
472
473/// Determines whether the given friend function matches anything in
474/// the effective context.
John McCall161755a2010-04-06 21:38:20 +0000475static AccessResult MatchesFriend(Sema &S,
476 const EffectiveContext &EC,
477 FunctionDecl *Friend) {
478 AccessResult OnFailure = AR_inaccessible;
John McCall0c01d182010-03-24 05:22:00 +0000479
Chris Lattner5f9e2722011-07-23 10:55:15 +0000480 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall2cc26752010-03-27 06:55:49 +0000481 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
482 if (Friend == *I)
John McCall161755a2010-04-06 21:38:20 +0000483 return AR_accessible;
John McCall0c01d182010-03-24 05:22:00 +0000484
John McCall2cc26752010-03-27 06:55:49 +0000485 if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
John McCall161755a2010-04-06 21:38:20 +0000486 OnFailure = AR_dependent;
John McCall2cc26752010-03-27 06:55:49 +0000487 }
John McCall0c01d182010-03-24 05:22:00 +0000488
John McCall2cc26752010-03-27 06:55:49 +0000489 return OnFailure;
John McCall0c01d182010-03-24 05:22:00 +0000490}
491
492/// Determines whether the given friend function template matches
493/// anything in the effective context.
John McCall161755a2010-04-06 21:38:20 +0000494static AccessResult MatchesFriend(Sema &S,
495 const EffectiveContext &EC,
496 FunctionTemplateDecl *Friend) {
497 if (EC.Functions.empty()) return AR_inaccessible;
John McCall0c01d182010-03-24 05:22:00 +0000498
John McCall161755a2010-04-06 21:38:20 +0000499 AccessResult OnFailure = AR_inaccessible;
John McCall0c01d182010-03-24 05:22:00 +0000500
Chris Lattner5f9e2722011-07-23 10:55:15 +0000501 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall2cc26752010-03-27 06:55:49 +0000502 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
John McCall0c01d182010-03-24 05:22:00 +0000503
John McCall2cc26752010-03-27 06:55:49 +0000504 FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
505 if (!FTD)
506 FTD = (*I)->getDescribedFunctionTemplate();
507 if (!FTD)
508 continue;
John McCall0c01d182010-03-24 05:22:00 +0000509
John McCall2cc26752010-03-27 06:55:49 +0000510 FTD = FTD->getCanonicalDecl();
511
512 if (Friend == FTD)
John McCall161755a2010-04-06 21:38:20 +0000513 return AR_accessible;
John McCall2cc26752010-03-27 06:55:49 +0000514
515 if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
John McCall161755a2010-04-06 21:38:20 +0000516 OnFailure = AR_dependent;
John McCall2cc26752010-03-27 06:55:49 +0000517 }
518
519 return OnFailure;
John McCall0c01d182010-03-24 05:22:00 +0000520}
521
522/// Determines whether the given friend declaration matches anything
523/// in the effective context.
John McCall161755a2010-04-06 21:38:20 +0000524static AccessResult MatchesFriend(Sema &S,
525 const EffectiveContext &EC,
526 FriendDecl *FriendD) {
John McCall6102ca12010-10-16 06:59:13 +0000527 // Whitelist accesses if there's an invalid or unsupported friend
528 // declaration.
529 if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
John McCall337ec3d2010-10-12 23:13:28 +0000530 return AR_accessible;
531
John McCall32f2fb52010-03-25 18:04:51 +0000532 if (TypeSourceInfo *T = FriendD->getFriendType())
533 return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
John McCall0c01d182010-03-24 05:22:00 +0000534
535 NamedDecl *Friend
536 = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
John McCalla742db02010-03-17 20:01:29 +0000537
538 // FIXME: declarations with dependent or templated scope.
539
John McCall0c01d182010-03-24 05:22:00 +0000540 if (isa<ClassTemplateDecl>(Friend))
541 return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
John McCalla742db02010-03-17 20:01:29 +0000542
John McCall0c01d182010-03-24 05:22:00 +0000543 if (isa<FunctionTemplateDecl>(Friend))
544 return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
John McCalla742db02010-03-17 20:01:29 +0000545
John McCall0c01d182010-03-24 05:22:00 +0000546 if (isa<CXXRecordDecl>(Friend))
547 return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
John McCalla742db02010-03-17 20:01:29 +0000548
John McCall0c01d182010-03-24 05:22:00 +0000549 assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
550 return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
John McCalla742db02010-03-17 20:01:29 +0000551}
552
John McCall161755a2010-04-06 21:38:20 +0000553static AccessResult GetFriendKind(Sema &S,
554 const EffectiveContext &EC,
555 const CXXRecordDecl *Class) {
556 AccessResult OnFailure = AR_inaccessible;
John McCall88b6c712010-03-17 04:58:56 +0000557
John McCalld60e22e2010-03-12 01:19:31 +0000558 // Okay, check friends.
559 for (CXXRecordDecl::friend_iterator I = Class->friend_begin(),
560 E = Class->friend_end(); I != E; ++I) {
561 FriendDecl *Friend = *I;
562
John McCalla742db02010-03-17 20:01:29 +0000563 switch (MatchesFriend(S, EC, Friend)) {
John McCall161755a2010-04-06 21:38:20 +0000564 case AR_accessible:
565 return AR_accessible;
John McCalld60e22e2010-03-12 01:19:31 +0000566
John McCall161755a2010-04-06 21:38:20 +0000567 case AR_inaccessible:
568 continue;
569
570 case AR_dependent:
571 OnFailure = AR_dependent;
John McCalla742db02010-03-17 20:01:29 +0000572 break;
John McCalld60e22e2010-03-12 01:19:31 +0000573 }
John McCalld60e22e2010-03-12 01:19:31 +0000574 }
575
576 // That's it, give up.
John McCall88b6c712010-03-17 04:58:56 +0000577 return OnFailure;
John McCall6b2accb2010-02-10 09:31:12 +0000578}
579
John McCall8c77bcb2010-08-28 07:56:00 +0000580namespace {
581
582/// A helper class for checking for a friend which will grant access
583/// to a protected instance member.
584struct ProtectedFriendContext {
585 Sema &S;
586 const EffectiveContext &EC;
587 const CXXRecordDecl *NamingClass;
588 bool CheckDependent;
589 bool EverDependent;
590
591 /// The path down to the current base class.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000592 SmallVector<const CXXRecordDecl*, 20> CurPath;
John McCall8c77bcb2010-08-28 07:56:00 +0000593
594 ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
595 const CXXRecordDecl *InstanceContext,
596 const CXXRecordDecl *NamingClass)
597 : S(S), EC(EC), NamingClass(NamingClass),
598 CheckDependent(InstanceContext->isDependentContext() ||
599 NamingClass->isDependentContext()),
600 EverDependent(false) {}
601
John McCall326c8c72010-08-28 08:47:21 +0000602 /// Check classes in the current path for friendship, starting at
603 /// the given index.
604 bool checkFriendshipAlongPath(unsigned I) {
605 assert(I < CurPath.size());
606 for (unsigned E = CurPath.size(); I != E; ++I) {
607 switch (GetFriendKind(S, EC, CurPath[I])) {
John McCall8c77bcb2010-08-28 07:56:00 +0000608 case AR_accessible: return true;
609 case AR_inaccessible: continue;
610 case AR_dependent: EverDependent = true; continue;
611 }
612 }
613 return false;
614 }
615
616 /// Perform a search starting at the given class.
John McCall326c8c72010-08-28 08:47:21 +0000617 ///
618 /// PrivateDepth is the index of the last (least derived) class
619 /// along the current path such that a notional public member of
620 /// the final class in the path would have access in that class.
621 bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
John McCall8c77bcb2010-08-28 07:56:00 +0000622 // If we ever reach the naming class, check the current path for
623 // friendship. We can also stop recursing because we obviously
624 // won't find the naming class there again.
John McCall326c8c72010-08-28 08:47:21 +0000625 if (Cur == NamingClass)
626 return checkFriendshipAlongPath(PrivateDepth);
John McCall8c77bcb2010-08-28 07:56:00 +0000627
628 if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
629 EverDependent = true;
630
631 // Recurse into the base classes.
632 for (CXXRecordDecl::base_class_const_iterator
633 I = Cur->bases_begin(), E = Cur->bases_end(); I != E; ++I) {
634
John McCall326c8c72010-08-28 08:47:21 +0000635 // If this is private inheritance, then a public member of the
636 // base will not have any access in classes derived from Cur.
637 unsigned BasePrivateDepth = PrivateDepth;
638 if (I->getAccessSpecifier() == AS_private)
639 BasePrivateDepth = CurPath.size() - 1;
John McCall8c77bcb2010-08-28 07:56:00 +0000640
641 const CXXRecordDecl *RD;
642
643 QualType T = I->getType();
644 if (const RecordType *RT = T->getAs<RecordType>()) {
645 RD = cast<CXXRecordDecl>(RT->getDecl());
646 } else if (const InjectedClassNameType *IT
647 = T->getAs<InjectedClassNameType>()) {
648 RD = IT->getDecl();
649 } else {
650 assert(T->isDependentType() && "non-dependent base wasn't a record?");
651 EverDependent = true;
652 continue;
653 }
654
655 // Recurse. We don't need to clean up if this returns true.
John McCall326c8c72010-08-28 08:47:21 +0000656 CurPath.push_back(RD);
657 if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
658 return true;
659 CurPath.pop_back();
John McCall8c77bcb2010-08-28 07:56:00 +0000660 }
661
John McCall8c77bcb2010-08-28 07:56:00 +0000662 return false;
663 }
John McCall326c8c72010-08-28 08:47:21 +0000664
665 bool findFriendship(const CXXRecordDecl *Cur) {
666 assert(CurPath.empty());
667 CurPath.push_back(Cur);
668 return findFriendship(Cur, 0);
669 }
John McCall8c77bcb2010-08-28 07:56:00 +0000670};
671}
672
673/// Search for a class P that EC is a friend of, under the constraint
674/// InstanceContext <= P <= NamingClass
675/// and with the additional restriction that a protected member of
676/// NamingClass would have some natural access in P.
677///
678/// That second condition isn't actually quite right: the condition in
679/// the standard is whether the target would have some natural access
680/// in P. The difference is that the target might be more accessible
681/// along some path not passing through NamingClass. Allowing that
682/// introduces two problems:
683/// - It breaks encapsulation because you can suddenly access a
684/// forbidden base class's members by subclassing it elsewhere.
685/// - It makes access substantially harder to compute because it
686/// breaks the hill-climbing algorithm: knowing that the target is
687/// accessible in some base class would no longer let you change
688/// the question solely to whether the base class is accessible,
689/// because the original target might have been more accessible
690/// because of crazy subclassing.
691/// So we don't implement that.
692static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
693 const CXXRecordDecl *InstanceContext,
694 const CXXRecordDecl *NamingClass) {
695 assert(InstanceContext->getCanonicalDecl() == InstanceContext);
696 assert(NamingClass->getCanonicalDecl() == NamingClass);
697
698 ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
699 if (PRC.findFriendship(InstanceContext)) return AR_accessible;
700 if (PRC.EverDependent) return AR_dependent;
701 return AR_inaccessible;
702}
703
John McCall161755a2010-04-06 21:38:20 +0000704static AccessResult HasAccess(Sema &S,
705 const EffectiveContext &EC,
706 const CXXRecordDecl *NamingClass,
707 AccessSpecifier Access,
708 const AccessTarget &Target) {
John McCalldb73c682010-04-02 00:03:43 +0000709 assert(NamingClass->getCanonicalDecl() == NamingClass &&
710 "declaration should be canonicalized before being passed here");
711
John McCall161755a2010-04-06 21:38:20 +0000712 if (Access == AS_public) return AR_accessible;
John McCalldb73c682010-04-02 00:03:43 +0000713 assert(Access == AS_private || Access == AS_protected);
714
John McCall161755a2010-04-06 21:38:20 +0000715 AccessResult OnFailure = AR_inaccessible;
716
John McCalldb73c682010-04-02 00:03:43 +0000717 for (EffectiveContext::record_iterator
718 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
719 // All the declarations in EC have been canonicalized, so pointer
720 // equality from this point on will work fine.
721 const CXXRecordDecl *ECRecord = *I;
722
723 // [B2] and [M2]
John McCall161755a2010-04-06 21:38:20 +0000724 if (Access == AS_private) {
725 if (ECRecord == NamingClass)
726 return AR_accessible;
John McCalldb73c682010-04-02 00:03:43 +0000727
John McCall01ebd9d2010-05-04 05:11:27 +0000728 if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
729 OnFailure = AR_dependent;
730
John McCalldb73c682010-04-02 00:03:43 +0000731 // [B3] and [M3]
John McCall161755a2010-04-06 21:38:20 +0000732 } else {
733 assert(Access == AS_protected);
734 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
735 case AR_accessible: break;
736 case AR_inaccessible: continue;
737 case AR_dependent: OnFailure = AR_dependent; continue;
738 }
739
740 if (!Target.hasInstanceContext())
741 return AR_accessible;
742
743 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
744 if (!InstanceContext) {
745 OnFailure = AR_dependent;
746 continue;
747 }
748
749 // C++ [class.protected]p1:
750 // An additional access check beyond those described earlier in
751 // [class.access] is applied when a non-static data member or
752 // non-static member function is a protected member of its naming
753 // class. As described earlier, access to a protected member is
754 // granted because the reference occurs in a friend or member of
755 // some class C. If the access is to form a pointer to member,
756 // the nested-name-specifier shall name C or a class derived from
757 // C. All other accesses involve a (possibly implicit) object
758 // expression. In this case, the class of the object expression
759 // shall be C or a class derived from C.
760 //
761 // We interpret this as a restriction on [M3]. Most of the
762 // conditions are encoded by not having any instance context.
763 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
764 case AR_accessible: return AR_accessible;
765 case AR_inaccessible: continue;
766 case AR_dependent: OnFailure = AR_dependent; continue;
767 }
768 }
John McCalldb73c682010-04-02 00:03:43 +0000769 }
770
John McCall8c77bcb2010-08-28 07:56:00 +0000771 // [M3] and [B3] say that, if the target is protected in N, we grant
772 // access if the access occurs in a friend or member of some class P
773 // that's a subclass of N and where the target has some natural
774 // access in P. The 'member' aspect is easy to handle because P
775 // would necessarily be one of the effective-context records, and we
776 // address that above. The 'friend' aspect is completely ridiculous
777 // to implement because there are no restrictions at all on P
778 // *unless* the [class.protected] restriction applies. If it does,
779 // however, we should ignore whether the naming class is a friend,
780 // and instead rely on whether any potential P is a friend.
John McCall161755a2010-04-06 21:38:20 +0000781 if (Access == AS_protected && Target.hasInstanceContext()) {
782 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
783 if (!InstanceContext) return AR_dependent;
John McCall8c77bcb2010-08-28 07:56:00 +0000784 switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
785 case AR_accessible: return AR_accessible;
John McCall161755a2010-04-06 21:38:20 +0000786 case AR_inaccessible: return OnFailure;
787 case AR_dependent: return AR_dependent;
788 }
John McCall1797a052010-08-28 08:10:32 +0000789 llvm_unreachable("impossible friendship kind");
John McCall161755a2010-04-06 21:38:20 +0000790 }
791
792 switch (GetFriendKind(S, EC, NamingClass)) {
793 case AR_accessible: return AR_accessible;
794 case AR_inaccessible: return OnFailure;
795 case AR_dependent: return AR_dependent;
796 }
797
798 // Silence bogus warnings
799 llvm_unreachable("impossible friendship kind");
John McCalldb73c682010-04-02 00:03:43 +0000800}
801
John McCall6b2accb2010-02-10 09:31:12 +0000802/// Finds the best path from the naming class to the declaring class,
803/// taking friend declarations into account.
804///
John McCalldb73c682010-04-02 00:03:43 +0000805/// C++0x [class.access.base]p5:
806/// A member m is accessible at the point R when named in class N if
807/// [M1] m as a member of N is public, or
808/// [M2] m as a member of N is private, and R occurs in a member or
809/// friend of class N, or
810/// [M3] m as a member of N is protected, and R occurs in a member or
811/// friend of class N, or in a member or friend of a class P
812/// derived from N, where m as a member of P is public, private,
813/// or protected, or
814/// [M4] there exists a base class B of N that is accessible at R, and
815/// m is accessible at R when named in class B.
816///
817/// C++0x [class.access.base]p4:
818/// A base class B of N is accessible at R, if
819/// [B1] an invented public member of B would be a public member of N, or
820/// [B2] R occurs in a member or friend of class N, and an invented public
821/// member of B would be a private or protected member of N, or
822/// [B3] R occurs in a member or friend of a class P derived from N, and an
823/// invented public member of B would be a private or protected member
824/// of P, or
825/// [B4] there exists a class S such that B is a base class of S accessible
826/// at R and S is a base class of N accessible at R.
827///
828/// Along a single inheritance path we can restate both of these
829/// iteratively:
830///
831/// First, we note that M1-4 are equivalent to B1-4 if the member is
832/// treated as a notional base of its declaring class with inheritance
833/// access equivalent to the member's access. Therefore we need only
834/// ask whether a class B is accessible from a class N in context R.
835///
836/// Let B_1 .. B_n be the inheritance path in question (i.e. where
837/// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
838/// B_i). For i in 1..n, we will calculate ACAB(i), the access to the
839/// closest accessible base in the path:
840/// Access(a, b) = (* access on the base specifier from a to b *)
841/// Merge(a, forbidden) = forbidden
842/// Merge(a, private) = forbidden
843/// Merge(a, b) = min(a,b)
844/// Accessible(c, forbidden) = false
845/// Accessible(c, private) = (R is c) || IsFriend(c, R)
846/// Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
847/// Accessible(c, public) = true
848/// ACAB(n) = public
849/// ACAB(i) =
850/// let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
851/// if Accessible(B_i, AccessToBase) then public else AccessToBase
852///
853/// B is an accessible base of N at R iff ACAB(1) = public.
854///
John McCall161755a2010-04-06 21:38:20 +0000855/// \param FinalAccess the access of the "final step", or AS_public if
John McCall7aceaf82010-03-18 23:49:19 +0000856/// there is no final step.
John McCall6b2accb2010-02-10 09:31:12 +0000857/// \return null if friendship is dependent
858static CXXBasePath *FindBestPath(Sema &S,
859 const EffectiveContext &EC,
John McCall161755a2010-04-06 21:38:20 +0000860 AccessTarget &Target,
John McCall7aceaf82010-03-18 23:49:19 +0000861 AccessSpecifier FinalAccess,
John McCall6b2accb2010-02-10 09:31:12 +0000862 CXXBasePaths &Paths) {
863 // Derive the paths to the desired base.
John McCall161755a2010-04-06 21:38:20 +0000864 const CXXRecordDecl *Derived = Target.getNamingClass();
865 const CXXRecordDecl *Base = Target.getDeclaringClass();
866
867 // FIXME: fail correctly when there are dependent paths.
868 bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
869 Paths);
John McCall6b2accb2010-02-10 09:31:12 +0000870 assert(isDerived && "derived class not actually derived from base");
871 (void) isDerived;
872
873 CXXBasePath *BestPath = 0;
874
John McCall7aceaf82010-03-18 23:49:19 +0000875 assert(FinalAccess != AS_none && "forbidden access after declaring class");
876
John McCall0c01d182010-03-24 05:22:00 +0000877 bool AnyDependent = false;
878
John McCall6b2accb2010-02-10 09:31:12 +0000879 // Derive the friend-modified access along each path.
880 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
881 PI != PE; ++PI) {
John McCall161755a2010-04-06 21:38:20 +0000882 AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
John McCall6b2accb2010-02-10 09:31:12 +0000883
884 // Walk through the path backwards.
John McCall7aceaf82010-03-18 23:49:19 +0000885 AccessSpecifier PathAccess = FinalAccess;
John McCall6b2accb2010-02-10 09:31:12 +0000886 CXXBasePath::iterator I = PI->end(), E = PI->begin();
887 while (I != E) {
888 --I;
889
John McCall7aceaf82010-03-18 23:49:19 +0000890 assert(PathAccess != AS_none);
891
892 // If the declaration is a private member of a base class, there
893 // is no level of friendship in derived classes that can make it
894 // accessible.
895 if (PathAccess == AS_private) {
896 PathAccess = AS_none;
897 break;
898 }
899
John McCall161755a2010-04-06 21:38:20 +0000900 const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
901
John McCall6b2accb2010-02-10 09:31:12 +0000902 AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
John McCalldb73c682010-04-02 00:03:43 +0000903 PathAccess = std::max(PathAccess, BaseAccess);
John McCall161755a2010-04-06 21:38:20 +0000904
905 switch (HasAccess(S, EC, NC, PathAccess, Target)) {
906 case AR_inaccessible: break;
907 case AR_accessible:
908 PathAccess = AS_public;
909
910 // Future tests are not against members and so do not have
911 // instance context.
912 Target.suppressInstanceContext();
913 break;
914 case AR_dependent:
John McCalldb73c682010-04-02 00:03:43 +0000915 AnyDependent = true;
916 goto Next;
John McCall6b2accb2010-02-10 09:31:12 +0000917 }
John McCall6b2accb2010-02-10 09:31:12 +0000918 }
919
920 // Note that we modify the path's Access field to the
921 // friend-modified access.
922 if (BestPath == 0 || PathAccess < BestPath->Access) {
923 BestPath = &*PI;
924 BestPath->Access = PathAccess;
John McCall0c01d182010-03-24 05:22:00 +0000925
926 // Short-circuit if we found a public path.
927 if (BestPath->Access == AS_public)
928 return BestPath;
John McCall6b2accb2010-02-10 09:31:12 +0000929 }
John McCall0c01d182010-03-24 05:22:00 +0000930
931 Next: ;
John McCall6b2accb2010-02-10 09:31:12 +0000932 }
933
John McCall0c01d182010-03-24 05:22:00 +0000934 assert((!BestPath || BestPath->Access != AS_public) &&
935 "fell out of loop with public path");
936
937 // We didn't find a public path, but at least one path was subject
938 // to dependent friendship, so delay the check.
939 if (AnyDependent)
940 return 0;
941
John McCall6b2accb2010-02-10 09:31:12 +0000942 return BestPath;
943}
944
John McCallfe24e052010-09-03 04:56:05 +0000945/// Given that an entity has protected natural access, check whether
946/// access might be denied because of the protected member access
947/// restriction.
948///
949/// \return true if a note was emitted
950static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
951 AccessTarget &Target) {
952 // Only applies to instance accesses.
953 if (!Target.hasInstanceContext())
954 return false;
955 assert(Target.isMemberAccess());
956 NamedDecl *D = Target.getTargetDecl();
957
958 const CXXRecordDecl *DeclaringClass = Target.getDeclaringClass();
959 DeclaringClass = DeclaringClass->getCanonicalDecl();
960
961 for (EffectiveContext::record_iterator
962 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
963 const CXXRecordDecl *ECRecord = *I;
964 switch (IsDerivedFromInclusive(ECRecord, DeclaringClass)) {
965 case AR_accessible: break;
966 case AR_inaccessible: continue;
967 case AR_dependent: continue;
968 }
969
970 // The effective context is a subclass of the declaring class.
971 // If that class isn't a superclass of the instance context,
972 // then the [class.protected] restriction applies.
973
974 // To get this exactly right, this might need to be checked more
975 // holistically; it's not necessarily the case that gaining
976 // access here would grant us access overall.
977
978 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
979 assert(InstanceContext && "diagnosing dependent access");
980
981 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
982 case AR_accessible: continue;
983 case AR_dependent: continue;
984 case AR_inaccessible:
985 S.Diag(D->getLocation(), diag::note_access_protected_restricted)
986 << (InstanceContext != Target.getNamingClass()->getCanonicalDecl())
987 << S.Context.getTypeDeclType(InstanceContext)
988 << S.Context.getTypeDeclType(ECRecord);
989 return true;
990 }
991 }
992
993 return false;
994}
995
John McCall6b2accb2010-02-10 09:31:12 +0000996/// Diagnose the path which caused the given declaration or base class
997/// to become inaccessible.
998static void DiagnoseAccessPath(Sema &S,
999 const EffectiveContext &EC,
John McCall161755a2010-04-06 21:38:20 +00001000 AccessTarget &Entity) {
John McCalldb73c682010-04-02 00:03:43 +00001001 AccessSpecifier Access = Entity.getAccess();
John McCalldb73c682010-04-02 00:03:43 +00001002
John McCall161755a2010-04-06 21:38:20 +00001003 NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : 0);
1004 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
John McCalldb73c682010-04-02 00:03:43 +00001005
John McCall92f88312010-01-23 00:46:32 +00001006 // Easy case: the decl's natural access determined its path access.
John McCall6b2accb2010-02-10 09:31:12 +00001007 // We have to check against AS_private here in case Access is AS_none,
1008 // indicating a non-public member of a private base class.
John McCall6b2accb2010-02-10 09:31:12 +00001009 if (D && (Access == D->getAccess() || D->getAccess() == AS_private)) {
John McCall161755a2010-04-06 21:38:20 +00001010 switch (HasAccess(S, EC, DeclaringClass, D->getAccess(), Entity)) {
1011 case AR_inaccessible: {
John McCallfe24e052010-09-03 04:56:05 +00001012 if (Access == AS_protected &&
1013 TryDiagnoseProtectedAccess(S, EC, Entity))
1014 return;
1015
John McCallaa56a662010-10-20 08:15:06 +00001016 // Find an original declaration.
1017 while (D->isOutOfLine()) {
1018 NamedDecl *PrevDecl = 0;
Richard Smith162e1c12011-04-15 14:24:37 +00001019 if (VarDecl *VD = dyn_cast<VarDecl>(D))
Douglas Gregoref96ee02012-01-14 16:38:05 +00001020 PrevDecl = VD->getPreviousDecl();
Richard Smith162e1c12011-04-15 14:24:37 +00001021 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
Douglas Gregoref96ee02012-01-14 16:38:05 +00001022 PrevDecl = FD->getPreviousDecl();
Richard Smith162e1c12011-04-15 14:24:37 +00001023 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
Douglas Gregoref96ee02012-01-14 16:38:05 +00001024 PrevDecl = TND->getPreviousDecl();
Richard Smith162e1c12011-04-15 14:24:37 +00001025 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
John McCallaa56a662010-10-20 08:15:06 +00001026 if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
1027 break;
Douglas Gregoref96ee02012-01-14 16:38:05 +00001028 PrevDecl = TD->getPreviousDecl();
John McCallaa56a662010-10-20 08:15:06 +00001029 }
1030 if (!PrevDecl) break;
1031 D = PrevDecl;
1032 }
1033
1034 CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1035 Decl *ImmediateChild;
1036 if (D->getDeclContext() == DeclaringClass)
1037 ImmediateChild = D;
1038 else {
1039 DeclContext *DC = D->getDeclContext();
1040 while (DC->getParent() != DeclaringClass)
1041 DC = DC->getParent();
1042 ImmediateChild = cast<Decl>(DC);
1043 }
1044
1045 // Check whether there's an AccessSpecDecl preceding this in the
1046 // chain of the DeclContext.
1047 bool Implicit = true;
1048 for (CXXRecordDecl::decl_iterator
1049 I = DeclaringClass->decls_begin(), E = DeclaringClass->decls_end();
1050 I != E; ++I) {
1051 if (*I == ImmediateChild) break;
1052 if (isa<AccessSpecDecl>(*I)) {
1053 Implicit = false;
1054 break;
1055 }
1056 }
1057
John McCall6b2accb2010-02-10 09:31:12 +00001058 S.Diag(D->getLocation(), diag::note_access_natural)
1059 << (unsigned) (Access == AS_protected)
John McCallaa56a662010-10-20 08:15:06 +00001060 << Implicit;
John McCall6b2accb2010-02-10 09:31:12 +00001061 return;
1062 }
1063
John McCall161755a2010-04-06 21:38:20 +00001064 case AR_accessible: break;
John McCall6b2accb2010-02-10 09:31:12 +00001065
John McCall161755a2010-04-06 21:38:20 +00001066 case AR_dependent:
1067 llvm_unreachable("can't diagnose dependent access failures");
John McCall6b2accb2010-02-10 09:31:12 +00001068 }
1069 }
1070
1071 CXXBasePaths Paths;
John McCall161755a2010-04-06 21:38:20 +00001072 CXXBasePath &Path = *FindBestPath(S, EC, Entity, AS_public, Paths);
John McCall6b2accb2010-02-10 09:31:12 +00001073
1074 CXXBasePath::iterator I = Path.end(), E = Path.begin();
1075 while (I != E) {
1076 --I;
1077
1078 const CXXBaseSpecifier *BS = I->Base;
1079 AccessSpecifier BaseAccess = BS->getAccessSpecifier();
1080
1081 // If this is public inheritance, or the derived class is a friend,
1082 // skip this step.
1083 if (BaseAccess == AS_public)
1084 continue;
1085
1086 switch (GetFriendKind(S, EC, I->Class)) {
John McCall161755a2010-04-06 21:38:20 +00001087 case AR_accessible: continue;
1088 case AR_inaccessible: break;
1089 case AR_dependent:
1090 llvm_unreachable("can't diagnose dependent access failures");
John McCall6b2accb2010-02-10 09:31:12 +00001091 }
1092
1093 // Check whether this base specifier is the tighest point
1094 // constraining access. We have to check against AS_private for
1095 // the same reasons as above.
1096 if (BaseAccess == AS_private || BaseAccess >= Access) {
1097
1098 // We're constrained by inheritance, but we want to say
1099 // "declared private here" if we're diagnosing a hierarchy
1100 // conversion and this is the final step.
1101 unsigned diagnostic;
1102 if (D) diagnostic = diag::note_access_constrained_by_path;
1103 else if (I + 1 == Path.end()) diagnostic = diag::note_access_natural;
1104 else diagnostic = diag::note_access_constrained_by_path;
1105
1106 S.Diag(BS->getSourceRange().getBegin(), diagnostic)
1107 << BS->getSourceRange()
1108 << (BaseAccess == AS_protected)
1109 << (BS->getAccessSpecifierAsWritten() == AS_none);
Douglas Gregor76ef6582010-05-28 04:34:55 +00001110
1111 if (D)
1112 S.Diag(D->getLocation(), diag::note_field_decl);
1113
John McCall6b2accb2010-02-10 09:31:12 +00001114 return;
1115 }
1116 }
1117
1118 llvm_unreachable("access not apparently constrained by path");
1119}
1120
John McCall58e6f342010-03-16 05:22:47 +00001121static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
John McCall6b2accb2010-02-10 09:31:12 +00001122 const EffectiveContext &EC,
John McCall161755a2010-04-06 21:38:20 +00001123 AccessTarget &Entity) {
John McCalldb73c682010-04-02 00:03:43 +00001124 const CXXRecordDecl *NamingClass = Entity.getNamingClass();
John McCall161755a2010-04-06 21:38:20 +00001125 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1126 NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : 0);
John McCalldb73c682010-04-02 00:03:43 +00001127
1128 S.Diag(Loc, Entity.getDiag())
1129 << (Entity.getAccess() == AS_protected)
1130 << (D ? D->getDeclName() : DeclarationName())
1131 << S.Context.getTypeDeclType(NamingClass)
1132 << S.Context.getTypeDeclType(DeclaringClass);
1133 DiagnoseAccessPath(S, EC, Entity);
John McCall6b2accb2010-02-10 09:31:12 +00001134}
1135
Francois Pichetb2ee8302011-05-23 03:43:44 +00001136/// MSVC has a bug where if during an using declaration name lookup,
1137/// the declaration found is unaccessible (private) and that declaration
1138/// was bring into scope via another using declaration whose target
1139/// declaration is accessible (public) then no error is generated.
1140/// Example:
1141/// class A {
1142/// public:
1143/// int f();
1144/// };
1145/// class B : public A {
1146/// private:
1147/// using A::f;
1148/// };
1149/// class C : public B {
1150/// private:
1151/// using B::f;
1152/// };
1153///
1154/// Here, B::f is private so this should fail in Standard C++, but
1155/// because B::f refers to A::f which is public MSVC accepts it.
1156static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
1157 SourceLocation AccessLoc,
1158 AccessTarget &Entity) {
1159 if (UsingShadowDecl *Shadow =
1160 dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) {
1161 const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
1162 if (Entity.getTargetDecl()->getAccess() == AS_private &&
1163 (OrigDecl->getAccess() == AS_public ||
1164 OrigDecl->getAccess() == AS_protected)) {
Richard Smithd7c56e12011-12-29 21:57:33 +00001165 S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
Francois Pichetb2ee8302011-05-23 03:43:44 +00001166 << Shadow->getUsingDecl()->getQualifiedNameAsString()
1167 << OrigDecl->getQualifiedNameAsString();
1168 return true;
1169 }
1170 }
1171 return false;
1172}
1173
John McCalldb73c682010-04-02 00:03:43 +00001174/// Determines whether the accessed entity is accessible. Public members
1175/// have been weeded out by this point.
John McCall161755a2010-04-06 21:38:20 +00001176static AccessResult IsAccessible(Sema &S,
1177 const EffectiveContext &EC,
1178 AccessTarget &Entity) {
John McCalldb73c682010-04-02 00:03:43 +00001179 // Determine the actual naming class.
1180 CXXRecordDecl *NamingClass = Entity.getNamingClass();
1181 while (NamingClass->isAnonymousStructOrUnion())
1182 NamingClass = cast<CXXRecordDecl>(NamingClass->getParent());
1183 NamingClass = NamingClass->getCanonicalDecl();
John McCall6b2accb2010-02-10 09:31:12 +00001184
John McCalldb73c682010-04-02 00:03:43 +00001185 AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1186 assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1187
1188 // Before we try to recalculate access paths, try to white-list
1189 // accesses which just trade in on the final step, i.e. accesses
1190 // which don't require [M4] or [B4]. These are by far the most
John McCall161755a2010-04-06 21:38:20 +00001191 // common forms of privileged access.
John McCalldb73c682010-04-02 00:03:43 +00001192 if (UnprivilegedAccess != AS_none) {
John McCall161755a2010-04-06 21:38:20 +00001193 switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1194 case AR_dependent:
John McCalldb73c682010-04-02 00:03:43 +00001195 // This is actually an interesting policy decision. We don't
1196 // *have* to delay immediately here: we can do the full access
1197 // calculation in the hope that friendship on some intermediate
1198 // class will make the declaration accessible non-dependently.
1199 // But that's not cheap, and odds are very good (note: assertion
1200 // made without data) that the friend declaration will determine
1201 // access.
John McCall161755a2010-04-06 21:38:20 +00001202 return AR_dependent;
John McCalldb73c682010-04-02 00:03:43 +00001203
John McCall161755a2010-04-06 21:38:20 +00001204 case AR_accessible: return AR_accessible;
1205 case AR_inaccessible: break;
John McCalldb73c682010-04-02 00:03:43 +00001206 }
1207 }
1208
John McCall161755a2010-04-06 21:38:20 +00001209 AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
John McCall6b2accb2010-02-10 09:31:12 +00001210
John McCalldb73c682010-04-02 00:03:43 +00001211 // We lower member accesses to base accesses by pretending that the
1212 // member is a base class of its declaring class.
1213 AccessSpecifier FinalAccess;
1214
John McCall6b2accb2010-02-10 09:31:12 +00001215 if (Entity.isMemberAccess()) {
John McCalldb73c682010-04-02 00:03:43 +00001216 // Determine if the declaration is accessible from EC when named
1217 // in its declaring class.
John McCall6b2accb2010-02-10 09:31:12 +00001218 NamedDecl *Target = Entity.getTargetDecl();
John McCall161755a2010-04-06 21:38:20 +00001219 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
John McCall6b2accb2010-02-10 09:31:12 +00001220
John McCalldb73c682010-04-02 00:03:43 +00001221 FinalAccess = Target->getAccess();
John McCall161755a2010-04-06 21:38:20 +00001222 switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1223 case AR_accessible:
1224 FinalAccess = AS_public;
1225 break;
1226 case AR_inaccessible: break;
1227 case AR_dependent: return AR_dependent; // see above
John McCall6b2accb2010-02-10 09:31:12 +00001228 }
1229
John McCalldb73c682010-04-02 00:03:43 +00001230 if (DeclaringClass == NamingClass)
John McCall161755a2010-04-06 21:38:20 +00001231 return (FinalAccess == AS_public ? AR_accessible : AR_inaccessible);
1232
1233 Entity.suppressInstanceContext();
John McCalldb73c682010-04-02 00:03:43 +00001234 } else {
1235 FinalAccess = AS_public;
John McCall6b2accb2010-02-10 09:31:12 +00001236 }
1237
John McCall161755a2010-04-06 21:38:20 +00001238 assert(Entity.getDeclaringClass() != NamingClass);
John McCall6b2accb2010-02-10 09:31:12 +00001239
1240 // Append the declaration's access if applicable.
1241 CXXBasePaths Paths;
John McCall161755a2010-04-06 21:38:20 +00001242 CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
John McCall0c01d182010-03-24 05:22:00 +00001243 if (!Path)
John McCall161755a2010-04-06 21:38:20 +00001244 return AR_dependent;
John McCall92f88312010-01-23 00:46:32 +00001245
John McCalldb73c682010-04-02 00:03:43 +00001246 assert(Path->Access <= UnprivilegedAccess &&
1247 "access along best path worse than direct?");
1248 if (Path->Access == AS_public)
John McCall161755a2010-04-06 21:38:20 +00001249 return AR_accessible;
1250 return AR_inaccessible;
John McCall0c01d182010-03-24 05:22:00 +00001251}
1252
John McCall161755a2010-04-06 21:38:20 +00001253static void DelayDependentAccess(Sema &S,
1254 const EffectiveContext &EC,
1255 SourceLocation Loc,
1256 const AccessTarget &Entity) {
John McCall0c01d182010-03-24 05:22:00 +00001257 assert(EC.isDependent() && "delaying non-dependent access");
John McCall7ad650f2010-03-24 07:46:06 +00001258 DeclContext *DC = EC.getInnerContext();
John McCall0c01d182010-03-24 05:22:00 +00001259 assert(DC->isDependentContext() && "delaying non-dependent access");
1260 DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1261 Loc,
1262 Entity.isMemberAccess(),
1263 Entity.getAccess(),
1264 Entity.getTargetDecl(),
1265 Entity.getNamingClass(),
John McCall161755a2010-04-06 21:38:20 +00001266 Entity.getBaseObjectType(),
John McCall0c01d182010-03-24 05:22:00 +00001267 Entity.getDiag());
John McCall92f88312010-01-23 00:46:32 +00001268}
1269
John McCall6b2accb2010-02-10 09:31:12 +00001270/// Checks access to an entity from the given effective context.
John McCall161755a2010-04-06 21:38:20 +00001271static AccessResult CheckEffectiveAccess(Sema &S,
1272 const EffectiveContext &EC,
1273 SourceLocation Loc,
1274 AccessTarget &Entity) {
John McCalldb73c682010-04-02 00:03:43 +00001275 assert(Entity.getAccess() != AS_public && "called for public access!");
John McCall92f88312010-01-23 00:46:32 +00001276
Francois Pichetcc6306e2011-09-20 22:08:26 +00001277 if (S.getLangOptions().MicrosoftMode &&
Francois Pichetb2ee8302011-05-23 03:43:44 +00001278 IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
1279 return AR_accessible;
1280
John McCalldb73c682010-04-02 00:03:43 +00001281 switch (IsAccessible(S, EC, Entity)) {
John McCall161755a2010-04-06 21:38:20 +00001282 case AR_dependent:
1283 DelayDependentAccess(S, EC, Loc, Entity);
1284 return AR_dependent;
John McCalldb73c682010-04-02 00:03:43 +00001285
John McCall161755a2010-04-06 21:38:20 +00001286 case AR_inaccessible:
John McCalldb73c682010-04-02 00:03:43 +00001287 if (!Entity.isQuiet())
1288 DiagnoseBadAccess(S, Loc, EC, Entity);
John McCall161755a2010-04-06 21:38:20 +00001289 return AR_inaccessible;
John McCalldb73c682010-04-02 00:03:43 +00001290
John McCall161755a2010-04-06 21:38:20 +00001291 case AR_accessible:
1292 return AR_accessible;
John McCall0c01d182010-03-24 05:22:00 +00001293 }
1294
John McCall161755a2010-04-06 21:38:20 +00001295 // silence unnecessary warning
1296 llvm_unreachable("invalid access result");
John McCall6b2accb2010-02-10 09:31:12 +00001297}
John McCall92f88312010-01-23 00:46:32 +00001298
John McCall6b2accb2010-02-10 09:31:12 +00001299static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
John McCall161755a2010-04-06 21:38:20 +00001300 AccessTarget &Entity) {
John McCall6b2accb2010-02-10 09:31:12 +00001301 // If the access path is public, it's accessible everywhere.
1302 if (Entity.getAccess() == AS_public)
1303 return Sema::AR_accessible;
John McCall92f88312010-01-23 00:46:32 +00001304
Chandler Carruth926c4b42010-06-28 08:39:25 +00001305 if (S.SuppressAccessChecking)
1306 return Sema::AR_accessible;
1307
John McCalleee1d542011-02-14 07:13:47 +00001308 // If we're currently parsing a declaration, we may need to delay
1309 // access control checking, because our effective context might be
1310 // different based on what the declaration comes out as.
1311 //
1312 // For example, we might be parsing a declaration with a scope
1313 // specifier, like this:
1314 // A::private_type A::foo() { ... }
1315 //
1316 // Or we might be parsing something that will turn out to be a friend:
1317 // void foo(A::private_type);
1318 // void B::foo(A::private_type);
1319 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1320 S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
John McCall6b2accb2010-02-10 09:31:12 +00001321 return Sema::AR_delayed;
John McCall92f88312010-01-23 00:46:32 +00001322 }
1323
John McCall161755a2010-04-06 21:38:20 +00001324 EffectiveContext EC(S.CurContext);
1325 switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1326 case AR_accessible: return Sema::AR_accessible;
1327 case AR_inaccessible: return Sema::AR_inaccessible;
1328 case AR_dependent: return Sema::AR_dependent;
1329 }
1330 llvm_unreachable("falling off end");
John McCall92f88312010-01-23 00:46:32 +00001331}
1332
John McCall4bfd6802011-02-15 22:51:53 +00001333void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *decl) {
1334 // Access control for names used in the declarations of functions
1335 // and function templates should normally be evaluated in the context
1336 // of the declaration, just in case it's a friend of something.
1337 // However, this does not apply to local extern declarations.
1338
1339 DeclContext *DC = decl->getDeclContext();
1340 if (FunctionDecl *fn = dyn_cast<FunctionDecl>(decl)) {
1341 if (!DC->isFunctionOrMethod()) DC = fn;
1342 } else if (FunctionTemplateDecl *fnt = dyn_cast<FunctionTemplateDecl>(decl)) {
1343 // Never a local declaration.
1344 DC = fnt->getTemplatedDecl();
1345 }
1346
Chandler Carruth630eb012010-04-18 08:23:21 +00001347 EffectiveContext EC(DC);
John McCall2f514482010-01-27 03:50:35 +00001348
John McCall161755a2010-04-06 21:38:20 +00001349 AccessTarget Target(DD.getAccessData());
1350
1351 if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
John McCall2f514482010-01-27 03:50:35 +00001352 DD.Triggered = true;
1353}
1354
John McCall0c01d182010-03-24 05:22:00 +00001355void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1356 const MultiLevelTemplateArgumentList &TemplateArgs) {
1357 SourceLocation Loc = DD.getAccessLoc();
1358 AccessSpecifier Access = DD.getAccess();
1359
1360 Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1361 TemplateArgs);
1362 if (!NamingD) return;
1363 Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1364 TemplateArgs);
1365 if (!TargetD) return;
1366
1367 if (DD.isAccessToMember()) {
John McCall161755a2010-04-06 21:38:20 +00001368 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1369 NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1370 QualType BaseObjectType = DD.getAccessBaseObjectType();
1371 if (!BaseObjectType.isNull()) {
1372 BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1373 DeclarationName());
1374 if (BaseObjectType.isNull()) return;
1375 }
1376
1377 AccessTarget Entity(Context,
1378 AccessTarget::Member,
1379 NamingClass,
1380 DeclAccessPair::make(TargetDecl, Access),
1381 BaseObjectType);
John McCall0c01d182010-03-24 05:22:00 +00001382 Entity.setDiag(DD.getDiagnostic());
1383 CheckAccess(*this, Loc, Entity);
1384 } else {
John McCall161755a2010-04-06 21:38:20 +00001385 AccessTarget Entity(Context,
1386 AccessTarget::Base,
1387 cast<CXXRecordDecl>(TargetD),
1388 cast<CXXRecordDecl>(NamingD),
1389 Access);
John McCall0c01d182010-03-24 05:22:00 +00001390 Entity.setDiag(DD.getDiagnostic());
1391 CheckAccess(*this, Loc, Entity);
1392 }
1393}
1394
John McCall6b2accb2010-02-10 09:31:12 +00001395Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
John McCall9aa472c2010-03-19 07:35:19 +00001396 DeclAccessPair Found) {
John McCall58e6f342010-03-16 05:22:47 +00001397 if (!getLangOptions().AccessControl ||
1398 !E->getNamingClass() ||
John McCall9aa472c2010-03-19 07:35:19 +00001399 Found.getAccess() == AS_public)
John McCall6b2accb2010-02-10 09:31:12 +00001400 return AR_accessible;
John McCallc373d482010-01-27 01:50:18 +00001401
John McCall161755a2010-04-06 21:38:20 +00001402 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1403 Found, QualType());
John McCall58e6f342010-03-16 05:22:47 +00001404 Entity.setDiag(diag::err_access) << E->getSourceRange();
1405
1406 return CheckAccess(*this, E->getNameLoc(), Entity);
John McCallc373d482010-01-27 01:50:18 +00001407}
1408
1409/// Perform access-control checking on a previously-unresolved member
1410/// access which has now been resolved to a member.
John McCall6b2accb2010-02-10 09:31:12 +00001411Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
John McCall9aa472c2010-03-19 07:35:19 +00001412 DeclAccessPair Found) {
John McCall58e6f342010-03-16 05:22:47 +00001413 if (!getLangOptions().AccessControl ||
John McCall9aa472c2010-03-19 07:35:19 +00001414 Found.getAccess() == AS_public)
John McCall6b2accb2010-02-10 09:31:12 +00001415 return AR_accessible;
John McCallc373d482010-01-27 01:50:18 +00001416
John McCall161755a2010-04-06 21:38:20 +00001417 QualType BaseType = E->getBaseType();
1418 if (E->isArrow())
1419 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1420
1421 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1422 Found, BaseType);
John McCall58e6f342010-03-16 05:22:47 +00001423 Entity.setDiag(diag::err_access) << E->getSourceRange();
1424
1425 return CheckAccess(*this, E->getMemberLoc(), Entity);
John McCallc373d482010-01-27 01:50:18 +00001426}
1427
John McCall6b2accb2010-02-10 09:31:12 +00001428Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
John McCall58e6f342010-03-16 05:22:47 +00001429 CXXDestructorDecl *Dtor,
1430 const PartialDiagnostic &PDiag) {
John McCall4f9506a2010-02-02 08:45:54 +00001431 if (!getLangOptions().AccessControl)
John McCall6b2accb2010-02-10 09:31:12 +00001432 return AR_accessible;
John McCall4f9506a2010-02-02 08:45:54 +00001433
John McCall58e6f342010-03-16 05:22:47 +00001434 // There's never a path involved when checking implicit destructor access.
John McCall4f9506a2010-02-02 08:45:54 +00001435 AccessSpecifier Access = Dtor->getAccess();
1436 if (Access == AS_public)
John McCall6b2accb2010-02-10 09:31:12 +00001437 return AR_accessible;
John McCall4f9506a2010-02-02 08:45:54 +00001438
John McCall58e6f342010-03-16 05:22:47 +00001439 CXXRecordDecl *NamingClass = Dtor->getParent();
John McCall161755a2010-04-06 21:38:20 +00001440 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1441 DeclAccessPair::make(Dtor, Access),
1442 QualType());
John McCall58e6f342010-03-16 05:22:47 +00001443 Entity.setDiag(PDiag); // TODO: avoid copy
1444
1445 return CheckAccess(*this, Loc, Entity);
John McCall4f9506a2010-02-02 08:45:54 +00001446}
1447
John McCallb13b7372010-02-01 03:16:54 +00001448/// Checks access to a constructor.
John McCall6b2accb2010-02-10 09:31:12 +00001449Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
Jeffrey Yasskin57d12fd2010-06-07 15:58:05 +00001450 CXXConstructorDecl *Constructor,
1451 const InitializedEntity &Entity,
1452 AccessSpecifier Access,
1453 bool IsCopyBindingRefToTemp) {
John McCall58e6f342010-03-16 05:22:47 +00001454 if (!getLangOptions().AccessControl ||
1455 Access == AS_public)
John McCall6b2accb2010-02-10 09:31:12 +00001456 return AR_accessible;
John McCallb13b7372010-02-01 03:16:54 +00001457
John McCall6b2accb2010-02-10 09:31:12 +00001458 CXXRecordDecl *NamingClass = Constructor->getParent();
Anders Carlsson9a68a672010-04-21 18:47:17 +00001459 AccessTarget AccessEntity(Context, AccessTarget::Member, NamingClass,
1460 DeclAccessPair::make(Constructor, Access),
1461 QualType());
Sean Huntb320e0c2011-06-10 03:50:41 +00001462 PartialDiagnostic PD(PDiag());
Anders Carlsson9a68a672010-04-21 18:47:17 +00001463 switch (Entity.getKind()) {
1464 default:
Sean Huntb320e0c2011-06-10 03:50:41 +00001465 PD = PDiag(IsCopyBindingRefToTemp
1466 ? diag::ext_rvalue_to_reference_access_ctor
1467 : diag::err_access_ctor);
1468
Anders Carlsson9a68a672010-04-21 18:47:17 +00001469 break;
John McCall58e6f342010-03-16 05:22:47 +00001470
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001471 case InitializedEntity::EK_Base:
Sean Huntb320e0c2011-06-10 03:50:41 +00001472 PD = PDiag(diag::err_access_base_ctor);
1473 PD << Entity.isInheritedVirtualBase()
1474 << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
Anders Carlsson9a68a672010-04-21 18:47:17 +00001475 break;
Anders Carlsson3b8c53b2010-04-22 05:40:53 +00001476
Anders Carlssonb99c6662010-04-21 20:28:29 +00001477 case InitializedEntity::EK_Member: {
1478 const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
Sean Huntb320e0c2011-06-10 03:50:41 +00001479 PD = PDiag(diag::err_access_field_ctor);
1480 PD << Field->getType() << getSpecialMember(Constructor);
Anders Carlssonb99c6662010-04-21 20:28:29 +00001481 break;
1482 }
Anders Carlsson9a68a672010-04-21 18:47:17 +00001483
Douglas Gregor47736542012-02-15 16:57:26 +00001484 case InitializedEntity::EK_LambdaCapture: {
1485 const VarDecl *Var = Entity.getCapturedVar();
1486 PD = PDiag(diag::err_access_lambda_capture);
1487 PD << Var->getName() << Entity.getType() << getSpecialMember(Constructor);
1488 break;
1489 }
1490
Anders Carlsson711f34a2010-04-21 19:52:01 +00001491 }
1492
Sean Huntb320e0c2011-06-10 03:50:41 +00001493 return CheckConstructorAccess(UseLoc, Constructor, Access, PD);
1494}
1495
1496/// Checks access to a constructor.
1497Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1498 CXXConstructorDecl *Constructor,
1499 AccessSpecifier Access,
1500 PartialDiagnostic PD) {
1501 if (!getLangOptions().AccessControl ||
1502 Access == AS_public)
1503 return AR_accessible;
1504
1505 CXXRecordDecl *NamingClass = Constructor->getParent();
1506 AccessTarget AccessEntity(Context, AccessTarget::Member, NamingClass,
1507 DeclAccessPair::make(Constructor, Access),
1508 QualType());
1509 AccessEntity.setDiag(PD);
1510
Anders Carlsson9a68a672010-04-21 18:47:17 +00001511 return CheckAccess(*this, UseLoc, AccessEntity);
John McCallb13b7372010-02-01 03:16:54 +00001512}
1513
John McCallb0207482010-03-16 06:11:48 +00001514/// Checks direct (i.e. non-inherited) access to an arbitrary class
1515/// member.
1516Sema::AccessResult Sema::CheckDirectMemberAccess(SourceLocation UseLoc,
1517 NamedDecl *Target,
1518 const PartialDiagnostic &Diag) {
1519 AccessSpecifier Access = Target->getAccess();
1520 if (!getLangOptions().AccessControl ||
1521 Access == AS_public)
1522 return AR_accessible;
1523
1524 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(Target->getDeclContext());
John McCall161755a2010-04-06 21:38:20 +00001525 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1526 DeclAccessPair::make(Target, Access),
1527 QualType());
John McCallb0207482010-03-16 06:11:48 +00001528 Entity.setDiag(Diag);
1529 return CheckAccess(*this, UseLoc, Entity);
1530}
1531
1532
John McCall90c8c572010-03-18 08:19:33 +00001533/// Checks access to an overloaded operator new or delete.
1534Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1535 SourceRange PlacementRange,
1536 CXXRecordDecl *NamingClass,
Sean Huntcb45a0f2011-05-12 22:46:25 +00001537 DeclAccessPair Found,
1538 bool Diagnose) {
John McCall90c8c572010-03-18 08:19:33 +00001539 if (!getLangOptions().AccessControl ||
1540 !NamingClass ||
John McCall9aa472c2010-03-19 07:35:19 +00001541 Found.getAccess() == AS_public)
John McCall90c8c572010-03-18 08:19:33 +00001542 return AR_accessible;
1543
John McCall161755a2010-04-06 21:38:20 +00001544 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1545 QualType());
Sean Huntcb45a0f2011-05-12 22:46:25 +00001546 if (Diagnose)
1547 Entity.setDiag(diag::err_access)
1548 << PlacementRange;
John McCall90c8c572010-03-18 08:19:33 +00001549
1550 return CheckAccess(*this, OpLoc, Entity);
1551}
1552
John McCallb13b7372010-02-01 03:16:54 +00001553/// Checks access to an overloaded member operator, including
1554/// conversion operators.
John McCall6b2accb2010-02-10 09:31:12 +00001555Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1556 Expr *ObjectExpr,
John McCall58e6f342010-03-16 05:22:47 +00001557 Expr *ArgExpr,
John McCall9aa472c2010-03-19 07:35:19 +00001558 DeclAccessPair Found) {
John McCall58e6f342010-03-16 05:22:47 +00001559 if (!getLangOptions().AccessControl ||
John McCall9aa472c2010-03-19 07:35:19 +00001560 Found.getAccess() == AS_public)
John McCall6b2accb2010-02-10 09:31:12 +00001561 return AR_accessible;
John McCall5357b612010-01-28 01:42:12 +00001562
John McCallca82a822011-09-21 08:36:56 +00001563 const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
John McCall5357b612010-01-28 01:42:12 +00001564 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1565
John McCall161755a2010-04-06 21:38:20 +00001566 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1567 ObjectExpr->getType());
John McCall58e6f342010-03-16 05:22:47 +00001568 Entity.setDiag(diag::err_access)
1569 << ObjectExpr->getSourceRange()
1570 << (ArgExpr ? ArgExpr->getSourceRange() : SourceRange());
1571
1572 return CheckAccess(*this, OpLoc, Entity);
John McCall6b2accb2010-02-10 09:31:12 +00001573}
John McCall5357b612010-01-28 01:42:12 +00001574
John McCall6bb80172010-03-30 21:47:33 +00001575Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1576 DeclAccessPair Found) {
1577 if (!getLangOptions().AccessControl ||
John McCalle2f5ba92010-03-30 22:20:00 +00001578 Found.getAccess() == AS_none ||
John McCall6bb80172010-03-30 21:47:33 +00001579 Found.getAccess() == AS_public)
1580 return AR_accessible;
1581
John McCall9c72c602010-08-27 09:08:28 +00001582 OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
John McCalle9ee23e2010-04-22 18:44:12 +00001583 CXXRecordDecl *NamingClass = Ovl->getNamingClass();
John McCall6bb80172010-03-30 21:47:33 +00001584
John McCall161755a2010-04-06 21:38:20 +00001585 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1586 Context.getTypeDeclType(NamingClass));
John McCall6bb80172010-03-30 21:47:33 +00001587 Entity.setDiag(diag::err_access)
1588 << Ovl->getSourceRange();
1589
1590 return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1591}
1592
John McCall6b2accb2010-02-10 09:31:12 +00001593/// Checks access for a hierarchy conversion.
1594///
1595/// \param IsBaseToDerived whether this is a base-to-derived conversion (true)
1596/// or a derived-to-base conversion (false)
1597/// \param ForceCheck true if this check should be performed even if access
1598/// control is disabled; some things rely on this for semantics
1599/// \param ForceUnprivileged true if this check should proceed as if the
1600/// context had no special privileges
1601/// \param ADK controls the kind of diagnostics that are used
1602Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
John McCall6b2accb2010-02-10 09:31:12 +00001603 QualType Base,
1604 QualType Derived,
1605 const CXXBasePath &Path,
John McCall58e6f342010-03-16 05:22:47 +00001606 unsigned DiagID,
John McCall6b2accb2010-02-10 09:31:12 +00001607 bool ForceCheck,
John McCall58e6f342010-03-16 05:22:47 +00001608 bool ForceUnprivileged) {
John McCall6b2accb2010-02-10 09:31:12 +00001609 if (!ForceCheck && !getLangOptions().AccessControl)
1610 return AR_accessible;
John McCall5357b612010-01-28 01:42:12 +00001611
John McCall6b2accb2010-02-10 09:31:12 +00001612 if (Path.Access == AS_public)
1613 return AR_accessible;
John McCall5357b612010-01-28 01:42:12 +00001614
John McCall6b2accb2010-02-10 09:31:12 +00001615 CXXRecordDecl *BaseD, *DerivedD;
1616 BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl());
1617 DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl());
John McCall58e6f342010-03-16 05:22:47 +00001618
John McCall161755a2010-04-06 21:38:20 +00001619 AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1620 Path.Access);
John McCall58e6f342010-03-16 05:22:47 +00001621 if (DiagID)
1622 Entity.setDiag(DiagID) << Derived << Base;
John McCall6b2accb2010-02-10 09:31:12 +00001623
John McCall161755a2010-04-06 21:38:20 +00001624 if (ForceUnprivileged) {
1625 switch (CheckEffectiveAccess(*this, EffectiveContext(),
1626 AccessLoc, Entity)) {
1627 case ::AR_accessible: return Sema::AR_accessible;
1628 case ::AR_inaccessible: return Sema::AR_inaccessible;
1629 case ::AR_dependent: return Sema::AR_dependent;
1630 }
1631 llvm_unreachable("unexpected result from CheckEffectiveAccess");
1632 }
John McCall58e6f342010-03-16 05:22:47 +00001633 return CheckAccess(*this, AccessLoc, Entity);
John McCall5357b612010-01-28 01:42:12 +00001634}
1635
John McCall92f88312010-01-23 00:46:32 +00001636/// Checks access to all the declarations in the given result set.
John McCall6b2accb2010-02-10 09:31:12 +00001637void Sema::CheckLookupAccess(const LookupResult &R) {
1638 assert(getLangOptions().AccessControl
1639 && "performing access check without access control");
1640 assert(R.getNamingClass() && "performing access check without naming class");
1641
John McCall58e6f342010-03-16 05:22:47 +00001642 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1643 if (I.getAccess() != AS_public) {
John McCall161755a2010-04-06 21:38:20 +00001644 AccessTarget Entity(Context, AccessedEntity::Member,
1645 R.getNamingClass(), I.getPair(),
Erik Verbruggen24dd9ad2011-09-19 15:10:40 +00001646 R.getBaseObjectType());
John McCall58e6f342010-03-16 05:22:47 +00001647 Entity.setDiag(diag::err_access);
John McCall58e6f342010-03-16 05:22:47 +00001648 CheckAccess(*this, R.getNameLoc(), Entity);
1649 }
1650 }
John McCall92f88312010-01-23 00:46:32 +00001651}
Chandler Carruth926c4b42010-06-28 08:39:25 +00001652
Erik Verbruggend1205962011-10-06 07:27:49 +00001653/// Checks access to Decl from the given class. The check will take access
1654/// specifiers into account, but no member access expressions and such.
1655///
1656/// \param Decl the declaration to check if it can be accessed
1657/// \param Class the class/context from which to start the search
1658/// \return true if the Decl is accessible from the Class, false otherwise.
Douglas Gregor17015ef2011-11-03 16:51:37 +00001659bool Sema::IsSimplyAccessible(NamedDecl *Decl, DeclContext *Ctx) {
1660 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) {
Douglas Gregora885dce2011-11-03 17:41:55 +00001661 if (!Decl->isCXXClassMember())
Douglas Gregor17015ef2011-11-03 16:51:37 +00001662 return true;
Erik Verbruggend1205962011-10-06 07:27:49 +00001663
Douglas Gregor17015ef2011-11-03 16:51:37 +00001664 QualType qType = Class->getTypeForDecl()->getCanonicalTypeInternal();
1665 AccessTarget Entity(Context, AccessedEntity::Member, Class,
1666 DeclAccessPair::make(Decl, Decl->getAccess()),
1667 qType);
1668 if (Entity.getAccess() == AS_public)
1669 return true;
Erik Verbruggend1205962011-10-06 07:27:49 +00001670
Douglas Gregor17015ef2011-11-03 16:51:37 +00001671 EffectiveContext EC(CurContext);
1672 return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1673 }
1674
Douglas Gregorf3c02862011-11-03 19:00:24 +00001675 if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Decl)) {
1676 // @public and @package ivars are always accessible.
1677 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1678 Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
1679 return true;
1680
1681
1682
1683 // If we are inside a class or category implementation, determine the
1684 // interface we're in.
1685 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1686 if (ObjCMethodDecl *MD = getCurMethodDecl())
1687 ClassOfMethodDecl = MD->getClassInterface();
1688 else if (FunctionDecl *FD = getCurFunctionDecl()) {
1689 if (ObjCImplDecl *Impl
1690 = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1691 if (ObjCImplementationDecl *IMPD
1692 = dyn_cast<ObjCImplementationDecl>(Impl))
1693 ClassOfMethodDecl = IMPD->getClassInterface();
1694 else if (ObjCCategoryImplDecl* CatImplClass
1695 = dyn_cast<ObjCCategoryImplDecl>(Impl))
1696 ClassOfMethodDecl = CatImplClass->getClassInterface();
1697 }
1698 }
1699
1700 // If we're not in an interface, this ivar is inaccessible.
1701 if (!ClassOfMethodDecl)
1702 return false;
1703
1704 // If we're inside the same interface that owns the ivar, we're fine.
Douglas Gregor60ef3082011-12-15 00:29:59 +00001705 if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
Douglas Gregorf3c02862011-11-03 19:00:24 +00001706 return true;
1707
1708 // If the ivar is private, it's inaccessible.
1709 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1710 return false;
1711
1712 return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1713 }
1714
Douglas Gregor17015ef2011-11-03 16:51:37 +00001715 return true;
Erik Verbruggend1205962011-10-06 07:27:49 +00001716}
1717
Chandler Carruth926c4b42010-06-28 08:39:25 +00001718void Sema::ActOnStartSuppressingAccessChecks() {
1719 assert(!SuppressAccessChecking &&
1720 "Tried to start access check suppression when already started.");
1721 SuppressAccessChecking = true;
1722}
1723
1724void Sema::ActOnStopSuppressingAccessChecks() {
1725 assert(SuppressAccessChecking &&
1726 "Tried to stop access check suprression when already stopped.");
1727 SuppressAccessChecking = false;
1728}