blob: c00ad81b097124e1dc12f70130faf2410b2ef95a [file] [log] [blame]
Anders Carlsson4742a9c2009-03-27 05:05:05 +00001//===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
Anders Carlsson8ed6f362009-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 Carlsson17941122009-03-27 04:54:36 +000013
John McCall83024632010-08-25 22:03:47 +000014#include "clang/Sema/SemaInternal.h"
Anders Carlsson733d77f2009-03-27 06:03:27 +000015#include "clang/AST/ASTContext.h"
Douglas Gregor36d1b142009-10-06 17:59:45 +000016#include "clang/AST/CXXInheritance.h"
17#include "clang/AST/DeclCXX.h"
John McCall16927f62010-03-12 01:19:31 +000018#include "clang/AST/DeclFriend.h"
Douglas Gregor21ceb182011-11-03 19:00:24 +000019#include "clang/AST/DeclObjC.h"
John McCallc62bb642010-03-24 05:22:00 +000020#include "clang/AST/DependentDiagnostic.h"
John McCall58cc69d2010-01-27 01:50:18 +000021#include "clang/AST/ExprCXX.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "clang/Sema/DelayedDiagnostic.h"
23#include "clang/Sema/Initialization.h"
24#include "clang/Sema/Lookup.h"
John McCall58cc69d2010-01-27 01:50:18 +000025
Anders Carlsson17941122009-03-27 04:54:36 +000026using namespace clang;
John McCallb45a1e72010-08-26 02:13:20 +000027using namespace sema;
Anders Carlsson17941122009-03-27 04:54:36 +000028
John McCalla8ae2222010-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 Carlsson4742a9c2009-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 Stump11289f42009-09-09 15:08:12 +000039bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
Anders Carlsson17941122009-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 Stump11289f42009-09-09 15:08:12 +000047
Anders Carlsson17941122009-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 Stump11289f42009-09-09 15:08:12 +000051 Diag(MemberDecl->getLocation(),
52 diag::err_class_redeclared_with_different_access)
Anders Carlsson17941122009-03-27 04:54:36 +000053 << MemberDecl << LexicalAS;
54 Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
55 << PrevMemberDecl << PrevMemberDecl->getAccess();
John McCall0a4bb262009-12-23 00:37:40 +000056
57 MemberDecl->setAccess(LexicalAS);
Anders Carlsson17941122009-03-27 04:54:36 +000058 return true;
59 }
Mike Stump11289f42009-09-09 15:08:12 +000060
Anders Carlsson17941122009-03-27 04:54:36 +000061 MemberDecl->setAccess(PrevMemberDecl->getAccess());
62 return false;
63}
Anders Carlsson4742a9c2009-03-27 05:05:05 +000064
John McCalla8ae2222010-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 McCall5b0829a2010-02-10 09:31:12 +000079namespace {
80struct EffectiveContext {
John McCall3dc81f72010-03-27 06:55:49 +000081 EffectiveContext() : Inner(0), Dependent(false) {}
Anders Carlsson733d77f2009-03-27 06:03:27 +000082
John McCall816d75b2010-03-24 07:46:06 +000083 explicit EffectiveContext(DeclContext *DC)
84 : Inner(DC),
85 Dependent(DC->isDependentContext()) {
John McCallc62bb642010-03-24 05:22:00 +000086
Richard Smithad5c1ca2013-04-29 10:13:55 +000087 // C++11 [class.access.nest]p1:
John McCallfb803d72010-03-17 04:58:56 +000088 // A nested class is a member and as such has the same access
89 // rights as any other member.
Richard Smithad5c1ca2013-04-29 10:13:55 +000090 // C++11 [class.access]p2:
John McCallfb803d72010-03-17 04:58:56 +000091 // A member of a class can also access all the names to which
John McCall3dc81f72010-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) {
John McCalle91aec72012-08-24 22:54:02 +0000100 // We want to add canonical declarations to the EC lists for
101 // simplicity of checking, but we need to walk up through the
102 // actual current DC chain. Otherwise, something like a local
103 // extern or friend which happens to be the canonical
104 // declaration will really mess us up.
105
John McCall3dc81f72010-03-27 06:55:49 +0000106 if (isa<CXXRecordDecl>(DC)) {
John McCalle91aec72012-08-24 22:54:02 +0000107 CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
108 Records.push_back(Record->getCanonicalDecl());
John McCall3dc81f72010-03-27 06:55:49 +0000109 DC = Record->getDeclContext();
110 } else if (isa<FunctionDecl>(DC)) {
John McCalle91aec72012-08-24 22:54:02 +0000111 FunctionDecl *Function = cast<FunctionDecl>(DC);
112 Functions.push_back(Function->getCanonicalDecl());
Douglas Gregor56636582011-10-09 22:38:36 +0000113 if (Function->getFriendObjectKind())
114 DC = Function->getLexicalDeclContext();
115 else
116 DC = Function->getDeclContext();
John McCall3dc81f72010-03-27 06:55:49 +0000117 } else if (DC->isFileContext()) {
118 break;
119 } else {
120 DC = DC->getParent();
121 }
John McCallfb803d72010-03-17 04:58:56 +0000122 }
Anders Carlsson733d77f2009-03-27 06:03:27 +0000123 }
Sebastian Redle644e192009-07-18 14:32:15 +0000124
John McCallc62bb642010-03-24 05:22:00 +0000125 bool isDependent() const { return Dependent; }
126
John McCallfb803d72010-03-17 04:58:56 +0000127 bool includesClass(const CXXRecordDecl *R) const {
128 R = R->getCanonicalDecl();
129 return std::find(Records.begin(), Records.end(), R)
130 != Records.end();
John McCall5b0829a2010-02-10 09:31:12 +0000131 }
132
John McCall816d75b2010-03-24 07:46:06 +0000133 /// Retrieves the innermost "useful" context. Can be null if we're
134 /// doing access-control without privileges.
135 DeclContext *getInnerContext() const {
136 return Inner;
John McCallc62bb642010-03-24 05:22:00 +0000137 }
138
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000139 typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
John McCallc62bb642010-03-24 05:22:00 +0000140
John McCall816d75b2010-03-24 07:46:06 +0000141 DeclContext *Inner;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000142 SmallVector<FunctionDecl*, 4> Functions;
143 SmallVector<CXXRecordDecl*, 4> Records;
John McCallc62bb642010-03-24 05:22:00 +0000144 bool Dependent;
John McCall5b0829a2010-02-10 09:31:12 +0000145};
John McCalla8ae2222010-04-06 21:38:20 +0000146
Nico Weber20c9f1d2010-11-28 22:53:37 +0000147/// Like sema::AccessedEntity, but kindly lets us scribble all over
John McCalla8ae2222010-04-06 21:38:20 +0000148/// it.
John McCallb45a1e72010-08-26 02:13:20 +0000149struct AccessTarget : public AccessedEntity {
150 AccessTarget(const AccessedEntity &Entity)
John McCalla8ae2222010-04-06 21:38:20 +0000151 : AccessedEntity(Entity) {
152 initialize();
153 }
154
155 AccessTarget(ASTContext &Context,
156 MemberNonce _,
157 CXXRecordDecl *NamingClass,
158 DeclAccessPair FoundDecl,
Erik Verbruggen631dfc62011-09-19 15:10:40 +0000159 QualType BaseObjectType)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000160 : AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
161 FoundDecl, BaseObjectType) {
John McCalla8ae2222010-04-06 21:38:20 +0000162 initialize();
163 }
164
165 AccessTarget(ASTContext &Context,
166 BaseNonce _,
167 CXXRecordDecl *BaseClass,
168 CXXRecordDecl *DerivedClass,
169 AccessSpecifier Access)
Benjamin Kramer1ea8e092012-07-04 17:04:04 +0000170 : AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
171 Access) {
John McCalla8ae2222010-04-06 21:38:20 +0000172 initialize();
173 }
174
John McCall5dadb652012-04-07 03:04:20 +0000175 bool isInstanceMember() const {
176 return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
177 }
178
John McCalla8ae2222010-04-06 21:38:20 +0000179 bool hasInstanceContext() const {
180 return HasInstanceContext;
181 }
182
183 class SavedInstanceContext {
184 public:
185 ~SavedInstanceContext() {
186 Target.HasInstanceContext = Has;
187 }
188
189 private:
John McCall8e36d532010-04-07 00:41:46 +0000190 friend struct AccessTarget;
John McCalla8ae2222010-04-06 21:38:20 +0000191 explicit SavedInstanceContext(AccessTarget &Target)
192 : Target(Target), Has(Target.HasInstanceContext) {}
193 AccessTarget &Target;
194 bool Has;
195 };
196
197 SavedInstanceContext saveInstanceContext() {
198 return SavedInstanceContext(*this);
199 }
200
201 void suppressInstanceContext() {
202 HasInstanceContext = false;
203 }
204
205 const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
206 assert(HasInstanceContext);
207 if (CalculatedInstanceContext)
208 return InstanceContext;
209
210 CalculatedInstanceContext = true;
211 DeclContext *IC = S.computeDeclContext(getBaseObjectType());
212 InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl() : 0);
213 return InstanceContext;
214 }
215
216 const CXXRecordDecl *getDeclaringClass() const {
217 return DeclaringClass;
218 }
219
John McCalld010ac92013-02-27 00:08:19 +0000220 /// The "effective" naming class is the canonical non-anonymous
221 /// class containing the actual naming class.
222 const CXXRecordDecl *getEffectiveNamingClass() const {
223 const CXXRecordDecl *namingClass = getNamingClass();
224 while (namingClass->isAnonymousStructOrUnion())
225 namingClass = cast<CXXRecordDecl>(namingClass->getParent());
226 return namingClass->getCanonicalDecl();
227 }
228
John McCalla8ae2222010-04-06 21:38:20 +0000229private:
230 void initialize() {
231 HasInstanceContext = (isMemberAccess() &&
232 !getBaseObjectType().isNull() &&
233 getTargetDecl()->isCXXInstanceMember());
234 CalculatedInstanceContext = false;
235 InstanceContext = 0;
236
237 if (isMemberAccess())
238 DeclaringClass = FindDeclaringClass(getTargetDecl());
239 else
240 DeclaringClass = getBaseClass();
241 DeclaringClass = DeclaringClass->getCanonicalDecl();
242 }
243
244 bool HasInstanceContext : 1;
245 mutable bool CalculatedInstanceContext : 1;
246 mutable const CXXRecordDecl *InstanceContext;
247 const CXXRecordDecl *DeclaringClass;
248};
249
Anders Carlsson4742a9c2009-03-27 05:05:05 +0000250}
John McCall553c0792010-01-23 00:46:32 +0000251
John McCall97205142010-05-04 05:11:27 +0000252/// Checks whether one class might instantiate to the other.
253static bool MightInstantiateTo(const CXXRecordDecl *From,
254 const CXXRecordDecl *To) {
255 // Declaration names are always preserved by instantiation.
256 if (From->getDeclName() != To->getDeclName())
257 return false;
258
259 const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
260 const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
261 if (FromDC == ToDC) return true;
262 if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
263
264 // Be conservative.
265 return true;
266}
267
John McCalla8ae2222010-04-06 21:38:20 +0000268/// Checks whether one class is derived from another, inclusively.
269/// Properly indicates when it couldn't be determined due to
270/// dependence.
271///
272/// This should probably be donated to AST or at least Sema.
273static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
274 const CXXRecordDecl *Target) {
275 assert(Derived->getCanonicalDecl() == Derived);
276 assert(Target->getCanonicalDecl() == Target);
John McCall69f75862010-03-24 09:04:37 +0000277
John McCalla8ae2222010-04-06 21:38:20 +0000278 if (Derived == Target) return AR_accessible;
John McCall69f75862010-03-24 09:04:37 +0000279
John McCall97205142010-05-04 05:11:27 +0000280 bool CheckDependent = Derived->isDependentContext();
281 if (CheckDependent && MightInstantiateTo(Derived, Target))
282 return AR_dependent;
283
John McCalla8ae2222010-04-06 21:38:20 +0000284 AccessResult OnFailure = AR_inaccessible;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000285 SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
John McCalla8ae2222010-04-06 21:38:20 +0000286
287 while (true) {
Douglas Gregor0201a4c2011-11-14 23:00:43 +0000288 if (Derived->isDependentContext() && !Derived->hasDefinition())
289 return AR_dependent;
290
John McCalla8ae2222010-04-06 21:38:20 +0000291 for (CXXRecordDecl::base_class_const_iterator
292 I = Derived->bases_begin(), E = Derived->bases_end(); I != E; ++I) {
293
294 const CXXRecordDecl *RD;
295
296 QualType T = I->getType();
297 if (const RecordType *RT = T->getAs<RecordType>()) {
298 RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall97205142010-05-04 05:11:27 +0000299 } else if (const InjectedClassNameType *IT
300 = T->getAs<InjectedClassNameType>()) {
301 RD = IT->getDecl();
John McCalla8ae2222010-04-06 21:38:20 +0000302 } else {
John McCalla8ae2222010-04-06 21:38:20 +0000303 assert(T->isDependentType() && "non-dependent base wasn't a record?");
304 OnFailure = AR_dependent;
305 continue;
306 }
307
308 RD = RD->getCanonicalDecl();
309 if (RD == Target) return AR_accessible;
John McCall97205142010-05-04 05:11:27 +0000310 if (CheckDependent && MightInstantiateTo(RD, Target))
311 OnFailure = AR_dependent;
312
John McCalla8ae2222010-04-06 21:38:20 +0000313 Queue.push_back(RD);
314 }
315
316 if (Queue.empty()) break;
317
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000318 Derived = Queue.pop_back_val();
John McCalla8ae2222010-04-06 21:38:20 +0000319 }
320
321 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000322}
323
John McCalla8ae2222010-04-06 21:38:20 +0000324
John McCallc62bb642010-03-24 05:22:00 +0000325static bool MightInstantiateTo(Sema &S, DeclContext *Context,
326 DeclContext *Friend) {
327 if (Friend == Context)
328 return true;
329
330 assert(!Friend->isDependentContext() &&
331 "can't handle friends with dependent contexts here");
332
333 if (!Context->isDependentContext())
334 return false;
335
336 if (Friend->isFileContext())
337 return false;
338
339 // TODO: this is very conservative
340 return true;
341}
342
343// Asks whether the type in 'context' can ever instantiate to the type
344// in 'friend'.
345static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
346 if (Friend == Context)
347 return true;
348
349 if (!Friend->isDependentType() && !Context->isDependentType())
350 return false;
351
352 // TODO: this is very conservative.
353 return true;
354}
355
356static bool MightInstantiateTo(Sema &S,
357 FunctionDecl *Context,
358 FunctionDecl *Friend) {
359 if (Context->getDeclName() != Friend->getDeclName())
360 return false;
361
362 if (!MightInstantiateTo(S,
363 Context->getDeclContext(),
364 Friend->getDeclContext()))
365 return false;
366
367 CanQual<FunctionProtoType> FriendTy
368 = S.Context.getCanonicalType(Friend->getType())
369 ->getAs<FunctionProtoType>();
370 CanQual<FunctionProtoType> ContextTy
371 = S.Context.getCanonicalType(Context->getType())
372 ->getAs<FunctionProtoType>();
373
374 // There isn't any way that I know of to add qualifiers
375 // during instantiation.
376 if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
377 return false;
378
Alp Toker9cacbab2014-01-20 20:26:09 +0000379 if (FriendTy->getNumParams() != ContextTy->getNumParams())
John McCallc62bb642010-03-24 05:22:00 +0000380 return false;
381
382 if (!MightInstantiateTo(S,
383 ContextTy->getResultType(),
384 FriendTy->getResultType()))
385 return false;
386
Alp Toker9cacbab2014-01-20 20:26:09 +0000387 for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
388 if (!MightInstantiateTo(S, ContextTy->getParamType(I),
389 FriendTy->getParamType(I)))
John McCallc62bb642010-03-24 05:22:00 +0000390 return false;
391
392 return true;
393}
394
395static bool MightInstantiateTo(Sema &S,
396 FunctionTemplateDecl *Context,
397 FunctionTemplateDecl *Friend) {
398 return MightInstantiateTo(S,
399 Context->getTemplatedDecl(),
400 Friend->getTemplatedDecl());
401}
402
John McCalla8ae2222010-04-06 21:38:20 +0000403static AccessResult MatchesFriend(Sema &S,
404 const EffectiveContext &EC,
405 const CXXRecordDecl *Friend) {
John McCall39e82882010-03-17 20:01:29 +0000406 if (EC.includesClass(Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000407 return AR_accessible;
John McCall39e82882010-03-17 20:01:29 +0000408
John McCallc62bb642010-03-24 05:22:00 +0000409 if (EC.isDependent()) {
410 CanQualType FriendTy
411 = S.Context.getCanonicalType(S.Context.getTypeDeclType(Friend));
412
413 for (EffectiveContext::record_iterator
414 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
415 CanQualType ContextTy
416 = S.Context.getCanonicalType(S.Context.getTypeDeclType(*I));
417 if (MightInstantiateTo(S, ContextTy, FriendTy))
John McCalla8ae2222010-04-06 21:38:20 +0000418 return AR_dependent;
John McCallc62bb642010-03-24 05:22:00 +0000419 }
420 }
421
John McCalla8ae2222010-04-06 21:38:20 +0000422 return AR_inaccessible;
John McCall39e82882010-03-17 20:01:29 +0000423}
424
John McCalla8ae2222010-04-06 21:38:20 +0000425static AccessResult MatchesFriend(Sema &S,
426 const EffectiveContext &EC,
427 CanQualType Friend) {
John McCallc62bb642010-03-24 05:22:00 +0000428 if (const RecordType *RT = Friend->getAs<RecordType>())
429 return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
John McCall39e82882010-03-17 20:01:29 +0000430
John McCallc62bb642010-03-24 05:22:00 +0000431 // TODO: we can do better than this
432 if (Friend->isDependentType())
John McCalla8ae2222010-04-06 21:38:20 +0000433 return AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000434
John McCalla8ae2222010-04-06 21:38:20 +0000435 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000436}
437
438/// Determines whether the given friend class template matches
439/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000440static AccessResult MatchesFriend(Sema &S,
441 const EffectiveContext &EC,
442 ClassTemplateDecl *Friend) {
443 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000444
John McCall598b4402010-03-25 06:39:04 +0000445 // Check whether the friend is the template of a class in the
446 // context chain.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000447 for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
John McCallc62bb642010-03-24 05:22:00 +0000448 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
449 CXXRecordDecl *Record = *I;
450
John McCall598b4402010-03-25 06:39:04 +0000451 // Figure out whether the current class has a template:
John McCallc62bb642010-03-24 05:22:00 +0000452 ClassTemplateDecl *CTD;
453
454 // A specialization of the template...
455 if (isa<ClassTemplateSpecializationDecl>(Record)) {
456 CTD = cast<ClassTemplateSpecializationDecl>(Record)
457 ->getSpecializedTemplate();
458
459 // ... or the template pattern itself.
460 } else {
461 CTD = Record->getDescribedClassTemplate();
462 if (!CTD) continue;
463 }
464
465 // It's a match.
466 if (Friend == CTD->getCanonicalDecl())
John McCalla8ae2222010-04-06 21:38:20 +0000467 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000468
John McCall598b4402010-03-25 06:39:04 +0000469 // If the context isn't dependent, it can't be a dependent match.
470 if (!EC.isDependent())
471 continue;
472
John McCallc62bb642010-03-24 05:22:00 +0000473 // If the template names don't match, it can't be a dependent
Richard Smith3f1b5d02011-05-05 21:57:07 +0000474 // match.
475 if (CTD->getDeclName() != Friend->getDeclName())
John McCallc62bb642010-03-24 05:22:00 +0000476 continue;
477
478 // If the class's context can't instantiate to the friend's
479 // context, it can't be a dependent match.
480 if (!MightInstantiateTo(S, CTD->getDeclContext(),
481 Friend->getDeclContext()))
482 continue;
483
484 // Otherwise, it's a dependent match.
John McCalla8ae2222010-04-06 21:38:20 +0000485 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000486 }
487
John McCallc62bb642010-03-24 05:22:00 +0000488 return OnFailure;
489}
490
491/// Determines whether the given friend function matches anything in
492/// the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000493static AccessResult MatchesFriend(Sema &S,
494 const EffectiveContext &EC,
495 FunctionDecl *Friend) {
496 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000497
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000498 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000499 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
500 if (Friend == *I)
John McCalla8ae2222010-04-06 21:38:20 +0000501 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000502
John McCall3dc81f72010-03-27 06:55:49 +0000503 if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000504 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000505 }
John McCallc62bb642010-03-24 05:22:00 +0000506
John McCall3dc81f72010-03-27 06:55:49 +0000507 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000508}
509
510/// Determines whether the given friend function template matches
511/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000512static AccessResult MatchesFriend(Sema &S,
513 const EffectiveContext &EC,
514 FunctionTemplateDecl *Friend) {
515 if (EC.Functions.empty()) return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000516
John McCalla8ae2222010-04-06 21:38:20 +0000517 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000518
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000519 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000520 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
John McCallc62bb642010-03-24 05:22:00 +0000521
John McCall3dc81f72010-03-27 06:55:49 +0000522 FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
523 if (!FTD)
524 FTD = (*I)->getDescribedFunctionTemplate();
525 if (!FTD)
526 continue;
John McCallc62bb642010-03-24 05:22:00 +0000527
John McCall3dc81f72010-03-27 06:55:49 +0000528 FTD = FTD->getCanonicalDecl();
529
530 if (Friend == FTD)
John McCalla8ae2222010-04-06 21:38:20 +0000531 return AR_accessible;
John McCall3dc81f72010-03-27 06:55:49 +0000532
533 if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000534 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000535 }
536
537 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000538}
539
540/// Determines whether the given friend declaration matches anything
541/// in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000542static AccessResult MatchesFriend(Sema &S,
543 const EffectiveContext &EC,
544 FriendDecl *FriendD) {
John McCall2c2eb122010-10-16 06:59:13 +0000545 // Whitelist accesses if there's an invalid or unsupported friend
546 // declaration.
547 if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
John McCallde3fd222010-10-12 23:13:28 +0000548 return AR_accessible;
549
John McCall15ad0962010-03-25 18:04:51 +0000550 if (TypeSourceInfo *T = FriendD->getFriendType())
551 return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
John McCallc62bb642010-03-24 05:22:00 +0000552
553 NamedDecl *Friend
554 = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
John McCall39e82882010-03-17 20:01:29 +0000555
556 // FIXME: declarations with dependent or templated scope.
557
John McCallc62bb642010-03-24 05:22:00 +0000558 if (isa<ClassTemplateDecl>(Friend))
559 return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000560
John McCallc62bb642010-03-24 05:22:00 +0000561 if (isa<FunctionTemplateDecl>(Friend))
562 return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000563
John McCallc62bb642010-03-24 05:22:00 +0000564 if (isa<CXXRecordDecl>(Friend))
565 return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000566
John McCallc62bb642010-03-24 05:22:00 +0000567 assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
568 return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000569}
570
John McCalla8ae2222010-04-06 21:38:20 +0000571static AccessResult GetFriendKind(Sema &S,
572 const EffectiveContext &EC,
573 const CXXRecordDecl *Class) {
574 AccessResult OnFailure = AR_inaccessible;
John McCallfb803d72010-03-17 04:58:56 +0000575
John McCall16927f62010-03-12 01:19:31 +0000576 // Okay, check friends.
577 for (CXXRecordDecl::friend_iterator I = Class->friend_begin(),
578 E = Class->friend_end(); I != E; ++I) {
579 FriendDecl *Friend = *I;
580
John McCall39e82882010-03-17 20:01:29 +0000581 switch (MatchesFriend(S, EC, Friend)) {
John McCalla8ae2222010-04-06 21:38:20 +0000582 case AR_accessible:
583 return AR_accessible;
John McCall16927f62010-03-12 01:19:31 +0000584
John McCalla8ae2222010-04-06 21:38:20 +0000585 case AR_inaccessible:
586 continue;
587
588 case AR_dependent:
589 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000590 break;
John McCall16927f62010-03-12 01:19:31 +0000591 }
John McCall16927f62010-03-12 01:19:31 +0000592 }
593
594 // That's it, give up.
John McCallfb803d72010-03-17 04:58:56 +0000595 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000596}
597
John McCall96329672010-08-28 07:56:00 +0000598namespace {
599
600/// A helper class for checking for a friend which will grant access
601/// to a protected instance member.
602struct ProtectedFriendContext {
603 Sema &S;
604 const EffectiveContext &EC;
605 const CXXRecordDecl *NamingClass;
606 bool CheckDependent;
607 bool EverDependent;
608
609 /// The path down to the current base class.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000610 SmallVector<const CXXRecordDecl*, 20> CurPath;
John McCall96329672010-08-28 07:56:00 +0000611
612 ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
613 const CXXRecordDecl *InstanceContext,
614 const CXXRecordDecl *NamingClass)
615 : S(S), EC(EC), NamingClass(NamingClass),
616 CheckDependent(InstanceContext->isDependentContext() ||
617 NamingClass->isDependentContext()),
618 EverDependent(false) {}
619
John McCall1177ff12010-08-28 08:47:21 +0000620 /// Check classes in the current path for friendship, starting at
621 /// the given index.
622 bool checkFriendshipAlongPath(unsigned I) {
623 assert(I < CurPath.size());
624 for (unsigned E = CurPath.size(); I != E; ++I) {
625 switch (GetFriendKind(S, EC, CurPath[I])) {
John McCall96329672010-08-28 07:56:00 +0000626 case AR_accessible: return true;
627 case AR_inaccessible: continue;
628 case AR_dependent: EverDependent = true; continue;
629 }
630 }
631 return false;
632 }
633
634 /// Perform a search starting at the given class.
John McCall1177ff12010-08-28 08:47:21 +0000635 ///
636 /// PrivateDepth is the index of the last (least derived) class
637 /// along the current path such that a notional public member of
638 /// the final class in the path would have access in that class.
639 bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
John McCall96329672010-08-28 07:56:00 +0000640 // If we ever reach the naming class, check the current path for
641 // friendship. We can also stop recursing because we obviously
642 // won't find the naming class there again.
John McCall1177ff12010-08-28 08:47:21 +0000643 if (Cur == NamingClass)
644 return checkFriendshipAlongPath(PrivateDepth);
John McCall96329672010-08-28 07:56:00 +0000645
646 if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
647 EverDependent = true;
648
649 // Recurse into the base classes.
650 for (CXXRecordDecl::base_class_const_iterator
651 I = Cur->bases_begin(), E = Cur->bases_end(); I != E; ++I) {
652
John McCall1177ff12010-08-28 08:47:21 +0000653 // If this is private inheritance, then a public member of the
654 // base will not have any access in classes derived from Cur.
655 unsigned BasePrivateDepth = PrivateDepth;
656 if (I->getAccessSpecifier() == AS_private)
657 BasePrivateDepth = CurPath.size() - 1;
John McCall96329672010-08-28 07:56:00 +0000658
659 const CXXRecordDecl *RD;
660
661 QualType T = I->getType();
662 if (const RecordType *RT = T->getAs<RecordType>()) {
663 RD = cast<CXXRecordDecl>(RT->getDecl());
664 } else if (const InjectedClassNameType *IT
665 = T->getAs<InjectedClassNameType>()) {
666 RD = IT->getDecl();
667 } else {
668 assert(T->isDependentType() && "non-dependent base wasn't a record?");
669 EverDependent = true;
670 continue;
671 }
672
673 // Recurse. We don't need to clean up if this returns true.
John McCall1177ff12010-08-28 08:47:21 +0000674 CurPath.push_back(RD);
675 if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
676 return true;
677 CurPath.pop_back();
John McCall96329672010-08-28 07:56:00 +0000678 }
679
John McCall96329672010-08-28 07:56:00 +0000680 return false;
681 }
John McCall1177ff12010-08-28 08:47:21 +0000682
683 bool findFriendship(const CXXRecordDecl *Cur) {
684 assert(CurPath.empty());
685 CurPath.push_back(Cur);
686 return findFriendship(Cur, 0);
687 }
John McCall96329672010-08-28 07:56:00 +0000688};
689}
690
691/// Search for a class P that EC is a friend of, under the constraint
John McCall5dadb652012-04-07 03:04:20 +0000692/// InstanceContext <= P
693/// if InstanceContext exists, or else
694/// NamingClass <= P
John McCall96329672010-08-28 07:56:00 +0000695/// and with the additional restriction that a protected member of
John McCall5dadb652012-04-07 03:04:20 +0000696/// NamingClass would have some natural access in P, which implicitly
697/// imposes the constraint that P <= NamingClass.
John McCall96329672010-08-28 07:56:00 +0000698///
John McCall5dadb652012-04-07 03:04:20 +0000699/// This isn't quite the condition laid out in the standard.
700/// Instead of saying that a notional protected member of NamingClass
701/// would have to have some natural access in P, it says the actual
702/// target has to have some natural access in P, which opens up the
703/// possibility that the target (which is not necessarily a member
704/// of NamingClass) might be more accessible along some path not
705/// passing through it. That's really a bad idea, though, because it
John McCall96329672010-08-28 07:56:00 +0000706/// introduces two problems:
John McCall5dadb652012-04-07 03:04:20 +0000707/// - Most importantly, it breaks encapsulation because you can
708/// access a forbidden base class's members by directly subclassing
709/// it elsewhere.
710/// - It also makes access substantially harder to compute because it
John McCall96329672010-08-28 07:56:00 +0000711/// breaks the hill-climbing algorithm: knowing that the target is
712/// accessible in some base class would no longer let you change
713/// the question solely to whether the base class is accessible,
714/// because the original target might have been more accessible
715/// because of crazy subclassing.
716/// So we don't implement that.
717static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
718 const CXXRecordDecl *InstanceContext,
719 const CXXRecordDecl *NamingClass) {
John McCall5dadb652012-04-07 03:04:20 +0000720 assert(InstanceContext == 0 ||
721 InstanceContext->getCanonicalDecl() == InstanceContext);
John McCall96329672010-08-28 07:56:00 +0000722 assert(NamingClass->getCanonicalDecl() == NamingClass);
723
John McCall5dadb652012-04-07 03:04:20 +0000724 // If we don't have an instance context, our constraints give us
725 // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
726 // This is just the usual friendship check.
727 if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
728
John McCall96329672010-08-28 07:56:00 +0000729 ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
730 if (PRC.findFriendship(InstanceContext)) return AR_accessible;
731 if (PRC.EverDependent) return AR_dependent;
732 return AR_inaccessible;
733}
734
John McCalla8ae2222010-04-06 21:38:20 +0000735static AccessResult HasAccess(Sema &S,
736 const EffectiveContext &EC,
737 const CXXRecordDecl *NamingClass,
738 AccessSpecifier Access,
739 const AccessTarget &Target) {
John McCalld79b4d82010-04-02 00:03:43 +0000740 assert(NamingClass->getCanonicalDecl() == NamingClass &&
741 "declaration should be canonicalized before being passed here");
742
John McCalla8ae2222010-04-06 21:38:20 +0000743 if (Access == AS_public) return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000744 assert(Access == AS_private || Access == AS_protected);
745
John McCalla8ae2222010-04-06 21:38:20 +0000746 AccessResult OnFailure = AR_inaccessible;
747
John McCalld79b4d82010-04-02 00:03:43 +0000748 for (EffectiveContext::record_iterator
749 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
750 // All the declarations in EC have been canonicalized, so pointer
751 // equality from this point on will work fine.
752 const CXXRecordDecl *ECRecord = *I;
753
754 // [B2] and [M2]
John McCalla8ae2222010-04-06 21:38:20 +0000755 if (Access == AS_private) {
756 if (ECRecord == NamingClass)
757 return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000758
John McCall97205142010-05-04 05:11:27 +0000759 if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
760 OnFailure = AR_dependent;
761
John McCalld79b4d82010-04-02 00:03:43 +0000762 // [B3] and [M3]
John McCalla8ae2222010-04-06 21:38:20 +0000763 } else {
764 assert(Access == AS_protected);
765 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
766 case AR_accessible: break;
767 case AR_inaccessible: continue;
768 case AR_dependent: OnFailure = AR_dependent; continue;
769 }
770
John McCalla8ae2222010-04-06 21:38:20 +0000771 // C++ [class.protected]p1:
772 // An additional access check beyond those described earlier in
773 // [class.access] is applied when a non-static data member or
774 // non-static member function is a protected member of its naming
775 // class. As described earlier, access to a protected member is
776 // granted because the reference occurs in a friend or member of
777 // some class C. If the access is to form a pointer to member,
778 // the nested-name-specifier shall name C or a class derived from
779 // C. All other accesses involve a (possibly implicit) object
780 // expression. In this case, the class of the object expression
781 // shall be C or a class derived from C.
782 //
John McCall5dadb652012-04-07 03:04:20 +0000783 // We interpret this as a restriction on [M3].
784
785 // In this part of the code, 'C' is just our context class ECRecord.
786
787 // These rules are different if we don't have an instance context.
788 if (!Target.hasInstanceContext()) {
789 // If it's not an instance member, these restrictions don't apply.
790 if (!Target.isInstanceMember()) return AR_accessible;
791
792 // If it's an instance member, use the pointer-to-member rule
793 // that the naming class has to be derived from the effective
794 // context.
795
Francois Picheta39371c2012-04-17 12:35:05 +0000796 // Emulate a MSVC bug where the creation of pointer-to-member
797 // to protected member of base class is allowed but only from
Francois Pichet52d38982012-04-19 07:48:57 +0000798 // static member functions.
Alp Tokerbfa39342014-01-14 12:51:41 +0000799 if (S.getLangOpts().MSVCCompat && !EC.Functions.empty())
Francois Pichet5b061f02012-04-18 03:24:38 +0000800 if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
801 if (MD->isStatic()) return AR_accessible;
Francois Picheta39371c2012-04-17 12:35:05 +0000802
John McCall5dadb652012-04-07 03:04:20 +0000803 // Despite the standard's confident wording, there is a case
804 // where you can have an instance member that's neither in a
805 // pointer-to-member expression nor in a member access: when
806 // it names a field in an unevaluated context that can't be an
807 // implicit member. Pending clarification, we just apply the
808 // same naming-class restriction here.
809 // FIXME: we're probably not correctly adding the
810 // protected-member restriction when we retroactively convert
811 // an expression to being evaluated.
812
813 // We know that ECRecord derives from NamingClass. The
814 // restriction says to check whether NamingClass derives from
815 // ECRecord, but that's not really necessary: two distinct
816 // classes can't be recursively derived from each other. So
817 // along this path, we just need to check whether the classes
818 // are equal.
819 if (NamingClass == ECRecord) return AR_accessible;
820
821 // Otherwise, this context class tells us nothing; on to the next.
822 continue;
823 }
824
825 assert(Target.isInstanceMember());
826
827 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
828 if (!InstanceContext) {
829 OnFailure = AR_dependent;
830 continue;
831 }
832
John McCalla8ae2222010-04-06 21:38:20 +0000833 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
834 case AR_accessible: return AR_accessible;
835 case AR_inaccessible: continue;
836 case AR_dependent: OnFailure = AR_dependent; continue;
837 }
838 }
John McCalld79b4d82010-04-02 00:03:43 +0000839 }
840
John McCall96329672010-08-28 07:56:00 +0000841 // [M3] and [B3] say that, if the target is protected in N, we grant
842 // access if the access occurs in a friend or member of some class P
843 // that's a subclass of N and where the target has some natural
844 // access in P. The 'member' aspect is easy to handle because P
845 // would necessarily be one of the effective-context records, and we
846 // address that above. The 'friend' aspect is completely ridiculous
847 // to implement because there are no restrictions at all on P
848 // *unless* the [class.protected] restriction applies. If it does,
849 // however, we should ignore whether the naming class is a friend,
850 // and instead rely on whether any potential P is a friend.
John McCall5dadb652012-04-07 03:04:20 +0000851 if (Access == AS_protected && Target.isInstanceMember()) {
852 // Compute the instance context if possible.
853 const CXXRecordDecl *InstanceContext = 0;
854 if (Target.hasInstanceContext()) {
855 InstanceContext = Target.resolveInstanceContext(S);
856 if (!InstanceContext) return AR_dependent;
857 }
858
John McCall96329672010-08-28 07:56:00 +0000859 switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
860 case AR_accessible: return AR_accessible;
John McCalla8ae2222010-04-06 21:38:20 +0000861 case AR_inaccessible: return OnFailure;
862 case AR_dependent: return AR_dependent;
863 }
John McCallc6af8f42010-08-28 08:10:32 +0000864 llvm_unreachable("impossible friendship kind");
John McCalla8ae2222010-04-06 21:38:20 +0000865 }
866
867 switch (GetFriendKind(S, EC, NamingClass)) {
868 case AR_accessible: return AR_accessible;
869 case AR_inaccessible: return OnFailure;
870 case AR_dependent: return AR_dependent;
871 }
872
873 // Silence bogus warnings
874 llvm_unreachable("impossible friendship kind");
John McCalld79b4d82010-04-02 00:03:43 +0000875}
876
John McCall5b0829a2010-02-10 09:31:12 +0000877/// Finds the best path from the naming class to the declaring class,
878/// taking friend declarations into account.
879///
John McCalld79b4d82010-04-02 00:03:43 +0000880/// C++0x [class.access.base]p5:
881/// A member m is accessible at the point R when named in class N if
882/// [M1] m as a member of N is public, or
883/// [M2] m as a member of N is private, and R occurs in a member or
884/// friend of class N, or
885/// [M3] m as a member of N is protected, and R occurs in a member or
886/// friend of class N, or in a member or friend of a class P
887/// derived from N, where m as a member of P is public, private,
888/// or protected, or
889/// [M4] there exists a base class B of N that is accessible at R, and
890/// m is accessible at R when named in class B.
891///
892/// C++0x [class.access.base]p4:
893/// A base class B of N is accessible at R, if
894/// [B1] an invented public member of B would be a public member of N, or
895/// [B2] R occurs in a member or friend of class N, and an invented public
896/// member of B would be a private or protected member of N, or
897/// [B3] R occurs in a member or friend of a class P derived from N, and an
898/// invented public member of B would be a private or protected member
899/// of P, or
900/// [B4] there exists a class S such that B is a base class of S accessible
901/// at R and S is a base class of N accessible at R.
902///
903/// Along a single inheritance path we can restate both of these
904/// iteratively:
905///
906/// First, we note that M1-4 are equivalent to B1-4 if the member is
907/// treated as a notional base of its declaring class with inheritance
908/// access equivalent to the member's access. Therefore we need only
909/// ask whether a class B is accessible from a class N in context R.
910///
911/// Let B_1 .. B_n be the inheritance path in question (i.e. where
912/// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
913/// B_i). For i in 1..n, we will calculate ACAB(i), the access to the
914/// closest accessible base in the path:
915/// Access(a, b) = (* access on the base specifier from a to b *)
916/// Merge(a, forbidden) = forbidden
917/// Merge(a, private) = forbidden
918/// Merge(a, b) = min(a,b)
919/// Accessible(c, forbidden) = false
920/// Accessible(c, private) = (R is c) || IsFriend(c, R)
921/// Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
922/// Accessible(c, public) = true
923/// ACAB(n) = public
924/// ACAB(i) =
925/// let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
926/// if Accessible(B_i, AccessToBase) then public else AccessToBase
927///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000928/// B is an accessible base of N at R iff ACAB(1) = public.
John McCalld79b4d82010-04-02 00:03:43 +0000929///
John McCalla8ae2222010-04-06 21:38:20 +0000930/// \param FinalAccess the access of the "final step", or AS_public if
John McCalla332b952010-03-18 23:49:19 +0000931/// there is no final step.
John McCall5b0829a2010-02-10 09:31:12 +0000932/// \return null if friendship is dependent
933static CXXBasePath *FindBestPath(Sema &S,
934 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +0000935 AccessTarget &Target,
John McCalla332b952010-03-18 23:49:19 +0000936 AccessSpecifier FinalAccess,
John McCall5b0829a2010-02-10 09:31:12 +0000937 CXXBasePaths &Paths) {
938 // Derive the paths to the desired base.
John McCalla8ae2222010-04-06 21:38:20 +0000939 const CXXRecordDecl *Derived = Target.getNamingClass();
940 const CXXRecordDecl *Base = Target.getDeclaringClass();
941
942 // FIXME: fail correctly when there are dependent paths.
943 bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
944 Paths);
John McCall5b0829a2010-02-10 09:31:12 +0000945 assert(isDerived && "derived class not actually derived from base");
946 (void) isDerived;
947
948 CXXBasePath *BestPath = 0;
949
John McCalla332b952010-03-18 23:49:19 +0000950 assert(FinalAccess != AS_none && "forbidden access after declaring class");
951
John McCallc62bb642010-03-24 05:22:00 +0000952 bool AnyDependent = false;
953
John McCall5b0829a2010-02-10 09:31:12 +0000954 // Derive the friend-modified access along each path.
955 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
956 PI != PE; ++PI) {
John McCalla8ae2222010-04-06 21:38:20 +0000957 AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +0000958
959 // Walk through the path backwards.
John McCalla332b952010-03-18 23:49:19 +0000960 AccessSpecifier PathAccess = FinalAccess;
John McCall5b0829a2010-02-10 09:31:12 +0000961 CXXBasePath::iterator I = PI->end(), E = PI->begin();
962 while (I != E) {
963 --I;
964
John McCalla332b952010-03-18 23:49:19 +0000965 assert(PathAccess != AS_none);
966
967 // If the declaration is a private member of a base class, there
968 // is no level of friendship in derived classes that can make it
969 // accessible.
970 if (PathAccess == AS_private) {
971 PathAccess = AS_none;
972 break;
973 }
974
John McCalla8ae2222010-04-06 21:38:20 +0000975 const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
976
John McCall5b0829a2010-02-10 09:31:12 +0000977 AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
John McCalld79b4d82010-04-02 00:03:43 +0000978 PathAccess = std::max(PathAccess, BaseAccess);
John McCalla8ae2222010-04-06 21:38:20 +0000979
980 switch (HasAccess(S, EC, NC, PathAccess, Target)) {
981 case AR_inaccessible: break;
982 case AR_accessible:
983 PathAccess = AS_public;
984
985 // Future tests are not against members and so do not have
986 // instance context.
987 Target.suppressInstanceContext();
988 break;
989 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +0000990 AnyDependent = true;
991 goto Next;
John McCall5b0829a2010-02-10 09:31:12 +0000992 }
John McCall5b0829a2010-02-10 09:31:12 +0000993 }
994
995 // Note that we modify the path's Access field to the
996 // friend-modified access.
997 if (BestPath == 0 || PathAccess < BestPath->Access) {
998 BestPath = &*PI;
999 BestPath->Access = PathAccess;
John McCallc62bb642010-03-24 05:22:00 +00001000
1001 // Short-circuit if we found a public path.
1002 if (BestPath->Access == AS_public)
1003 return BestPath;
John McCall5b0829a2010-02-10 09:31:12 +00001004 }
John McCallc62bb642010-03-24 05:22:00 +00001005
1006 Next: ;
John McCall5b0829a2010-02-10 09:31:12 +00001007 }
1008
John McCallc62bb642010-03-24 05:22:00 +00001009 assert((!BestPath || BestPath->Access != AS_public) &&
1010 "fell out of loop with public path");
1011
1012 // We didn't find a public path, but at least one path was subject
1013 // to dependent friendship, so delay the check.
1014 if (AnyDependent)
1015 return 0;
1016
John McCall5b0829a2010-02-10 09:31:12 +00001017 return BestPath;
1018}
1019
John McCall417e7442010-09-03 04:56:05 +00001020/// Given that an entity has protected natural access, check whether
1021/// access might be denied because of the protected member access
1022/// restriction.
1023///
1024/// \return true if a note was emitted
1025static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
1026 AccessTarget &Target) {
1027 // Only applies to instance accesses.
John McCall5dadb652012-04-07 03:04:20 +00001028 if (!Target.isInstanceMember())
John McCall417e7442010-09-03 04:56:05 +00001029 return false;
John McCall417e7442010-09-03 04:56:05 +00001030
John McCall5dadb652012-04-07 03:04:20 +00001031 assert(Target.isMemberAccess());
1032
John McCalld010ac92013-02-27 00:08:19 +00001033 const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
John McCall417e7442010-09-03 04:56:05 +00001034
1035 for (EffectiveContext::record_iterator
1036 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
1037 const CXXRecordDecl *ECRecord = *I;
John McCall5dadb652012-04-07 03:04:20 +00001038 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
John McCall417e7442010-09-03 04:56:05 +00001039 case AR_accessible: break;
1040 case AR_inaccessible: continue;
1041 case AR_dependent: continue;
1042 }
1043
1044 // The effective context is a subclass of the declaring class.
John McCall5dadb652012-04-07 03:04:20 +00001045 // Check whether the [class.protected] restriction is limiting
1046 // access.
John McCall417e7442010-09-03 04:56:05 +00001047
1048 // To get this exactly right, this might need to be checked more
1049 // holistically; it's not necessarily the case that gaining
1050 // access here would grant us access overall.
1051
John McCall5dadb652012-04-07 03:04:20 +00001052 NamedDecl *D = Target.getTargetDecl();
1053
1054 // If we don't have an instance context, [class.protected] says the
1055 // naming class has to equal the context class.
1056 if (!Target.hasInstanceContext()) {
1057 // If it does, the restriction doesn't apply.
1058 if (NamingClass == ECRecord) continue;
1059
1060 // TODO: it would be great to have a fixit here, since this is
1061 // such an obvious error.
1062 S.Diag(D->getLocation(), diag::note_access_protected_restricted_noobject)
1063 << S.Context.getTypeDeclType(ECRecord);
1064 return true;
1065 }
1066
John McCall417e7442010-09-03 04:56:05 +00001067 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
1068 assert(InstanceContext && "diagnosing dependent access");
1069
1070 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
1071 case AR_accessible: continue;
1072 case AR_dependent: continue;
1073 case AR_inaccessible:
John McCall5dadb652012-04-07 03:04:20 +00001074 break;
1075 }
1076
1077 // Okay, the restriction seems to be what's limiting us.
1078
1079 // Use a special diagnostic for constructors and destructors.
1080 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D) ||
1081 (isa<FunctionTemplateDecl>(D) &&
1082 isa<CXXConstructorDecl>(
1083 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
Alp Tokera2794f92014-01-22 07:29:52 +00001084 return S.Diag(D->getLocation(),
1085 diag::note_access_protected_restricted_ctordtor)
1086 << isa<CXXDestructorDecl>(D->getAsFunction());
John McCall417e7442010-09-03 04:56:05 +00001087 }
John McCall5dadb652012-04-07 03:04:20 +00001088
1089 // Otherwise, use the generic diagnostic.
Alp Tokera2794f92014-01-22 07:29:52 +00001090 return S.Diag(D->getLocation(),
1091 diag::note_access_protected_restricted_object)
1092 << S.Context.getTypeDeclType(ECRecord);
John McCall417e7442010-09-03 04:56:05 +00001093 }
1094
1095 return false;
1096}
1097
John McCalld010ac92013-02-27 00:08:19 +00001098/// We are unable to access a given declaration due to its direct
1099/// access control; diagnose that.
1100static void diagnoseBadDirectAccess(Sema &S,
1101 const EffectiveContext &EC,
1102 AccessTarget &entity) {
1103 assert(entity.isMemberAccess());
1104 NamedDecl *D = entity.getTargetDecl();
1105
1106 if (D->getAccess() == AS_protected &&
1107 TryDiagnoseProtectedAccess(S, EC, entity))
1108 return;
1109
1110 // Find an original declaration.
1111 while (D->isOutOfLine()) {
1112 NamedDecl *PrevDecl = 0;
1113 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1114 PrevDecl = VD->getPreviousDecl();
1115 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1116 PrevDecl = FD->getPreviousDecl();
1117 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
1118 PrevDecl = TND->getPreviousDecl();
1119 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1120 if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
1121 break;
1122 PrevDecl = TD->getPreviousDecl();
1123 }
1124 if (!PrevDecl) break;
1125 D = PrevDecl;
1126 }
1127
1128 CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1129 Decl *ImmediateChild;
1130 if (D->getDeclContext() == DeclaringClass)
1131 ImmediateChild = D;
1132 else {
1133 DeclContext *DC = D->getDeclContext();
1134 while (DC->getParent() != DeclaringClass)
1135 DC = DC->getParent();
1136 ImmediateChild = cast<Decl>(DC);
1137 }
1138
1139 // Check whether there's an AccessSpecDecl preceding this in the
1140 // chain of the DeclContext.
1141 bool isImplicit = true;
1142 for (CXXRecordDecl::decl_iterator
1143 I = DeclaringClass->decls_begin(), E = DeclaringClass->decls_end();
1144 I != E; ++I) {
1145 if (*I == ImmediateChild) break;
1146 if (isa<AccessSpecDecl>(*I)) {
1147 isImplicit = false;
1148 break;
1149 }
1150 }
1151
1152 S.Diag(D->getLocation(), diag::note_access_natural)
1153 << (unsigned) (D->getAccess() == AS_protected)
1154 << isImplicit;
1155}
1156
John McCall5b0829a2010-02-10 09:31:12 +00001157/// Diagnose the path which caused the given declaration or base class
1158/// to become inaccessible.
1159static void DiagnoseAccessPath(Sema &S,
1160 const EffectiveContext &EC,
John McCalld010ac92013-02-27 00:08:19 +00001161 AccessTarget &entity) {
1162 // Save the instance context to preserve invariants.
1163 AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
John McCalld79b4d82010-04-02 00:03:43 +00001164
John McCalld010ac92013-02-27 00:08:19 +00001165 // This basically repeats the main algorithm but keeps some more
1166 // information.
John McCalld79b4d82010-04-02 00:03:43 +00001167
John McCalld010ac92013-02-27 00:08:19 +00001168 // The natural access so far.
1169 AccessSpecifier accessSoFar = AS_public;
John McCall417e7442010-09-03 04:56:05 +00001170
John McCalld010ac92013-02-27 00:08:19 +00001171 // Check whether we have special rights to the declaring class.
1172 if (entity.isMemberAccess()) {
1173 NamedDecl *D = entity.getTargetDecl();
1174 accessSoFar = D->getAccess();
1175 const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
John McCallf551aca2010-10-20 08:15:06 +00001176
John McCalld010ac92013-02-27 00:08:19 +00001177 switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1178 // If the declaration is accessible when named in its declaring
1179 // class, then we must be constrained by the path.
1180 case AR_accessible:
1181 accessSoFar = AS_public;
1182 entity.suppressInstanceContext();
1183 break;
John McCallf551aca2010-10-20 08:15:06 +00001184
John McCalld010ac92013-02-27 00:08:19 +00001185 case AR_inaccessible:
1186 if (accessSoFar == AS_private ||
1187 declaringClass == entity.getEffectiveNamingClass())
1188 return diagnoseBadDirectAccess(S, EC, entity);
1189 break;
John McCall5b0829a2010-02-10 09:31:12 +00001190
John McCalla8ae2222010-04-06 21:38:20 +00001191 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001192 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001193 }
1194 }
1195
John McCalld010ac92013-02-27 00:08:19 +00001196 CXXBasePaths paths;
1197 CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1198 assert(path.Access != AS_public);
John McCall5b0829a2010-02-10 09:31:12 +00001199
John McCalld010ac92013-02-27 00:08:19 +00001200 CXXBasePath::iterator i = path.end(), e = path.begin();
1201 CXXBasePath::iterator constrainingBase = i;
1202 while (i != e) {
1203 --i;
John McCall5b0829a2010-02-10 09:31:12 +00001204
John McCalld010ac92013-02-27 00:08:19 +00001205 assert(accessSoFar != AS_none && accessSoFar != AS_private);
John McCall5b0829a2010-02-10 09:31:12 +00001206
John McCalld010ac92013-02-27 00:08:19 +00001207 // Is the entity accessible when named in the deriving class, as
1208 // modified by the base specifier?
1209 const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1210 const CXXBaseSpecifier *base = i->Base;
John McCall5b0829a2010-02-10 09:31:12 +00001211
John McCalld010ac92013-02-27 00:08:19 +00001212 // If the access to this base is worse than the access we have to
1213 // the declaration, remember it.
1214 AccessSpecifier baseAccess = base->getAccessSpecifier();
1215 if (baseAccess > accessSoFar) {
1216 constrainingBase = i;
1217 accessSoFar = baseAccess;
1218 }
1219
1220 switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001221 case AR_inaccessible: break;
John McCalld010ac92013-02-27 00:08:19 +00001222 case AR_accessible:
1223 accessSoFar = AS_public;
1224 entity.suppressInstanceContext();
1225 constrainingBase = 0;
1226 break;
John McCalla8ae2222010-04-06 21:38:20 +00001227 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001228 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001229 }
1230
John McCalld010ac92013-02-27 00:08:19 +00001231 // If this was private inheritance, but we don't have access to
1232 // the deriving class, we're done.
1233 if (accessSoFar == AS_private) {
1234 assert(baseAccess == AS_private);
1235 assert(constrainingBase == i);
1236 break;
John McCall5b0829a2010-02-10 09:31:12 +00001237 }
1238 }
1239
John McCalld010ac92013-02-27 00:08:19 +00001240 // If we don't have a constraining base, the access failure must be
1241 // due to the original declaration.
1242 if (constrainingBase == path.end())
1243 return diagnoseBadDirectAccess(S, EC, entity);
1244
1245 // We're constrained by inheritance, but we want to say
1246 // "declared private here" if we're diagnosing a hierarchy
1247 // conversion and this is the final step.
1248 unsigned diagnostic;
1249 if (entity.isMemberAccess() ||
1250 constrainingBase + 1 != path.end()) {
1251 diagnostic = diag::note_access_constrained_by_path;
1252 } else {
1253 diagnostic = diag::note_access_natural;
1254 }
1255
1256 const CXXBaseSpecifier *base = constrainingBase->Base;
1257
1258 S.Diag(base->getSourceRange().getBegin(), diagnostic)
1259 << base->getSourceRange()
1260 << (base->getAccessSpecifier() == AS_protected)
1261 << (base->getAccessSpecifierAsWritten() == AS_none);
1262
1263 if (entity.isMemberAccess())
1264 S.Diag(entity.getTargetDecl()->getLocation(), diag::note_field_decl);
John McCall5b0829a2010-02-10 09:31:12 +00001265}
1266
John McCall1064d7e2010-03-16 05:22:47 +00001267static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
John McCall5b0829a2010-02-10 09:31:12 +00001268 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +00001269 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001270 const CXXRecordDecl *NamingClass = Entity.getNamingClass();
John McCalla8ae2222010-04-06 21:38:20 +00001271 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1272 NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : 0);
John McCalld79b4d82010-04-02 00:03:43 +00001273
1274 S.Diag(Loc, Entity.getDiag())
1275 << (Entity.getAccess() == AS_protected)
1276 << (D ? D->getDeclName() : DeclarationName())
1277 << S.Context.getTypeDeclType(NamingClass)
1278 << S.Context.getTypeDeclType(DeclaringClass);
1279 DiagnoseAccessPath(S, EC, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001280}
1281
Francois Pichetefb1af92011-05-23 03:43:44 +00001282/// MSVC has a bug where if during an using declaration name lookup,
1283/// the declaration found is unaccessible (private) and that declaration
1284/// was bring into scope via another using declaration whose target
1285/// declaration is accessible (public) then no error is generated.
1286/// Example:
1287/// class A {
1288/// public:
1289/// int f();
1290/// };
1291/// class B : public A {
1292/// private:
1293/// using A::f;
1294/// };
1295/// class C : public B {
1296/// private:
1297/// using B::f;
1298/// };
1299///
1300/// Here, B::f is private so this should fail in Standard C++, but
1301/// because B::f refers to A::f which is public MSVC accepts it.
1302static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
1303 SourceLocation AccessLoc,
1304 AccessTarget &Entity) {
1305 if (UsingShadowDecl *Shadow =
1306 dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) {
1307 const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
1308 if (Entity.getTargetDecl()->getAccess() == AS_private &&
1309 (OrigDecl->getAccess() == AS_public ||
1310 OrigDecl->getAccess() == AS_protected)) {
Richard Smithe4345902011-12-29 21:57:33 +00001311 S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
Francois Pichetefb1af92011-05-23 03:43:44 +00001312 << Shadow->getUsingDecl()->getQualifiedNameAsString()
1313 << OrigDecl->getQualifiedNameAsString();
1314 return true;
1315 }
1316 }
1317 return false;
1318}
1319
John McCalld79b4d82010-04-02 00:03:43 +00001320/// Determines whether the accessed entity is accessible. Public members
1321/// have been weeded out by this point.
John McCalla8ae2222010-04-06 21:38:20 +00001322static AccessResult IsAccessible(Sema &S,
1323 const EffectiveContext &EC,
1324 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001325 // Determine the actual naming class.
John McCalld010ac92013-02-27 00:08:19 +00001326 const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
John McCall5b0829a2010-02-10 09:31:12 +00001327
John McCalld79b4d82010-04-02 00:03:43 +00001328 AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1329 assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1330
1331 // Before we try to recalculate access paths, try to white-list
1332 // accesses which just trade in on the final step, i.e. accesses
1333 // which don't require [M4] or [B4]. These are by far the most
John McCalla8ae2222010-04-06 21:38:20 +00001334 // common forms of privileged access.
John McCalld79b4d82010-04-02 00:03:43 +00001335 if (UnprivilegedAccess != AS_none) {
John McCalla8ae2222010-04-06 21:38:20 +00001336 switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1337 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +00001338 // This is actually an interesting policy decision. We don't
1339 // *have* to delay immediately here: we can do the full access
1340 // calculation in the hope that friendship on some intermediate
1341 // class will make the declaration accessible non-dependently.
1342 // But that's not cheap, and odds are very good (note: assertion
1343 // made without data) that the friend declaration will determine
1344 // access.
John McCalla8ae2222010-04-06 21:38:20 +00001345 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001346
John McCalla8ae2222010-04-06 21:38:20 +00001347 case AR_accessible: return AR_accessible;
1348 case AR_inaccessible: break;
John McCalld79b4d82010-04-02 00:03:43 +00001349 }
1350 }
1351
John McCalla8ae2222010-04-06 21:38:20 +00001352 AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +00001353
John McCalld79b4d82010-04-02 00:03:43 +00001354 // We lower member accesses to base accesses by pretending that the
1355 // member is a base class of its declaring class.
1356 AccessSpecifier FinalAccess;
1357
John McCall5b0829a2010-02-10 09:31:12 +00001358 if (Entity.isMemberAccess()) {
John McCalld79b4d82010-04-02 00:03:43 +00001359 // Determine if the declaration is accessible from EC when named
1360 // in its declaring class.
John McCall5b0829a2010-02-10 09:31:12 +00001361 NamedDecl *Target = Entity.getTargetDecl();
John McCalla8ae2222010-04-06 21:38:20 +00001362 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
John McCall5b0829a2010-02-10 09:31:12 +00001363
John McCalld79b4d82010-04-02 00:03:43 +00001364 FinalAccess = Target->getAccess();
John McCalla8ae2222010-04-06 21:38:20 +00001365 switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1366 case AR_accessible:
John McCall5149fbf2013-02-22 03:52:55 +00001367 // Target is accessible at EC when named in its declaring class.
1368 // We can now hill-climb and simply check whether the declaring
1369 // class is accessible as a base of the naming class. This is
1370 // equivalent to checking the access of a notional public
1371 // member with no instance context.
John McCalla8ae2222010-04-06 21:38:20 +00001372 FinalAccess = AS_public;
John McCall5149fbf2013-02-22 03:52:55 +00001373 Entity.suppressInstanceContext();
John McCalla8ae2222010-04-06 21:38:20 +00001374 break;
1375 case AR_inaccessible: break;
1376 case AR_dependent: return AR_dependent; // see above
John McCall5b0829a2010-02-10 09:31:12 +00001377 }
1378
John McCalld79b4d82010-04-02 00:03:43 +00001379 if (DeclaringClass == NamingClass)
John McCalla8ae2222010-04-06 21:38:20 +00001380 return (FinalAccess == AS_public ? AR_accessible : AR_inaccessible);
John McCalld79b4d82010-04-02 00:03:43 +00001381 } else {
1382 FinalAccess = AS_public;
John McCall5b0829a2010-02-10 09:31:12 +00001383 }
1384
John McCalla8ae2222010-04-06 21:38:20 +00001385 assert(Entity.getDeclaringClass() != NamingClass);
John McCall5b0829a2010-02-10 09:31:12 +00001386
1387 // Append the declaration's access if applicable.
1388 CXXBasePaths Paths;
John McCalla8ae2222010-04-06 21:38:20 +00001389 CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
John McCallc62bb642010-03-24 05:22:00 +00001390 if (!Path)
John McCalla8ae2222010-04-06 21:38:20 +00001391 return AR_dependent;
John McCall553c0792010-01-23 00:46:32 +00001392
John McCalld79b4d82010-04-02 00:03:43 +00001393 assert(Path->Access <= UnprivilegedAccess &&
1394 "access along best path worse than direct?");
1395 if (Path->Access == AS_public)
John McCalla8ae2222010-04-06 21:38:20 +00001396 return AR_accessible;
1397 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +00001398}
1399
John McCalla8ae2222010-04-06 21:38:20 +00001400static void DelayDependentAccess(Sema &S,
1401 const EffectiveContext &EC,
1402 SourceLocation Loc,
1403 const AccessTarget &Entity) {
John McCallc62bb642010-03-24 05:22:00 +00001404 assert(EC.isDependent() && "delaying non-dependent access");
John McCall816d75b2010-03-24 07:46:06 +00001405 DeclContext *DC = EC.getInnerContext();
John McCallc62bb642010-03-24 05:22:00 +00001406 assert(DC->isDependentContext() && "delaying non-dependent access");
1407 DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1408 Loc,
1409 Entity.isMemberAccess(),
1410 Entity.getAccess(),
1411 Entity.getTargetDecl(),
1412 Entity.getNamingClass(),
John McCalla8ae2222010-04-06 21:38:20 +00001413 Entity.getBaseObjectType(),
John McCallc62bb642010-03-24 05:22:00 +00001414 Entity.getDiag());
John McCall553c0792010-01-23 00:46:32 +00001415}
1416
John McCall5b0829a2010-02-10 09:31:12 +00001417/// Checks access to an entity from the given effective context.
John McCalla8ae2222010-04-06 21:38:20 +00001418static AccessResult CheckEffectiveAccess(Sema &S,
1419 const EffectiveContext &EC,
1420 SourceLocation Loc,
1421 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001422 assert(Entity.getAccess() != AS_public && "called for public access!");
John McCall553c0792010-01-23 00:46:32 +00001423
Alp Tokerbfa39342014-01-14 12:51:41 +00001424 if (S.getLangOpts().MSVCCompat &&
Francois Pichetefb1af92011-05-23 03:43:44 +00001425 IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
1426 return AR_accessible;
1427
John McCalld79b4d82010-04-02 00:03:43 +00001428 switch (IsAccessible(S, EC, Entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001429 case AR_dependent:
1430 DelayDependentAccess(S, EC, Loc, Entity);
1431 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001432
John McCalla8ae2222010-04-06 21:38:20 +00001433 case AR_inaccessible:
John McCalld79b4d82010-04-02 00:03:43 +00001434 if (!Entity.isQuiet())
1435 DiagnoseBadAccess(S, Loc, EC, Entity);
John McCalla8ae2222010-04-06 21:38:20 +00001436 return AR_inaccessible;
John McCalld79b4d82010-04-02 00:03:43 +00001437
John McCalla8ae2222010-04-06 21:38:20 +00001438 case AR_accessible:
1439 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +00001440 }
1441
John McCalla8ae2222010-04-06 21:38:20 +00001442 // silence unnecessary warning
1443 llvm_unreachable("invalid access result");
John McCall5b0829a2010-02-10 09:31:12 +00001444}
John McCall553c0792010-01-23 00:46:32 +00001445
John McCall5b0829a2010-02-10 09:31:12 +00001446static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
John McCalla8ae2222010-04-06 21:38:20 +00001447 AccessTarget &Entity) {
John McCall5b0829a2010-02-10 09:31:12 +00001448 // If the access path is public, it's accessible everywhere.
1449 if (Entity.getAccess() == AS_public)
1450 return Sema::AR_accessible;
John McCall553c0792010-01-23 00:46:32 +00001451
John McCallc1465822011-02-14 07:13:47 +00001452 // If we're currently parsing a declaration, we may need to delay
1453 // access control checking, because our effective context might be
1454 // different based on what the declaration comes out as.
1455 //
1456 // For example, we might be parsing a declaration with a scope
1457 // specifier, like this:
1458 // A::private_type A::foo() { ... }
1459 //
1460 // Or we might be parsing something that will turn out to be a friend:
1461 // void foo(A::private_type);
1462 // void B::foo(A::private_type);
1463 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1464 S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
John McCall5b0829a2010-02-10 09:31:12 +00001465 return Sema::AR_delayed;
John McCall553c0792010-01-23 00:46:32 +00001466 }
1467
John McCalla8ae2222010-04-06 21:38:20 +00001468 EffectiveContext EC(S.CurContext);
1469 switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1470 case AR_accessible: return Sema::AR_accessible;
1471 case AR_inaccessible: return Sema::AR_inaccessible;
1472 case AR_dependent: return Sema::AR_dependent;
1473 }
1474 llvm_unreachable("falling off end");
John McCall553c0792010-01-23 00:46:32 +00001475}
1476
Richard Smithad5c1ca2013-04-29 10:13:55 +00001477void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
John McCall9743e8d2011-02-15 22:51:53 +00001478 // Access control for names used in the declarations of functions
1479 // and function templates should normally be evaluated in the context
1480 // of the declaration, just in case it's a friend of something.
1481 // However, this does not apply to local extern declarations.
1482
Richard Smithad5c1ca2013-04-29 10:13:55 +00001483 DeclContext *DC = D->getDeclContext();
Richard Smith608da012013-12-11 03:35:27 +00001484 if (D->isLocalExternDecl()) {
1485 DC = D->getLexicalDeclContext();
1486 } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1487 DC = FN;
Richard Smithad5c1ca2013-04-29 10:13:55 +00001488 } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1489 DC = cast<DeclContext>(TD->getTemplatedDecl());
John McCall9743e8d2011-02-15 22:51:53 +00001490 }
1491
Chandler Carruthaad30072010-04-18 08:23:21 +00001492 EffectiveContext EC(DC);
John McCall86121512010-01-27 03:50:35 +00001493
John McCalla8ae2222010-04-06 21:38:20 +00001494 AccessTarget Target(DD.getAccessData());
1495
1496 if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
John McCall86121512010-01-27 03:50:35 +00001497 DD.Triggered = true;
1498}
1499
John McCallc62bb642010-03-24 05:22:00 +00001500void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1501 const MultiLevelTemplateArgumentList &TemplateArgs) {
1502 SourceLocation Loc = DD.getAccessLoc();
1503 AccessSpecifier Access = DD.getAccess();
1504
1505 Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1506 TemplateArgs);
1507 if (!NamingD) return;
1508 Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1509 TemplateArgs);
1510 if (!TargetD) return;
1511
1512 if (DD.isAccessToMember()) {
John McCalla8ae2222010-04-06 21:38:20 +00001513 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1514 NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1515 QualType BaseObjectType = DD.getAccessBaseObjectType();
1516 if (!BaseObjectType.isNull()) {
1517 BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1518 DeclarationName());
1519 if (BaseObjectType.isNull()) return;
1520 }
1521
1522 AccessTarget Entity(Context,
1523 AccessTarget::Member,
1524 NamingClass,
1525 DeclAccessPair::make(TargetDecl, Access),
1526 BaseObjectType);
John McCallc62bb642010-03-24 05:22:00 +00001527 Entity.setDiag(DD.getDiagnostic());
1528 CheckAccess(*this, Loc, Entity);
1529 } else {
John McCalla8ae2222010-04-06 21:38:20 +00001530 AccessTarget Entity(Context,
1531 AccessTarget::Base,
1532 cast<CXXRecordDecl>(TargetD),
1533 cast<CXXRecordDecl>(NamingD),
1534 Access);
John McCallc62bb642010-03-24 05:22:00 +00001535 Entity.setDiag(DD.getDiagnostic());
1536 CheckAccess(*this, Loc, Entity);
1537 }
1538}
1539
John McCall5b0829a2010-02-10 09:31:12 +00001540Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001541 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001542 if (!getLangOpts().AccessControl ||
John McCall1064d7e2010-03-16 05:22:47 +00001543 !E->getNamingClass() ||
John McCalla0296f72010-03-19 07:35:19 +00001544 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001545 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001546
John McCalla8ae2222010-04-06 21:38:20 +00001547 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1548 Found, QualType());
John McCall1064d7e2010-03-16 05:22:47 +00001549 Entity.setDiag(diag::err_access) << E->getSourceRange();
1550
1551 return CheckAccess(*this, E->getNameLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001552}
1553
1554/// Perform access-control checking on a previously-unresolved member
1555/// access which has now been resolved to a member.
John McCall5b0829a2010-02-10 09:31:12 +00001556Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001557 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001558 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001559 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001560 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001561
John McCalla8ae2222010-04-06 21:38:20 +00001562 QualType BaseType = E->getBaseType();
1563 if (E->isArrow())
1564 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1565
1566 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1567 Found, BaseType);
John McCall1064d7e2010-03-16 05:22:47 +00001568 Entity.setDiag(diag::err_access) << E->getSourceRange();
1569
1570 return CheckAccess(*this, E->getMemberLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001571}
1572
John McCalld4274212012-04-09 20:53:23 +00001573/// Is the given special member function accessible for the purposes of
1574/// deciding whether to define a special member function as deleted?
1575bool Sema::isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
1576 AccessSpecifier access,
1577 QualType objectType) {
1578 // Fast path.
1579 if (access == AS_public || !getLangOpts().AccessControl) return true;
1580
1581 AccessTarget entity(Context, AccessTarget::Member, decl->getParent(),
1582 DeclAccessPair::make(decl, access), objectType);
1583
1584 // Suppress diagnostics.
1585 entity.setDiag(PDiag());
1586
1587 switch (CheckAccess(*this, SourceLocation(), entity)) {
1588 case AR_accessible: return true;
1589 case AR_inaccessible: return false;
1590 case AR_dependent: llvm_unreachable("dependent for =delete computation");
1591 case AR_delayed: llvm_unreachable("cannot delay =delete computation");
1592 }
1593 llvm_unreachable("bad access result");
1594}
1595
John McCall5b0829a2010-02-10 09:31:12 +00001596Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
John McCall1064d7e2010-03-16 05:22:47 +00001597 CXXDestructorDecl *Dtor,
John McCall5dadb652012-04-07 03:04:20 +00001598 const PartialDiagnostic &PDiag,
1599 QualType ObjectTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001600 if (!getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001601 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001602
John McCall1064d7e2010-03-16 05:22:47 +00001603 // There's never a path involved when checking implicit destructor access.
John McCall6781b052010-02-02 08:45:54 +00001604 AccessSpecifier Access = Dtor->getAccess();
1605 if (Access == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001606 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001607
John McCall1064d7e2010-03-16 05:22:47 +00001608 CXXRecordDecl *NamingClass = Dtor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001609 if (ObjectTy.isNull()) ObjectTy = Context.getTypeDeclType(NamingClass);
1610
John McCalla8ae2222010-04-06 21:38:20 +00001611 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1612 DeclAccessPair::make(Dtor, Access),
John McCall5dadb652012-04-07 03:04:20 +00001613 ObjectTy);
John McCall1064d7e2010-03-16 05:22:47 +00001614 Entity.setDiag(PDiag); // TODO: avoid copy
1615
1616 return CheckAccess(*this, Loc, Entity);
John McCall6781b052010-02-02 08:45:54 +00001617}
1618
John McCall760af172010-02-01 03:16:54 +00001619/// Checks access to a constructor.
John McCall5b0829a2010-02-10 09:31:12 +00001620Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00001621 CXXConstructorDecl *Constructor,
1622 const InitializedEntity &Entity,
1623 AccessSpecifier Access,
1624 bool IsCopyBindingRefToTemp) {
John McCall5dadb652012-04-07 03:04:20 +00001625 if (!getLangOpts().AccessControl || Access == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001626 return AR_accessible;
John McCall760af172010-02-01 03:16:54 +00001627
Alexis Hunteef8ee02011-06-10 03:50:41 +00001628 PartialDiagnostic PD(PDiag());
Anders Carlssona01874b2010-04-21 18:47:17 +00001629 switch (Entity.getKind()) {
1630 default:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001631 PD = PDiag(IsCopyBindingRefToTemp
1632 ? diag::ext_rvalue_to_reference_access_ctor
1633 : diag::err_access_ctor);
1634
Anders Carlssona01874b2010-04-21 18:47:17 +00001635 break;
John McCall1064d7e2010-03-16 05:22:47 +00001636
Anders Carlsson05bf0092010-04-22 05:40:53 +00001637 case InitializedEntity::EK_Base:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001638 PD = PDiag(diag::err_access_base_ctor);
1639 PD << Entity.isInheritedVirtualBase()
1640 << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
Anders Carlssona01874b2010-04-21 18:47:17 +00001641 break;
Anders Carlsson05bf0092010-04-22 05:40:53 +00001642
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001643 case InitializedEntity::EK_Member: {
1644 const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00001645 PD = PDiag(diag::err_access_field_ctor);
1646 PD << Field->getType() << getSpecialMember(Constructor);
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001647 break;
1648 }
Anders Carlssona01874b2010-04-21 18:47:17 +00001649
Douglas Gregor19666fb2012-02-15 16:57:26 +00001650 case InitializedEntity::EK_LambdaCapture: {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001651 StringRef VarName = Entity.getCapturedVarName();
Douglas Gregor19666fb2012-02-15 16:57:26 +00001652 PD = PDiag(diag::err_access_lambda_capture);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001653 PD << VarName << Entity.getType() << getSpecialMember(Constructor);
Douglas Gregor19666fb2012-02-15 16:57:26 +00001654 break;
1655 }
1656
Anders Carlsson43c64af2010-04-21 19:52:01 +00001657 }
1658
John McCall5dadb652012-04-07 03:04:20 +00001659 return CheckConstructorAccess(UseLoc, Constructor, Entity, Access, PD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00001660}
1661
1662/// Checks access to a constructor.
1663Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1664 CXXConstructorDecl *Constructor,
John McCall5dadb652012-04-07 03:04:20 +00001665 const InitializedEntity &Entity,
Alexis Hunteef8ee02011-06-10 03:50:41 +00001666 AccessSpecifier Access,
John McCall5dadb652012-04-07 03:04:20 +00001667 const PartialDiagnostic &PD) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001668 if (!getLangOpts().AccessControl ||
Alexis Hunteef8ee02011-06-10 03:50:41 +00001669 Access == AS_public)
1670 return AR_accessible;
1671
1672 CXXRecordDecl *NamingClass = Constructor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001673
1674 // Initializing a base sub-object is an instance method call on an
1675 // object of the derived class. Otherwise, we have an instance method
1676 // call on an object of the constructed type.
1677 CXXRecordDecl *ObjectClass;
1678 if (Entity.getKind() == InitializedEntity::EK_Base) {
1679 ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
1680 } else {
1681 ObjectClass = NamingClass;
1682 }
1683
Alexis Hunteef8ee02011-06-10 03:50:41 +00001684 AccessTarget AccessEntity(Context, AccessTarget::Member, NamingClass,
1685 DeclAccessPair::make(Constructor, Access),
John McCall5dadb652012-04-07 03:04:20 +00001686 Context.getTypeDeclType(ObjectClass));
Alexis Hunteef8ee02011-06-10 03:50:41 +00001687 AccessEntity.setDiag(PD);
1688
Anders Carlssona01874b2010-04-21 18:47:17 +00001689 return CheckAccess(*this, UseLoc, AccessEntity);
John McCall5dadb652012-04-07 03:04:20 +00001690}
John McCall760af172010-02-01 03:16:54 +00001691
John McCallfb6f5262010-03-18 08:19:33 +00001692/// Checks access to an overloaded operator new or delete.
1693Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1694 SourceRange PlacementRange,
1695 CXXRecordDecl *NamingClass,
Alexis Huntf91729462011-05-12 22:46:25 +00001696 DeclAccessPair Found,
1697 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001698 if (!getLangOpts().AccessControl ||
John McCallfb6f5262010-03-18 08:19:33 +00001699 !NamingClass ||
John McCalla0296f72010-03-19 07:35:19 +00001700 Found.getAccess() == AS_public)
John McCallfb6f5262010-03-18 08:19:33 +00001701 return AR_accessible;
1702
John McCalla8ae2222010-04-06 21:38:20 +00001703 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1704 QualType());
Alexis Huntf91729462011-05-12 22:46:25 +00001705 if (Diagnose)
1706 Entity.setDiag(diag::err_access)
1707 << PlacementRange;
John McCallfb6f5262010-03-18 08:19:33 +00001708
1709 return CheckAccess(*this, OpLoc, Entity);
1710}
1711
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001712/// \brief Checks access to a member.
1713Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1714 CXXRecordDecl *NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001715 DeclAccessPair Found) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001716 if (!getLangOpts().AccessControl ||
1717 !NamingClass ||
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001718 Found.getAccess() == AS_public)
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001719 return AR_accessible;
1720
1721 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001722 Found, QualType());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001723
1724 return CheckAccess(*this, UseLoc, Entity);
1725}
1726
John McCall760af172010-02-01 03:16:54 +00001727/// Checks access to an overloaded member operator, including
1728/// conversion operators.
John McCall5b0829a2010-02-10 09:31:12 +00001729Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1730 Expr *ObjectExpr,
John McCall1064d7e2010-03-16 05:22:47 +00001731 Expr *ArgExpr,
John McCalla0296f72010-03-19 07:35:19 +00001732 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001733 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001734 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001735 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001736
John McCall30909032011-09-21 08:36:56 +00001737 const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
John McCallb3a44002010-01-28 01:42:12 +00001738 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1739
John McCalla8ae2222010-04-06 21:38:20 +00001740 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1741 ObjectExpr->getType());
John McCall1064d7e2010-03-16 05:22:47 +00001742 Entity.setDiag(diag::err_access)
1743 << ObjectExpr->getSourceRange()
1744 << (ArgExpr ? ArgExpr->getSourceRange() : SourceRange());
1745
1746 return CheckAccess(*this, OpLoc, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001747}
John McCallb3a44002010-01-28 01:42:12 +00001748
John McCalla0a96892012-08-10 03:15:35 +00001749/// Checks access to the target of a friend declaration.
1750Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
Alp Tokera2794f92014-01-22 07:29:52 +00001751 assert(isa<CXXMethodDecl>(target->getAsFunction()));
John McCalla0a96892012-08-10 03:15:35 +00001752
1753 // Friendship lookup is a redeclaration lookup, so there's never an
1754 // inheritance path modifying access.
1755 AccessSpecifier access = target->getAccess();
1756
1757 if (!getLangOpts().AccessControl || access == AS_public)
1758 return AR_accessible;
1759
Alp Tokera2794f92014-01-22 07:29:52 +00001760 CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(target->getAsFunction());
John McCalla0a96892012-08-10 03:15:35 +00001761 assert(method->getQualifier());
1762
1763 AccessTarget entity(Context, AccessTarget::Member,
1764 cast<CXXRecordDecl>(target->getDeclContext()),
1765 DeclAccessPair::make(target, access),
1766 /*no instance context*/ QualType());
1767 entity.setDiag(diag::err_access_friend_function)
1768 << method->getQualifierLoc().getSourceRange();
1769
1770 // We need to bypass delayed-diagnostics because we might be called
1771 // while the ParsingDeclarator is active.
1772 EffectiveContext EC(CurContext);
1773 switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
1774 case AR_accessible: return Sema::AR_accessible;
1775 case AR_inaccessible: return Sema::AR_inaccessible;
1776 case AR_dependent: return Sema::AR_dependent;
1777 }
1778 llvm_unreachable("falling off end");
1779}
1780
John McCall16df1e52010-03-30 21:47:33 +00001781Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1782 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 if (!getLangOpts().AccessControl ||
John McCallb493d532010-03-30 22:20:00 +00001784 Found.getAccess() == AS_none ||
John McCall16df1e52010-03-30 21:47:33 +00001785 Found.getAccess() == AS_public)
1786 return AR_accessible;
1787
John McCall8d08b9b2010-08-27 09:08:28 +00001788 OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
John McCall8c12dc42010-04-22 18:44:12 +00001789 CXXRecordDecl *NamingClass = Ovl->getNamingClass();
John McCall16df1e52010-03-30 21:47:33 +00001790
John McCalla8ae2222010-04-06 21:38:20 +00001791 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
John McCall5dadb652012-04-07 03:04:20 +00001792 /*no instance context*/ QualType());
John McCall16df1e52010-03-30 21:47:33 +00001793 Entity.setDiag(diag::err_access)
1794 << Ovl->getSourceRange();
1795
1796 return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1797}
1798
John McCall5b0829a2010-02-10 09:31:12 +00001799/// Checks access for a hierarchy conversion.
1800///
John McCall5b0829a2010-02-10 09:31:12 +00001801/// \param ForceCheck true if this check should be performed even if access
1802/// control is disabled; some things rely on this for semantics
1803/// \param ForceUnprivileged true if this check should proceed as if the
1804/// context had no special privileges
John McCall5b0829a2010-02-10 09:31:12 +00001805Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
John McCall5b0829a2010-02-10 09:31:12 +00001806 QualType Base,
1807 QualType Derived,
1808 const CXXBasePath &Path,
John McCall1064d7e2010-03-16 05:22:47 +00001809 unsigned DiagID,
John McCall5b0829a2010-02-10 09:31:12 +00001810 bool ForceCheck,
John McCall1064d7e2010-03-16 05:22:47 +00001811 bool ForceUnprivileged) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001812 if (!ForceCheck && !getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001813 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001814
John McCall5b0829a2010-02-10 09:31:12 +00001815 if (Path.Access == AS_public)
1816 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001817
John McCall5b0829a2010-02-10 09:31:12 +00001818 CXXRecordDecl *BaseD, *DerivedD;
1819 BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl());
1820 DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl());
John McCall1064d7e2010-03-16 05:22:47 +00001821
John McCalla8ae2222010-04-06 21:38:20 +00001822 AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1823 Path.Access);
John McCall1064d7e2010-03-16 05:22:47 +00001824 if (DiagID)
1825 Entity.setDiag(DiagID) << Derived << Base;
John McCall5b0829a2010-02-10 09:31:12 +00001826
John McCalla8ae2222010-04-06 21:38:20 +00001827 if (ForceUnprivileged) {
1828 switch (CheckEffectiveAccess(*this, EffectiveContext(),
1829 AccessLoc, Entity)) {
1830 case ::AR_accessible: return Sema::AR_accessible;
1831 case ::AR_inaccessible: return Sema::AR_inaccessible;
1832 case ::AR_dependent: return Sema::AR_dependent;
1833 }
1834 llvm_unreachable("unexpected result from CheckEffectiveAccess");
1835 }
John McCall1064d7e2010-03-16 05:22:47 +00001836 return CheckAccess(*this, AccessLoc, Entity);
John McCallb3a44002010-01-28 01:42:12 +00001837}
1838
John McCall553c0792010-01-23 00:46:32 +00001839/// Checks access to all the declarations in the given result set.
John McCall5b0829a2010-02-10 09:31:12 +00001840void Sema::CheckLookupAccess(const LookupResult &R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001841 assert(getLangOpts().AccessControl
John McCall5b0829a2010-02-10 09:31:12 +00001842 && "performing access check without access control");
1843 assert(R.getNamingClass() && "performing access check without naming class");
1844
John McCall1064d7e2010-03-16 05:22:47 +00001845 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1846 if (I.getAccess() != AS_public) {
John McCalla8ae2222010-04-06 21:38:20 +00001847 AccessTarget Entity(Context, AccessedEntity::Member,
1848 R.getNamingClass(), I.getPair(),
Erik Verbruggen631dfc62011-09-19 15:10:40 +00001849 R.getBaseObjectType());
John McCall1064d7e2010-03-16 05:22:47 +00001850 Entity.setDiag(diag::err_access);
John McCall1064d7e2010-03-16 05:22:47 +00001851 CheckAccess(*this, R.getNameLoc(), Entity);
1852 }
1853 }
John McCall553c0792010-01-23 00:46:32 +00001854}
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001855
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001856/// Checks access to Decl from the given class. The check will take access
1857/// specifiers into account, but no member access expressions and such.
1858///
1859/// \param Decl the declaration to check if it can be accessed
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001860/// \param Ctx the class/context from which to start the search
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001861/// \return true if the Decl is accessible from the Class, false otherwise.
Douglas Gregor03ba1882011-11-03 16:51:37 +00001862bool Sema::IsSimplyAccessible(NamedDecl *Decl, DeclContext *Ctx) {
1863 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) {
Douglas Gregor3b52b692011-11-03 17:41:55 +00001864 if (!Decl->isCXXClassMember())
Douglas Gregor03ba1882011-11-03 16:51:37 +00001865 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001866
Douglas Gregor03ba1882011-11-03 16:51:37 +00001867 QualType qType = Class->getTypeForDecl()->getCanonicalTypeInternal();
1868 AccessTarget Entity(Context, AccessedEntity::Member, Class,
1869 DeclAccessPair::make(Decl, Decl->getAccess()),
1870 qType);
1871 if (Entity.getAccess() == AS_public)
1872 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001873
Douglas Gregor03ba1882011-11-03 16:51:37 +00001874 EffectiveContext EC(CurContext);
1875 return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1876 }
1877
Douglas Gregor21ceb182011-11-03 19:00:24 +00001878 if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Decl)) {
1879 // @public and @package ivars are always accessible.
1880 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1881 Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
1882 return true;
Serge Pavlov64bc7032013-05-07 16:56:03 +00001883
Douglas Gregor21ceb182011-11-03 19:00:24 +00001884 // If we are inside a class or category implementation, determine the
1885 // interface we're in.
1886 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1887 if (ObjCMethodDecl *MD = getCurMethodDecl())
1888 ClassOfMethodDecl = MD->getClassInterface();
1889 else if (FunctionDecl *FD = getCurFunctionDecl()) {
1890 if (ObjCImplDecl *Impl
1891 = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1892 if (ObjCImplementationDecl *IMPD
1893 = dyn_cast<ObjCImplementationDecl>(Impl))
1894 ClassOfMethodDecl = IMPD->getClassInterface();
1895 else if (ObjCCategoryImplDecl* CatImplClass
1896 = dyn_cast<ObjCCategoryImplDecl>(Impl))
1897 ClassOfMethodDecl = CatImplClass->getClassInterface();
1898 }
1899 }
1900
1901 // If we're not in an interface, this ivar is inaccessible.
1902 if (!ClassOfMethodDecl)
1903 return false;
1904
1905 // If we're inside the same interface that owns the ivar, we're fine.
Douglas Gregor0b144e12011-12-15 00:29:59 +00001906 if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
Douglas Gregor21ceb182011-11-03 19:00:24 +00001907 return true;
1908
1909 // If the ivar is private, it's inaccessible.
1910 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1911 return false;
1912
1913 return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1914 }
1915
Douglas Gregor03ba1882011-11-03 16:51:37 +00001916 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001917}