blob: 541b7f927597b2d0b1421753e4fb12e7789b7b26 [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
Aaron Ballman574705e2014-03-13 15:41:46 +0000291 for (const auto &I : Derived->bases()) {
John McCalla8ae2222010-04-06 21:38:20 +0000292 const CXXRecordDecl *RD;
293
Aaron Ballman574705e2014-03-13 15:41:46 +0000294 QualType T = I.getType();
John McCalla8ae2222010-04-06 21:38:20 +0000295 if (const RecordType *RT = T->getAs<RecordType>()) {
296 RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall97205142010-05-04 05:11:27 +0000297 } else if (const InjectedClassNameType *IT
298 = T->getAs<InjectedClassNameType>()) {
299 RD = IT->getDecl();
John McCalla8ae2222010-04-06 21:38:20 +0000300 } else {
John McCalla8ae2222010-04-06 21:38:20 +0000301 assert(T->isDependentType() && "non-dependent base wasn't a record?");
302 OnFailure = AR_dependent;
303 continue;
304 }
305
306 RD = RD->getCanonicalDecl();
307 if (RD == Target) return AR_accessible;
John McCall97205142010-05-04 05:11:27 +0000308 if (CheckDependent && MightInstantiateTo(RD, Target))
309 OnFailure = AR_dependent;
310
John McCalla8ae2222010-04-06 21:38:20 +0000311 Queue.push_back(RD);
312 }
313
314 if (Queue.empty()) break;
315
Robert Wilhelm25284cc2013-08-23 16:11:15 +0000316 Derived = Queue.pop_back_val();
John McCalla8ae2222010-04-06 21:38:20 +0000317 }
318
319 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000320}
321
John McCalla8ae2222010-04-06 21:38:20 +0000322
John McCallc62bb642010-03-24 05:22:00 +0000323static bool MightInstantiateTo(Sema &S, DeclContext *Context,
324 DeclContext *Friend) {
325 if (Friend == Context)
326 return true;
327
328 assert(!Friend->isDependentContext() &&
329 "can't handle friends with dependent contexts here");
330
331 if (!Context->isDependentContext())
332 return false;
333
334 if (Friend->isFileContext())
335 return false;
336
337 // TODO: this is very conservative
338 return true;
339}
340
341// Asks whether the type in 'context' can ever instantiate to the type
342// in 'friend'.
343static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
344 if (Friend == Context)
345 return true;
346
347 if (!Friend->isDependentType() && !Context->isDependentType())
348 return false;
349
350 // TODO: this is very conservative.
351 return true;
352}
353
354static bool MightInstantiateTo(Sema &S,
355 FunctionDecl *Context,
356 FunctionDecl *Friend) {
357 if (Context->getDeclName() != Friend->getDeclName())
358 return false;
359
360 if (!MightInstantiateTo(S,
361 Context->getDeclContext(),
362 Friend->getDeclContext()))
363 return false;
364
365 CanQual<FunctionProtoType> FriendTy
366 = S.Context.getCanonicalType(Friend->getType())
367 ->getAs<FunctionProtoType>();
368 CanQual<FunctionProtoType> ContextTy
369 = S.Context.getCanonicalType(Context->getType())
370 ->getAs<FunctionProtoType>();
371
372 // There isn't any way that I know of to add qualifiers
373 // during instantiation.
374 if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
375 return false;
376
Alp Toker9cacbab2014-01-20 20:26:09 +0000377 if (FriendTy->getNumParams() != ContextTy->getNumParams())
John McCallc62bb642010-03-24 05:22:00 +0000378 return false;
379
Alp Toker314cc812014-01-25 16:55:45 +0000380 if (!MightInstantiateTo(S, ContextTy->getReturnType(),
381 FriendTy->getReturnType()))
John McCallc62bb642010-03-24 05:22:00 +0000382 return false;
383
Alp Toker9cacbab2014-01-20 20:26:09 +0000384 for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
385 if (!MightInstantiateTo(S, ContextTy->getParamType(I),
386 FriendTy->getParamType(I)))
John McCallc62bb642010-03-24 05:22:00 +0000387 return false;
388
389 return true;
390}
391
392static bool MightInstantiateTo(Sema &S,
393 FunctionTemplateDecl *Context,
394 FunctionTemplateDecl *Friend) {
395 return MightInstantiateTo(S,
396 Context->getTemplatedDecl(),
397 Friend->getTemplatedDecl());
398}
399
John McCalla8ae2222010-04-06 21:38:20 +0000400static AccessResult MatchesFriend(Sema &S,
401 const EffectiveContext &EC,
402 const CXXRecordDecl *Friend) {
John McCall39e82882010-03-17 20:01:29 +0000403 if (EC.includesClass(Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000404 return AR_accessible;
John McCall39e82882010-03-17 20:01:29 +0000405
John McCallc62bb642010-03-24 05:22:00 +0000406 if (EC.isDependent()) {
407 CanQualType FriendTy
408 = S.Context.getCanonicalType(S.Context.getTypeDeclType(Friend));
409
410 for (EffectiveContext::record_iterator
411 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
412 CanQualType ContextTy
413 = S.Context.getCanonicalType(S.Context.getTypeDeclType(*I));
414 if (MightInstantiateTo(S, ContextTy, FriendTy))
John McCalla8ae2222010-04-06 21:38:20 +0000415 return AR_dependent;
John McCallc62bb642010-03-24 05:22:00 +0000416 }
417 }
418
John McCalla8ae2222010-04-06 21:38:20 +0000419 return AR_inaccessible;
John McCall39e82882010-03-17 20:01:29 +0000420}
421
John McCalla8ae2222010-04-06 21:38:20 +0000422static AccessResult MatchesFriend(Sema &S,
423 const EffectiveContext &EC,
424 CanQualType Friend) {
John McCallc62bb642010-03-24 05:22:00 +0000425 if (const RecordType *RT = Friend->getAs<RecordType>())
426 return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
John McCall39e82882010-03-17 20:01:29 +0000427
John McCallc62bb642010-03-24 05:22:00 +0000428 // TODO: we can do better than this
429 if (Friend->isDependentType())
John McCalla8ae2222010-04-06 21:38:20 +0000430 return AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000431
John McCalla8ae2222010-04-06 21:38:20 +0000432 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000433}
434
435/// Determines whether the given friend class template matches
436/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000437static AccessResult MatchesFriend(Sema &S,
438 const EffectiveContext &EC,
439 ClassTemplateDecl *Friend) {
440 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000441
John McCall598b4402010-03-25 06:39:04 +0000442 // Check whether the friend is the template of a class in the
443 // context chain.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000444 for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
John McCallc62bb642010-03-24 05:22:00 +0000445 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
446 CXXRecordDecl *Record = *I;
447
John McCall598b4402010-03-25 06:39:04 +0000448 // Figure out whether the current class has a template:
John McCallc62bb642010-03-24 05:22:00 +0000449 ClassTemplateDecl *CTD;
450
451 // A specialization of the template...
452 if (isa<ClassTemplateSpecializationDecl>(Record)) {
453 CTD = cast<ClassTemplateSpecializationDecl>(Record)
454 ->getSpecializedTemplate();
455
456 // ... or the template pattern itself.
457 } else {
458 CTD = Record->getDescribedClassTemplate();
459 if (!CTD) continue;
460 }
461
462 // It's a match.
463 if (Friend == CTD->getCanonicalDecl())
John McCalla8ae2222010-04-06 21:38:20 +0000464 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000465
John McCall598b4402010-03-25 06:39:04 +0000466 // If the context isn't dependent, it can't be a dependent match.
467 if (!EC.isDependent())
468 continue;
469
John McCallc62bb642010-03-24 05:22:00 +0000470 // If the template names don't match, it can't be a dependent
Richard Smith3f1b5d02011-05-05 21:57:07 +0000471 // match.
472 if (CTD->getDeclName() != Friend->getDeclName())
John McCallc62bb642010-03-24 05:22:00 +0000473 continue;
474
475 // If the class's context can't instantiate to the friend's
476 // context, it can't be a dependent match.
477 if (!MightInstantiateTo(S, CTD->getDeclContext(),
478 Friend->getDeclContext()))
479 continue;
480
481 // Otherwise, it's a dependent match.
John McCalla8ae2222010-04-06 21:38:20 +0000482 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000483 }
484
John McCallc62bb642010-03-24 05:22:00 +0000485 return OnFailure;
486}
487
488/// Determines whether the given friend function matches anything in
489/// the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000490static AccessResult MatchesFriend(Sema &S,
491 const EffectiveContext &EC,
492 FunctionDecl *Friend) {
493 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000494
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000495 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000496 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
497 if (Friend == *I)
John McCalla8ae2222010-04-06 21:38:20 +0000498 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +0000499
John McCall3dc81f72010-03-27 06:55:49 +0000500 if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000501 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000502 }
John McCallc62bb642010-03-24 05:22:00 +0000503
John McCall3dc81f72010-03-27 06:55:49 +0000504 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000505}
506
507/// Determines whether the given friend function template matches
508/// anything in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000509static AccessResult MatchesFriend(Sema &S,
510 const EffectiveContext &EC,
511 FunctionTemplateDecl *Friend) {
512 if (EC.Functions.empty()) return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000513
John McCalla8ae2222010-04-06 21:38:20 +0000514 AccessResult OnFailure = AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +0000515
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000516 for (SmallVectorImpl<FunctionDecl*>::const_iterator
John McCall3dc81f72010-03-27 06:55:49 +0000517 I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
John McCallc62bb642010-03-24 05:22:00 +0000518
John McCall3dc81f72010-03-27 06:55:49 +0000519 FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
520 if (!FTD)
521 FTD = (*I)->getDescribedFunctionTemplate();
522 if (!FTD)
523 continue;
John McCallc62bb642010-03-24 05:22:00 +0000524
John McCall3dc81f72010-03-27 06:55:49 +0000525 FTD = FTD->getCanonicalDecl();
526
527 if (Friend == FTD)
John McCalla8ae2222010-04-06 21:38:20 +0000528 return AR_accessible;
John McCall3dc81f72010-03-27 06:55:49 +0000529
530 if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
John McCalla8ae2222010-04-06 21:38:20 +0000531 OnFailure = AR_dependent;
John McCall3dc81f72010-03-27 06:55:49 +0000532 }
533
534 return OnFailure;
John McCallc62bb642010-03-24 05:22:00 +0000535}
536
537/// Determines whether the given friend declaration matches anything
538/// in the effective context.
John McCalla8ae2222010-04-06 21:38:20 +0000539static AccessResult MatchesFriend(Sema &S,
540 const EffectiveContext &EC,
541 FriendDecl *FriendD) {
John McCall2c2eb122010-10-16 06:59:13 +0000542 // Whitelist accesses if there's an invalid or unsupported friend
543 // declaration.
544 if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
John McCallde3fd222010-10-12 23:13:28 +0000545 return AR_accessible;
546
John McCall15ad0962010-03-25 18:04:51 +0000547 if (TypeSourceInfo *T = FriendD->getFriendType())
548 return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
John McCallc62bb642010-03-24 05:22:00 +0000549
550 NamedDecl *Friend
551 = cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
John McCall39e82882010-03-17 20:01:29 +0000552
553 // FIXME: declarations with dependent or templated scope.
554
John McCallc62bb642010-03-24 05:22:00 +0000555 if (isa<ClassTemplateDecl>(Friend))
556 return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000557
John McCallc62bb642010-03-24 05:22:00 +0000558 if (isa<FunctionTemplateDecl>(Friend))
559 return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000560
John McCallc62bb642010-03-24 05:22:00 +0000561 if (isa<CXXRecordDecl>(Friend))
562 return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000563
John McCallc62bb642010-03-24 05:22:00 +0000564 assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
565 return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
John McCall39e82882010-03-17 20:01:29 +0000566}
567
John McCalla8ae2222010-04-06 21:38:20 +0000568static AccessResult GetFriendKind(Sema &S,
569 const EffectiveContext &EC,
570 const CXXRecordDecl *Class) {
571 AccessResult OnFailure = AR_inaccessible;
John McCallfb803d72010-03-17 04:58:56 +0000572
John McCall16927f62010-03-12 01:19:31 +0000573 // Okay, check friends.
574 for (CXXRecordDecl::friend_iterator I = Class->friend_begin(),
575 E = Class->friend_end(); I != E; ++I) {
576 FriendDecl *Friend = *I;
577
John McCall39e82882010-03-17 20:01:29 +0000578 switch (MatchesFriend(S, EC, Friend)) {
John McCalla8ae2222010-04-06 21:38:20 +0000579 case AR_accessible:
580 return AR_accessible;
John McCall16927f62010-03-12 01:19:31 +0000581
John McCalla8ae2222010-04-06 21:38:20 +0000582 case AR_inaccessible:
583 continue;
584
585 case AR_dependent:
586 OnFailure = AR_dependent;
John McCall39e82882010-03-17 20:01:29 +0000587 break;
John McCall16927f62010-03-12 01:19:31 +0000588 }
John McCall16927f62010-03-12 01:19:31 +0000589 }
590
591 // That's it, give up.
John McCallfb803d72010-03-17 04:58:56 +0000592 return OnFailure;
John McCall5b0829a2010-02-10 09:31:12 +0000593}
594
John McCall96329672010-08-28 07:56:00 +0000595namespace {
596
597/// A helper class for checking for a friend which will grant access
598/// to a protected instance member.
599struct ProtectedFriendContext {
600 Sema &S;
601 const EffectiveContext &EC;
602 const CXXRecordDecl *NamingClass;
603 bool CheckDependent;
604 bool EverDependent;
605
606 /// The path down to the current base class.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000607 SmallVector<const CXXRecordDecl*, 20> CurPath;
John McCall96329672010-08-28 07:56:00 +0000608
609 ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
610 const CXXRecordDecl *InstanceContext,
611 const CXXRecordDecl *NamingClass)
612 : S(S), EC(EC), NamingClass(NamingClass),
613 CheckDependent(InstanceContext->isDependentContext() ||
614 NamingClass->isDependentContext()),
615 EverDependent(false) {}
616
John McCall1177ff12010-08-28 08:47:21 +0000617 /// Check classes in the current path for friendship, starting at
618 /// the given index.
619 bool checkFriendshipAlongPath(unsigned I) {
620 assert(I < CurPath.size());
621 for (unsigned E = CurPath.size(); I != E; ++I) {
622 switch (GetFriendKind(S, EC, CurPath[I])) {
John McCall96329672010-08-28 07:56:00 +0000623 case AR_accessible: return true;
624 case AR_inaccessible: continue;
625 case AR_dependent: EverDependent = true; continue;
626 }
627 }
628 return false;
629 }
630
631 /// Perform a search starting at the given class.
John McCall1177ff12010-08-28 08:47:21 +0000632 ///
633 /// PrivateDepth is the index of the last (least derived) class
634 /// along the current path such that a notional public member of
635 /// the final class in the path would have access in that class.
636 bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
John McCall96329672010-08-28 07:56:00 +0000637 // If we ever reach the naming class, check the current path for
638 // friendship. We can also stop recursing because we obviously
639 // won't find the naming class there again.
John McCall1177ff12010-08-28 08:47:21 +0000640 if (Cur == NamingClass)
641 return checkFriendshipAlongPath(PrivateDepth);
John McCall96329672010-08-28 07:56:00 +0000642
643 if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
644 EverDependent = true;
645
646 // Recurse into the base classes.
Aaron Ballman574705e2014-03-13 15:41:46 +0000647 for (const auto &I : Cur->bases()) {
John McCall1177ff12010-08-28 08:47:21 +0000648 // If this is private inheritance, then a public member of the
649 // base will not have any access in classes derived from Cur.
650 unsigned BasePrivateDepth = PrivateDepth;
Aaron Ballman574705e2014-03-13 15:41:46 +0000651 if (I.getAccessSpecifier() == AS_private)
John McCall1177ff12010-08-28 08:47:21 +0000652 BasePrivateDepth = CurPath.size() - 1;
John McCall96329672010-08-28 07:56:00 +0000653
654 const CXXRecordDecl *RD;
655
Aaron Ballman574705e2014-03-13 15:41:46 +0000656 QualType T = I.getType();
John McCall96329672010-08-28 07:56:00 +0000657 if (const RecordType *RT = T->getAs<RecordType>()) {
658 RD = cast<CXXRecordDecl>(RT->getDecl());
659 } else if (const InjectedClassNameType *IT
660 = T->getAs<InjectedClassNameType>()) {
661 RD = IT->getDecl();
662 } else {
663 assert(T->isDependentType() && "non-dependent base wasn't a record?");
664 EverDependent = true;
665 continue;
666 }
667
668 // Recurse. We don't need to clean up if this returns true.
John McCall1177ff12010-08-28 08:47:21 +0000669 CurPath.push_back(RD);
670 if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
671 return true;
672 CurPath.pop_back();
John McCall96329672010-08-28 07:56:00 +0000673 }
674
John McCall96329672010-08-28 07:56:00 +0000675 return false;
676 }
John McCall1177ff12010-08-28 08:47:21 +0000677
678 bool findFriendship(const CXXRecordDecl *Cur) {
679 assert(CurPath.empty());
680 CurPath.push_back(Cur);
681 return findFriendship(Cur, 0);
682 }
John McCall96329672010-08-28 07:56:00 +0000683};
684}
685
686/// Search for a class P that EC is a friend of, under the constraint
John McCall5dadb652012-04-07 03:04:20 +0000687/// InstanceContext <= P
688/// if InstanceContext exists, or else
689/// NamingClass <= P
John McCall96329672010-08-28 07:56:00 +0000690/// and with the additional restriction that a protected member of
John McCall5dadb652012-04-07 03:04:20 +0000691/// NamingClass would have some natural access in P, which implicitly
692/// imposes the constraint that P <= NamingClass.
John McCall96329672010-08-28 07:56:00 +0000693///
John McCall5dadb652012-04-07 03:04:20 +0000694/// This isn't quite the condition laid out in the standard.
695/// Instead of saying that a notional protected member of NamingClass
696/// would have to have some natural access in P, it says the actual
697/// target has to have some natural access in P, which opens up the
698/// possibility that the target (which is not necessarily a member
699/// of NamingClass) might be more accessible along some path not
700/// passing through it. That's really a bad idea, though, because it
John McCall96329672010-08-28 07:56:00 +0000701/// introduces two problems:
John McCall5dadb652012-04-07 03:04:20 +0000702/// - Most importantly, it breaks encapsulation because you can
703/// access a forbidden base class's members by directly subclassing
704/// it elsewhere.
705/// - It also makes access substantially harder to compute because it
John McCall96329672010-08-28 07:56:00 +0000706/// breaks the hill-climbing algorithm: knowing that the target is
707/// accessible in some base class would no longer let you change
708/// the question solely to whether the base class is accessible,
709/// because the original target might have been more accessible
710/// because of crazy subclassing.
711/// So we don't implement that.
712static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
713 const CXXRecordDecl *InstanceContext,
714 const CXXRecordDecl *NamingClass) {
John McCall5dadb652012-04-07 03:04:20 +0000715 assert(InstanceContext == 0 ||
716 InstanceContext->getCanonicalDecl() == InstanceContext);
John McCall96329672010-08-28 07:56:00 +0000717 assert(NamingClass->getCanonicalDecl() == NamingClass);
718
John McCall5dadb652012-04-07 03:04:20 +0000719 // If we don't have an instance context, our constraints give us
720 // that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
721 // This is just the usual friendship check.
722 if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
723
John McCall96329672010-08-28 07:56:00 +0000724 ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
725 if (PRC.findFriendship(InstanceContext)) return AR_accessible;
726 if (PRC.EverDependent) return AR_dependent;
727 return AR_inaccessible;
728}
729
John McCalla8ae2222010-04-06 21:38:20 +0000730static AccessResult HasAccess(Sema &S,
731 const EffectiveContext &EC,
732 const CXXRecordDecl *NamingClass,
733 AccessSpecifier Access,
734 const AccessTarget &Target) {
John McCalld79b4d82010-04-02 00:03:43 +0000735 assert(NamingClass->getCanonicalDecl() == NamingClass &&
736 "declaration should be canonicalized before being passed here");
737
John McCalla8ae2222010-04-06 21:38:20 +0000738 if (Access == AS_public) return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000739 assert(Access == AS_private || Access == AS_protected);
740
John McCalla8ae2222010-04-06 21:38:20 +0000741 AccessResult OnFailure = AR_inaccessible;
742
John McCalld79b4d82010-04-02 00:03:43 +0000743 for (EffectiveContext::record_iterator
744 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
745 // All the declarations in EC have been canonicalized, so pointer
746 // equality from this point on will work fine.
747 const CXXRecordDecl *ECRecord = *I;
748
749 // [B2] and [M2]
John McCalla8ae2222010-04-06 21:38:20 +0000750 if (Access == AS_private) {
751 if (ECRecord == NamingClass)
752 return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +0000753
John McCall97205142010-05-04 05:11:27 +0000754 if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
755 OnFailure = AR_dependent;
756
John McCalld79b4d82010-04-02 00:03:43 +0000757 // [B3] and [M3]
John McCalla8ae2222010-04-06 21:38:20 +0000758 } else {
759 assert(Access == AS_protected);
760 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
761 case AR_accessible: break;
762 case AR_inaccessible: continue;
763 case AR_dependent: OnFailure = AR_dependent; continue;
764 }
765
John McCalla8ae2222010-04-06 21:38:20 +0000766 // C++ [class.protected]p1:
767 // An additional access check beyond those described earlier in
768 // [class.access] is applied when a non-static data member or
769 // non-static member function is a protected member of its naming
770 // class. As described earlier, access to a protected member is
771 // granted because the reference occurs in a friend or member of
772 // some class C. If the access is to form a pointer to member,
773 // the nested-name-specifier shall name C or a class derived from
774 // C. All other accesses involve a (possibly implicit) object
775 // expression. In this case, the class of the object expression
776 // shall be C or a class derived from C.
777 //
John McCall5dadb652012-04-07 03:04:20 +0000778 // We interpret this as a restriction on [M3].
779
780 // In this part of the code, 'C' is just our context class ECRecord.
781
782 // These rules are different if we don't have an instance context.
783 if (!Target.hasInstanceContext()) {
784 // If it's not an instance member, these restrictions don't apply.
785 if (!Target.isInstanceMember()) return AR_accessible;
786
787 // If it's an instance member, use the pointer-to-member rule
788 // that the naming class has to be derived from the effective
789 // context.
790
Francois Picheta39371c2012-04-17 12:35:05 +0000791 // Emulate a MSVC bug where the creation of pointer-to-member
792 // to protected member of base class is allowed but only from
Francois Pichet52d38982012-04-19 07:48:57 +0000793 // static member functions.
Alp Tokerbfa39342014-01-14 12:51:41 +0000794 if (S.getLangOpts().MSVCCompat && !EC.Functions.empty())
Francois Pichet5b061f02012-04-18 03:24:38 +0000795 if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
796 if (MD->isStatic()) return AR_accessible;
Francois Picheta39371c2012-04-17 12:35:05 +0000797
John McCall5dadb652012-04-07 03:04:20 +0000798 // Despite the standard's confident wording, there is a case
799 // where you can have an instance member that's neither in a
800 // pointer-to-member expression nor in a member access: when
801 // it names a field in an unevaluated context that can't be an
802 // implicit member. Pending clarification, we just apply the
803 // same naming-class restriction here.
804 // FIXME: we're probably not correctly adding the
805 // protected-member restriction when we retroactively convert
806 // an expression to being evaluated.
807
808 // We know that ECRecord derives from NamingClass. The
809 // restriction says to check whether NamingClass derives from
810 // ECRecord, but that's not really necessary: two distinct
811 // classes can't be recursively derived from each other. So
812 // along this path, we just need to check whether the classes
813 // are equal.
814 if (NamingClass == ECRecord) return AR_accessible;
815
816 // Otherwise, this context class tells us nothing; on to the next.
817 continue;
818 }
819
820 assert(Target.isInstanceMember());
821
822 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
823 if (!InstanceContext) {
824 OnFailure = AR_dependent;
825 continue;
826 }
827
John McCalla8ae2222010-04-06 21:38:20 +0000828 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
829 case AR_accessible: return AR_accessible;
830 case AR_inaccessible: continue;
831 case AR_dependent: OnFailure = AR_dependent; continue;
832 }
833 }
John McCalld79b4d82010-04-02 00:03:43 +0000834 }
835
John McCall96329672010-08-28 07:56:00 +0000836 // [M3] and [B3] say that, if the target is protected in N, we grant
837 // access if the access occurs in a friend or member of some class P
838 // that's a subclass of N and where the target has some natural
839 // access in P. The 'member' aspect is easy to handle because P
840 // would necessarily be one of the effective-context records, and we
841 // address that above. The 'friend' aspect is completely ridiculous
842 // to implement because there are no restrictions at all on P
843 // *unless* the [class.protected] restriction applies. If it does,
844 // however, we should ignore whether the naming class is a friend,
845 // and instead rely on whether any potential P is a friend.
John McCall5dadb652012-04-07 03:04:20 +0000846 if (Access == AS_protected && Target.isInstanceMember()) {
847 // Compute the instance context if possible.
848 const CXXRecordDecl *InstanceContext = 0;
849 if (Target.hasInstanceContext()) {
850 InstanceContext = Target.resolveInstanceContext(S);
851 if (!InstanceContext) return AR_dependent;
852 }
853
John McCall96329672010-08-28 07:56:00 +0000854 switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
855 case AR_accessible: return AR_accessible;
John McCalla8ae2222010-04-06 21:38:20 +0000856 case AR_inaccessible: return OnFailure;
857 case AR_dependent: return AR_dependent;
858 }
John McCallc6af8f42010-08-28 08:10:32 +0000859 llvm_unreachable("impossible friendship kind");
John McCalla8ae2222010-04-06 21:38:20 +0000860 }
861
862 switch (GetFriendKind(S, EC, NamingClass)) {
863 case AR_accessible: return AR_accessible;
864 case AR_inaccessible: return OnFailure;
865 case AR_dependent: return AR_dependent;
866 }
867
868 // Silence bogus warnings
869 llvm_unreachable("impossible friendship kind");
John McCalld79b4d82010-04-02 00:03:43 +0000870}
871
John McCall5b0829a2010-02-10 09:31:12 +0000872/// Finds the best path from the naming class to the declaring class,
873/// taking friend declarations into account.
874///
John McCalld79b4d82010-04-02 00:03:43 +0000875/// C++0x [class.access.base]p5:
876/// A member m is accessible at the point R when named in class N if
877/// [M1] m as a member of N is public, or
878/// [M2] m as a member of N is private, and R occurs in a member or
879/// friend of class N, or
880/// [M3] m as a member of N is protected, and R occurs in a member or
881/// friend of class N, or in a member or friend of a class P
882/// derived from N, where m as a member of P is public, private,
883/// or protected, or
884/// [M4] there exists a base class B of N that is accessible at R, and
885/// m is accessible at R when named in class B.
886///
887/// C++0x [class.access.base]p4:
888/// A base class B of N is accessible at R, if
889/// [B1] an invented public member of B would be a public member of N, or
890/// [B2] R occurs in a member or friend of class N, and an invented public
891/// member of B would be a private or protected member of N, or
892/// [B3] R occurs in a member or friend of a class P derived from N, and an
893/// invented public member of B would be a private or protected member
894/// of P, or
895/// [B4] there exists a class S such that B is a base class of S accessible
896/// at R and S is a base class of N accessible at R.
897///
898/// Along a single inheritance path we can restate both of these
899/// iteratively:
900///
901/// First, we note that M1-4 are equivalent to B1-4 if the member is
902/// treated as a notional base of its declaring class with inheritance
903/// access equivalent to the member's access. Therefore we need only
904/// ask whether a class B is accessible from a class N in context R.
905///
906/// Let B_1 .. B_n be the inheritance path in question (i.e. where
907/// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
908/// B_i). For i in 1..n, we will calculate ACAB(i), the access to the
909/// closest accessible base in the path:
910/// Access(a, b) = (* access on the base specifier from a to b *)
911/// Merge(a, forbidden) = forbidden
912/// Merge(a, private) = forbidden
913/// Merge(a, b) = min(a,b)
914/// Accessible(c, forbidden) = false
915/// Accessible(c, private) = (R is c) || IsFriend(c, R)
916/// Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
917/// Accessible(c, public) = true
918/// ACAB(n) = public
919/// ACAB(i) =
920/// let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
921/// if Accessible(B_i, AccessToBase) then public else AccessToBase
922///
Sylvestre Ledru33b5baf2012-09-27 10:16:10 +0000923/// B is an accessible base of N at R iff ACAB(1) = public.
John McCalld79b4d82010-04-02 00:03:43 +0000924///
John McCalla8ae2222010-04-06 21:38:20 +0000925/// \param FinalAccess the access of the "final step", or AS_public if
John McCalla332b952010-03-18 23:49:19 +0000926/// there is no final step.
John McCall5b0829a2010-02-10 09:31:12 +0000927/// \return null if friendship is dependent
928static CXXBasePath *FindBestPath(Sema &S,
929 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +0000930 AccessTarget &Target,
John McCalla332b952010-03-18 23:49:19 +0000931 AccessSpecifier FinalAccess,
John McCall5b0829a2010-02-10 09:31:12 +0000932 CXXBasePaths &Paths) {
933 // Derive the paths to the desired base.
John McCalla8ae2222010-04-06 21:38:20 +0000934 const CXXRecordDecl *Derived = Target.getNamingClass();
935 const CXXRecordDecl *Base = Target.getDeclaringClass();
936
937 // FIXME: fail correctly when there are dependent paths.
938 bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
939 Paths);
John McCall5b0829a2010-02-10 09:31:12 +0000940 assert(isDerived && "derived class not actually derived from base");
941 (void) isDerived;
942
943 CXXBasePath *BestPath = 0;
944
John McCalla332b952010-03-18 23:49:19 +0000945 assert(FinalAccess != AS_none && "forbidden access after declaring class");
946
John McCallc62bb642010-03-24 05:22:00 +0000947 bool AnyDependent = false;
948
John McCall5b0829a2010-02-10 09:31:12 +0000949 // Derive the friend-modified access along each path.
950 for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
951 PI != PE; ++PI) {
John McCalla8ae2222010-04-06 21:38:20 +0000952 AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +0000953
954 // Walk through the path backwards.
John McCalla332b952010-03-18 23:49:19 +0000955 AccessSpecifier PathAccess = FinalAccess;
John McCall5b0829a2010-02-10 09:31:12 +0000956 CXXBasePath::iterator I = PI->end(), E = PI->begin();
957 while (I != E) {
958 --I;
959
John McCalla332b952010-03-18 23:49:19 +0000960 assert(PathAccess != AS_none);
961
962 // If the declaration is a private member of a base class, there
963 // is no level of friendship in derived classes that can make it
964 // accessible.
965 if (PathAccess == AS_private) {
966 PathAccess = AS_none;
967 break;
968 }
969
John McCalla8ae2222010-04-06 21:38:20 +0000970 const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
971
John McCall5b0829a2010-02-10 09:31:12 +0000972 AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
John McCalld79b4d82010-04-02 00:03:43 +0000973 PathAccess = std::max(PathAccess, BaseAccess);
John McCalla8ae2222010-04-06 21:38:20 +0000974
975 switch (HasAccess(S, EC, NC, PathAccess, Target)) {
976 case AR_inaccessible: break;
977 case AR_accessible:
978 PathAccess = AS_public;
979
980 // Future tests are not against members and so do not have
981 // instance context.
982 Target.suppressInstanceContext();
983 break;
984 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +0000985 AnyDependent = true;
986 goto Next;
John McCall5b0829a2010-02-10 09:31:12 +0000987 }
John McCall5b0829a2010-02-10 09:31:12 +0000988 }
989
990 // Note that we modify the path's Access field to the
991 // friend-modified access.
992 if (BestPath == 0 || PathAccess < BestPath->Access) {
993 BestPath = &*PI;
994 BestPath->Access = PathAccess;
John McCallc62bb642010-03-24 05:22:00 +0000995
996 // Short-circuit if we found a public path.
997 if (BestPath->Access == AS_public)
998 return BestPath;
John McCall5b0829a2010-02-10 09:31:12 +0000999 }
John McCallc62bb642010-03-24 05:22:00 +00001000
1001 Next: ;
John McCall5b0829a2010-02-10 09:31:12 +00001002 }
1003
John McCallc62bb642010-03-24 05:22:00 +00001004 assert((!BestPath || BestPath->Access != AS_public) &&
1005 "fell out of loop with public path");
1006
1007 // We didn't find a public path, but at least one path was subject
1008 // to dependent friendship, so delay the check.
1009 if (AnyDependent)
1010 return 0;
1011
John McCall5b0829a2010-02-10 09:31:12 +00001012 return BestPath;
1013}
1014
John McCall417e7442010-09-03 04:56:05 +00001015/// Given that an entity has protected natural access, check whether
1016/// access might be denied because of the protected member access
1017/// restriction.
1018///
1019/// \return true if a note was emitted
1020static bool TryDiagnoseProtectedAccess(Sema &S, const EffectiveContext &EC,
1021 AccessTarget &Target) {
1022 // Only applies to instance accesses.
John McCall5dadb652012-04-07 03:04:20 +00001023 if (!Target.isInstanceMember())
John McCall417e7442010-09-03 04:56:05 +00001024 return false;
John McCall417e7442010-09-03 04:56:05 +00001025
John McCall5dadb652012-04-07 03:04:20 +00001026 assert(Target.isMemberAccess());
1027
John McCalld010ac92013-02-27 00:08:19 +00001028 const CXXRecordDecl *NamingClass = Target.getEffectiveNamingClass();
John McCall417e7442010-09-03 04:56:05 +00001029
1030 for (EffectiveContext::record_iterator
1031 I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
1032 const CXXRecordDecl *ECRecord = *I;
John McCall5dadb652012-04-07 03:04:20 +00001033 switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
John McCall417e7442010-09-03 04:56:05 +00001034 case AR_accessible: break;
1035 case AR_inaccessible: continue;
1036 case AR_dependent: continue;
1037 }
1038
1039 // The effective context is a subclass of the declaring class.
John McCall5dadb652012-04-07 03:04:20 +00001040 // Check whether the [class.protected] restriction is limiting
1041 // access.
John McCall417e7442010-09-03 04:56:05 +00001042
1043 // To get this exactly right, this might need to be checked more
1044 // holistically; it's not necessarily the case that gaining
1045 // access here would grant us access overall.
1046
John McCall5dadb652012-04-07 03:04:20 +00001047 NamedDecl *D = Target.getTargetDecl();
1048
1049 // If we don't have an instance context, [class.protected] says the
1050 // naming class has to equal the context class.
1051 if (!Target.hasInstanceContext()) {
1052 // If it does, the restriction doesn't apply.
1053 if (NamingClass == ECRecord) continue;
1054
1055 // TODO: it would be great to have a fixit here, since this is
1056 // such an obvious error.
1057 S.Diag(D->getLocation(), diag::note_access_protected_restricted_noobject)
1058 << S.Context.getTypeDeclType(ECRecord);
1059 return true;
1060 }
1061
John McCall417e7442010-09-03 04:56:05 +00001062 const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
1063 assert(InstanceContext && "diagnosing dependent access");
1064
1065 switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
1066 case AR_accessible: continue;
1067 case AR_dependent: continue;
1068 case AR_inaccessible:
John McCall5dadb652012-04-07 03:04:20 +00001069 break;
1070 }
1071
1072 // Okay, the restriction seems to be what's limiting us.
1073
1074 // Use a special diagnostic for constructors and destructors.
1075 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D) ||
1076 (isa<FunctionTemplateDecl>(D) &&
1077 isa<CXXConstructorDecl>(
1078 cast<FunctionTemplateDecl>(D)->getTemplatedDecl()))) {
Alp Tokera2794f92014-01-22 07:29:52 +00001079 return S.Diag(D->getLocation(),
1080 diag::note_access_protected_restricted_ctordtor)
1081 << isa<CXXDestructorDecl>(D->getAsFunction());
John McCall417e7442010-09-03 04:56:05 +00001082 }
John McCall5dadb652012-04-07 03:04:20 +00001083
1084 // Otherwise, use the generic diagnostic.
Alp Tokera2794f92014-01-22 07:29:52 +00001085 return S.Diag(D->getLocation(),
1086 diag::note_access_protected_restricted_object)
1087 << S.Context.getTypeDeclType(ECRecord);
John McCall417e7442010-09-03 04:56:05 +00001088 }
1089
1090 return false;
1091}
1092
John McCalld010ac92013-02-27 00:08:19 +00001093/// We are unable to access a given declaration due to its direct
1094/// access control; diagnose that.
1095static void diagnoseBadDirectAccess(Sema &S,
1096 const EffectiveContext &EC,
1097 AccessTarget &entity) {
1098 assert(entity.isMemberAccess());
1099 NamedDecl *D = entity.getTargetDecl();
1100
1101 if (D->getAccess() == AS_protected &&
1102 TryDiagnoseProtectedAccess(S, EC, entity))
1103 return;
1104
1105 // Find an original declaration.
1106 while (D->isOutOfLine()) {
1107 NamedDecl *PrevDecl = 0;
1108 if (VarDecl *VD = dyn_cast<VarDecl>(D))
1109 PrevDecl = VD->getPreviousDecl();
1110 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
1111 PrevDecl = FD->getPreviousDecl();
1112 else if (TypedefNameDecl *TND = dyn_cast<TypedefNameDecl>(D))
1113 PrevDecl = TND->getPreviousDecl();
1114 else if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1115 if (isa<RecordDecl>(D) && cast<RecordDecl>(D)->isInjectedClassName())
1116 break;
1117 PrevDecl = TD->getPreviousDecl();
1118 }
1119 if (!PrevDecl) break;
1120 D = PrevDecl;
1121 }
1122
1123 CXXRecordDecl *DeclaringClass = FindDeclaringClass(D);
1124 Decl *ImmediateChild;
1125 if (D->getDeclContext() == DeclaringClass)
1126 ImmediateChild = D;
1127 else {
1128 DeclContext *DC = D->getDeclContext();
1129 while (DC->getParent() != DeclaringClass)
1130 DC = DC->getParent();
1131 ImmediateChild = cast<Decl>(DC);
1132 }
1133
1134 // Check whether there's an AccessSpecDecl preceding this in the
1135 // chain of the DeclContext.
1136 bool isImplicit = true;
Aaron Ballman629afae2014-03-07 19:56:05 +00001137 for (const auto *I : DeclaringClass->decls()) {
1138 if (I == ImmediateChild) break;
1139 if (isa<AccessSpecDecl>(I)) {
John McCalld010ac92013-02-27 00:08:19 +00001140 isImplicit = false;
1141 break;
1142 }
1143 }
1144
1145 S.Diag(D->getLocation(), diag::note_access_natural)
1146 << (unsigned) (D->getAccess() == AS_protected)
1147 << isImplicit;
1148}
1149
John McCall5b0829a2010-02-10 09:31:12 +00001150/// Diagnose the path which caused the given declaration or base class
1151/// to become inaccessible.
1152static void DiagnoseAccessPath(Sema &S,
1153 const EffectiveContext &EC,
John McCalld010ac92013-02-27 00:08:19 +00001154 AccessTarget &entity) {
1155 // Save the instance context to preserve invariants.
1156 AccessTarget::SavedInstanceContext _ = entity.saveInstanceContext();
John McCalld79b4d82010-04-02 00:03:43 +00001157
John McCalld010ac92013-02-27 00:08:19 +00001158 // This basically repeats the main algorithm but keeps some more
1159 // information.
John McCalld79b4d82010-04-02 00:03:43 +00001160
John McCalld010ac92013-02-27 00:08:19 +00001161 // The natural access so far.
1162 AccessSpecifier accessSoFar = AS_public;
John McCall417e7442010-09-03 04:56:05 +00001163
John McCalld010ac92013-02-27 00:08:19 +00001164 // Check whether we have special rights to the declaring class.
1165 if (entity.isMemberAccess()) {
1166 NamedDecl *D = entity.getTargetDecl();
1167 accessSoFar = D->getAccess();
1168 const CXXRecordDecl *declaringClass = entity.getDeclaringClass();
John McCallf551aca2010-10-20 08:15:06 +00001169
John McCalld010ac92013-02-27 00:08:19 +00001170 switch (HasAccess(S, EC, declaringClass, accessSoFar, entity)) {
1171 // If the declaration is accessible when named in its declaring
1172 // class, then we must be constrained by the path.
1173 case AR_accessible:
1174 accessSoFar = AS_public;
1175 entity.suppressInstanceContext();
1176 break;
John McCallf551aca2010-10-20 08:15:06 +00001177
John McCalld010ac92013-02-27 00:08:19 +00001178 case AR_inaccessible:
1179 if (accessSoFar == AS_private ||
1180 declaringClass == entity.getEffectiveNamingClass())
1181 return diagnoseBadDirectAccess(S, EC, entity);
1182 break;
John McCall5b0829a2010-02-10 09:31:12 +00001183
John McCalla8ae2222010-04-06 21:38:20 +00001184 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001185 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001186 }
1187 }
1188
John McCalld010ac92013-02-27 00:08:19 +00001189 CXXBasePaths paths;
1190 CXXBasePath &path = *FindBestPath(S, EC, entity, accessSoFar, paths);
1191 assert(path.Access != AS_public);
John McCall5b0829a2010-02-10 09:31:12 +00001192
John McCalld010ac92013-02-27 00:08:19 +00001193 CXXBasePath::iterator i = path.end(), e = path.begin();
1194 CXXBasePath::iterator constrainingBase = i;
1195 while (i != e) {
1196 --i;
John McCall5b0829a2010-02-10 09:31:12 +00001197
John McCalld010ac92013-02-27 00:08:19 +00001198 assert(accessSoFar != AS_none && accessSoFar != AS_private);
John McCall5b0829a2010-02-10 09:31:12 +00001199
John McCalld010ac92013-02-27 00:08:19 +00001200 // Is the entity accessible when named in the deriving class, as
1201 // modified by the base specifier?
1202 const CXXRecordDecl *derivingClass = i->Class->getCanonicalDecl();
1203 const CXXBaseSpecifier *base = i->Base;
John McCall5b0829a2010-02-10 09:31:12 +00001204
John McCalld010ac92013-02-27 00:08:19 +00001205 // If the access to this base is worse than the access we have to
1206 // the declaration, remember it.
1207 AccessSpecifier baseAccess = base->getAccessSpecifier();
1208 if (baseAccess > accessSoFar) {
1209 constrainingBase = i;
1210 accessSoFar = baseAccess;
1211 }
1212
1213 switch (HasAccess(S, EC, derivingClass, accessSoFar, entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001214 case AR_inaccessible: break;
John McCalld010ac92013-02-27 00:08:19 +00001215 case AR_accessible:
1216 accessSoFar = AS_public;
1217 entity.suppressInstanceContext();
1218 constrainingBase = 0;
1219 break;
John McCalla8ae2222010-04-06 21:38:20 +00001220 case AR_dependent:
John McCalld010ac92013-02-27 00:08:19 +00001221 llvm_unreachable("cannot diagnose dependent access");
John McCall5b0829a2010-02-10 09:31:12 +00001222 }
1223
John McCalld010ac92013-02-27 00:08:19 +00001224 // If this was private inheritance, but we don't have access to
1225 // the deriving class, we're done.
1226 if (accessSoFar == AS_private) {
1227 assert(baseAccess == AS_private);
1228 assert(constrainingBase == i);
1229 break;
John McCall5b0829a2010-02-10 09:31:12 +00001230 }
1231 }
1232
John McCalld010ac92013-02-27 00:08:19 +00001233 // If we don't have a constraining base, the access failure must be
1234 // due to the original declaration.
1235 if (constrainingBase == path.end())
1236 return diagnoseBadDirectAccess(S, EC, entity);
1237
1238 // We're constrained by inheritance, but we want to say
1239 // "declared private here" if we're diagnosing a hierarchy
1240 // conversion and this is the final step.
1241 unsigned diagnostic;
1242 if (entity.isMemberAccess() ||
1243 constrainingBase + 1 != path.end()) {
1244 diagnostic = diag::note_access_constrained_by_path;
1245 } else {
1246 diagnostic = diag::note_access_natural;
1247 }
1248
1249 const CXXBaseSpecifier *base = constrainingBase->Base;
1250
1251 S.Diag(base->getSourceRange().getBegin(), diagnostic)
1252 << base->getSourceRange()
1253 << (base->getAccessSpecifier() == AS_protected)
1254 << (base->getAccessSpecifierAsWritten() == AS_none);
1255
1256 if (entity.isMemberAccess())
1257 S.Diag(entity.getTargetDecl()->getLocation(), diag::note_field_decl);
John McCall5b0829a2010-02-10 09:31:12 +00001258}
1259
John McCall1064d7e2010-03-16 05:22:47 +00001260static void DiagnoseBadAccess(Sema &S, SourceLocation Loc,
John McCall5b0829a2010-02-10 09:31:12 +00001261 const EffectiveContext &EC,
John McCalla8ae2222010-04-06 21:38:20 +00001262 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001263 const CXXRecordDecl *NamingClass = Entity.getNamingClass();
John McCalla8ae2222010-04-06 21:38:20 +00001264 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
1265 NamedDecl *D = (Entity.isMemberAccess() ? Entity.getTargetDecl() : 0);
John McCalld79b4d82010-04-02 00:03:43 +00001266
1267 S.Diag(Loc, Entity.getDiag())
1268 << (Entity.getAccess() == AS_protected)
1269 << (D ? D->getDeclName() : DeclarationName())
1270 << S.Context.getTypeDeclType(NamingClass)
1271 << S.Context.getTypeDeclType(DeclaringClass);
1272 DiagnoseAccessPath(S, EC, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001273}
1274
Francois Pichetefb1af92011-05-23 03:43:44 +00001275/// MSVC has a bug where if during an using declaration name lookup,
1276/// the declaration found is unaccessible (private) and that declaration
1277/// was bring into scope via another using declaration whose target
1278/// declaration is accessible (public) then no error is generated.
1279/// Example:
1280/// class A {
1281/// public:
1282/// int f();
1283/// };
1284/// class B : public A {
1285/// private:
1286/// using A::f;
1287/// };
1288/// class C : public B {
1289/// private:
1290/// using B::f;
1291/// };
1292///
1293/// Here, B::f is private so this should fail in Standard C++, but
1294/// because B::f refers to A::f which is public MSVC accepts it.
1295static bool IsMicrosoftUsingDeclarationAccessBug(Sema& S,
1296 SourceLocation AccessLoc,
1297 AccessTarget &Entity) {
1298 if (UsingShadowDecl *Shadow =
1299 dyn_cast<UsingShadowDecl>(Entity.getTargetDecl())) {
1300 const NamedDecl *OrigDecl = Entity.getTargetDecl()->getUnderlyingDecl();
1301 if (Entity.getTargetDecl()->getAccess() == AS_private &&
1302 (OrigDecl->getAccess() == AS_public ||
1303 OrigDecl->getAccess() == AS_protected)) {
Richard Smithe4345902011-12-29 21:57:33 +00001304 S.Diag(AccessLoc, diag::ext_ms_using_declaration_inaccessible)
Francois Pichetefb1af92011-05-23 03:43:44 +00001305 << Shadow->getUsingDecl()->getQualifiedNameAsString()
1306 << OrigDecl->getQualifiedNameAsString();
1307 return true;
1308 }
1309 }
1310 return false;
1311}
1312
John McCalld79b4d82010-04-02 00:03:43 +00001313/// Determines whether the accessed entity is accessible. Public members
1314/// have been weeded out by this point.
John McCalla8ae2222010-04-06 21:38:20 +00001315static AccessResult IsAccessible(Sema &S,
1316 const EffectiveContext &EC,
1317 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001318 // Determine the actual naming class.
John McCalld010ac92013-02-27 00:08:19 +00001319 const CXXRecordDecl *NamingClass = Entity.getEffectiveNamingClass();
John McCall5b0829a2010-02-10 09:31:12 +00001320
John McCalld79b4d82010-04-02 00:03:43 +00001321 AccessSpecifier UnprivilegedAccess = Entity.getAccess();
1322 assert(UnprivilegedAccess != AS_public && "public access not weeded out");
1323
1324 // Before we try to recalculate access paths, try to white-list
1325 // accesses which just trade in on the final step, i.e. accesses
1326 // which don't require [M4] or [B4]. These are by far the most
John McCalla8ae2222010-04-06 21:38:20 +00001327 // common forms of privileged access.
John McCalld79b4d82010-04-02 00:03:43 +00001328 if (UnprivilegedAccess != AS_none) {
John McCalla8ae2222010-04-06 21:38:20 +00001329 switch (HasAccess(S, EC, NamingClass, UnprivilegedAccess, Entity)) {
1330 case AR_dependent:
John McCalld79b4d82010-04-02 00:03:43 +00001331 // This is actually an interesting policy decision. We don't
1332 // *have* to delay immediately here: we can do the full access
1333 // calculation in the hope that friendship on some intermediate
1334 // class will make the declaration accessible non-dependently.
1335 // But that's not cheap, and odds are very good (note: assertion
1336 // made without data) that the friend declaration will determine
1337 // access.
John McCalla8ae2222010-04-06 21:38:20 +00001338 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001339
John McCalla8ae2222010-04-06 21:38:20 +00001340 case AR_accessible: return AR_accessible;
1341 case AR_inaccessible: break;
John McCalld79b4d82010-04-02 00:03:43 +00001342 }
1343 }
1344
John McCalla8ae2222010-04-06 21:38:20 +00001345 AccessTarget::SavedInstanceContext _ = Entity.saveInstanceContext();
John McCall5b0829a2010-02-10 09:31:12 +00001346
John McCalld79b4d82010-04-02 00:03:43 +00001347 // We lower member accesses to base accesses by pretending that the
1348 // member is a base class of its declaring class.
1349 AccessSpecifier FinalAccess;
1350
John McCall5b0829a2010-02-10 09:31:12 +00001351 if (Entity.isMemberAccess()) {
John McCalld79b4d82010-04-02 00:03:43 +00001352 // Determine if the declaration is accessible from EC when named
1353 // in its declaring class.
John McCall5b0829a2010-02-10 09:31:12 +00001354 NamedDecl *Target = Entity.getTargetDecl();
John McCalla8ae2222010-04-06 21:38:20 +00001355 const CXXRecordDecl *DeclaringClass = Entity.getDeclaringClass();
John McCall5b0829a2010-02-10 09:31:12 +00001356
John McCalld79b4d82010-04-02 00:03:43 +00001357 FinalAccess = Target->getAccess();
John McCalla8ae2222010-04-06 21:38:20 +00001358 switch (HasAccess(S, EC, DeclaringClass, FinalAccess, Entity)) {
1359 case AR_accessible:
John McCall5149fbf2013-02-22 03:52:55 +00001360 // Target is accessible at EC when named in its declaring class.
1361 // We can now hill-climb and simply check whether the declaring
1362 // class is accessible as a base of the naming class. This is
1363 // equivalent to checking the access of a notional public
1364 // member with no instance context.
John McCalla8ae2222010-04-06 21:38:20 +00001365 FinalAccess = AS_public;
John McCall5149fbf2013-02-22 03:52:55 +00001366 Entity.suppressInstanceContext();
John McCalla8ae2222010-04-06 21:38:20 +00001367 break;
1368 case AR_inaccessible: break;
1369 case AR_dependent: return AR_dependent; // see above
John McCall5b0829a2010-02-10 09:31:12 +00001370 }
1371
John McCalld79b4d82010-04-02 00:03:43 +00001372 if (DeclaringClass == NamingClass)
John McCalla8ae2222010-04-06 21:38:20 +00001373 return (FinalAccess == AS_public ? AR_accessible : AR_inaccessible);
John McCalld79b4d82010-04-02 00:03:43 +00001374 } else {
1375 FinalAccess = AS_public;
John McCall5b0829a2010-02-10 09:31:12 +00001376 }
1377
John McCalla8ae2222010-04-06 21:38:20 +00001378 assert(Entity.getDeclaringClass() != NamingClass);
John McCall5b0829a2010-02-10 09:31:12 +00001379
1380 // Append the declaration's access if applicable.
1381 CXXBasePaths Paths;
John McCalla8ae2222010-04-06 21:38:20 +00001382 CXXBasePath *Path = FindBestPath(S, EC, Entity, FinalAccess, Paths);
John McCallc62bb642010-03-24 05:22:00 +00001383 if (!Path)
John McCalla8ae2222010-04-06 21:38:20 +00001384 return AR_dependent;
John McCall553c0792010-01-23 00:46:32 +00001385
John McCalld79b4d82010-04-02 00:03:43 +00001386 assert(Path->Access <= UnprivilegedAccess &&
1387 "access along best path worse than direct?");
1388 if (Path->Access == AS_public)
John McCalla8ae2222010-04-06 21:38:20 +00001389 return AR_accessible;
1390 return AR_inaccessible;
John McCallc62bb642010-03-24 05:22:00 +00001391}
1392
John McCalla8ae2222010-04-06 21:38:20 +00001393static void DelayDependentAccess(Sema &S,
1394 const EffectiveContext &EC,
1395 SourceLocation Loc,
1396 const AccessTarget &Entity) {
John McCallc62bb642010-03-24 05:22:00 +00001397 assert(EC.isDependent() && "delaying non-dependent access");
John McCall816d75b2010-03-24 07:46:06 +00001398 DeclContext *DC = EC.getInnerContext();
John McCallc62bb642010-03-24 05:22:00 +00001399 assert(DC->isDependentContext() && "delaying non-dependent access");
1400 DependentDiagnostic::Create(S.Context, DC, DependentDiagnostic::Access,
1401 Loc,
1402 Entity.isMemberAccess(),
1403 Entity.getAccess(),
1404 Entity.getTargetDecl(),
1405 Entity.getNamingClass(),
John McCalla8ae2222010-04-06 21:38:20 +00001406 Entity.getBaseObjectType(),
John McCallc62bb642010-03-24 05:22:00 +00001407 Entity.getDiag());
John McCall553c0792010-01-23 00:46:32 +00001408}
1409
John McCall5b0829a2010-02-10 09:31:12 +00001410/// Checks access to an entity from the given effective context.
John McCalla8ae2222010-04-06 21:38:20 +00001411static AccessResult CheckEffectiveAccess(Sema &S,
1412 const EffectiveContext &EC,
1413 SourceLocation Loc,
1414 AccessTarget &Entity) {
John McCalld79b4d82010-04-02 00:03:43 +00001415 assert(Entity.getAccess() != AS_public && "called for public access!");
John McCall553c0792010-01-23 00:46:32 +00001416
John McCalld79b4d82010-04-02 00:03:43 +00001417 switch (IsAccessible(S, EC, Entity)) {
John McCalla8ae2222010-04-06 21:38:20 +00001418 case AR_dependent:
1419 DelayDependentAccess(S, EC, Loc, Entity);
1420 return AR_dependent;
John McCalld79b4d82010-04-02 00:03:43 +00001421
John McCalla8ae2222010-04-06 21:38:20 +00001422 case AR_inaccessible:
Reid Kleckner42063b02014-02-08 02:40:20 +00001423 if (S.getLangOpts().MSVCCompat &&
1424 IsMicrosoftUsingDeclarationAccessBug(S, Loc, Entity))
1425 return AR_accessible;
John McCalld79b4d82010-04-02 00:03:43 +00001426 if (!Entity.isQuiet())
1427 DiagnoseBadAccess(S, Loc, EC, Entity);
John McCalla8ae2222010-04-06 21:38:20 +00001428 return AR_inaccessible;
John McCalld79b4d82010-04-02 00:03:43 +00001429
John McCalla8ae2222010-04-06 21:38:20 +00001430 case AR_accessible:
1431 return AR_accessible;
John McCallc62bb642010-03-24 05:22:00 +00001432 }
1433
John McCalla8ae2222010-04-06 21:38:20 +00001434 // silence unnecessary warning
1435 llvm_unreachable("invalid access result");
John McCall5b0829a2010-02-10 09:31:12 +00001436}
John McCall553c0792010-01-23 00:46:32 +00001437
John McCall5b0829a2010-02-10 09:31:12 +00001438static Sema::AccessResult CheckAccess(Sema &S, SourceLocation Loc,
John McCalla8ae2222010-04-06 21:38:20 +00001439 AccessTarget &Entity) {
John McCall5b0829a2010-02-10 09:31:12 +00001440 // If the access path is public, it's accessible everywhere.
1441 if (Entity.getAccess() == AS_public)
1442 return Sema::AR_accessible;
John McCall553c0792010-01-23 00:46:32 +00001443
John McCallc1465822011-02-14 07:13:47 +00001444 // If we're currently parsing a declaration, we may need to delay
1445 // access control checking, because our effective context might be
1446 // different based on what the declaration comes out as.
1447 //
1448 // For example, we might be parsing a declaration with a scope
1449 // specifier, like this:
1450 // A::private_type A::foo() { ... }
1451 //
1452 // Or we might be parsing something that will turn out to be a friend:
1453 // void foo(A::private_type);
1454 // void B::foo(A::private_type);
1455 if (S.DelayedDiagnostics.shouldDelayDiagnostics()) {
1456 S.DelayedDiagnostics.add(DelayedDiagnostic::makeAccess(Loc, Entity));
John McCall5b0829a2010-02-10 09:31:12 +00001457 return Sema::AR_delayed;
John McCall553c0792010-01-23 00:46:32 +00001458 }
1459
John McCalla8ae2222010-04-06 21:38:20 +00001460 EffectiveContext EC(S.CurContext);
1461 switch (CheckEffectiveAccess(S, EC, Loc, Entity)) {
1462 case AR_accessible: return Sema::AR_accessible;
1463 case AR_inaccessible: return Sema::AR_inaccessible;
1464 case AR_dependent: return Sema::AR_dependent;
1465 }
1466 llvm_unreachable("falling off end");
John McCall553c0792010-01-23 00:46:32 +00001467}
1468
Richard Smithad5c1ca2013-04-29 10:13:55 +00001469void Sema::HandleDelayedAccessCheck(DelayedDiagnostic &DD, Decl *D) {
John McCall9743e8d2011-02-15 22:51:53 +00001470 // Access control for names used in the declarations of functions
1471 // and function templates should normally be evaluated in the context
1472 // of the declaration, just in case it's a friend of something.
1473 // However, this does not apply to local extern declarations.
1474
Richard Smithad5c1ca2013-04-29 10:13:55 +00001475 DeclContext *DC = D->getDeclContext();
Richard Smith608da012013-12-11 03:35:27 +00001476 if (D->isLocalExternDecl()) {
1477 DC = D->getLexicalDeclContext();
1478 } else if (FunctionDecl *FN = dyn_cast<FunctionDecl>(D)) {
1479 DC = FN;
Richard Smithad5c1ca2013-04-29 10:13:55 +00001480 } else if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D)) {
1481 DC = cast<DeclContext>(TD->getTemplatedDecl());
John McCall9743e8d2011-02-15 22:51:53 +00001482 }
1483
Chandler Carruthaad30072010-04-18 08:23:21 +00001484 EffectiveContext EC(DC);
John McCall86121512010-01-27 03:50:35 +00001485
John McCalla8ae2222010-04-06 21:38:20 +00001486 AccessTarget Target(DD.getAccessData());
1487
1488 if (CheckEffectiveAccess(*this, EC, DD.Loc, Target) == ::AR_inaccessible)
John McCall86121512010-01-27 03:50:35 +00001489 DD.Triggered = true;
1490}
1491
John McCallc62bb642010-03-24 05:22:00 +00001492void Sema::HandleDependentAccessCheck(const DependentDiagnostic &DD,
1493 const MultiLevelTemplateArgumentList &TemplateArgs) {
1494 SourceLocation Loc = DD.getAccessLoc();
1495 AccessSpecifier Access = DD.getAccess();
1496
1497 Decl *NamingD = FindInstantiatedDecl(Loc, DD.getAccessNamingClass(),
1498 TemplateArgs);
1499 if (!NamingD) return;
1500 Decl *TargetD = FindInstantiatedDecl(Loc, DD.getAccessTarget(),
1501 TemplateArgs);
1502 if (!TargetD) return;
1503
1504 if (DD.isAccessToMember()) {
John McCalla8ae2222010-04-06 21:38:20 +00001505 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(NamingD);
1506 NamedDecl *TargetDecl = cast<NamedDecl>(TargetD);
1507 QualType BaseObjectType = DD.getAccessBaseObjectType();
1508 if (!BaseObjectType.isNull()) {
1509 BaseObjectType = SubstType(BaseObjectType, TemplateArgs, Loc,
1510 DeclarationName());
1511 if (BaseObjectType.isNull()) return;
1512 }
1513
1514 AccessTarget Entity(Context,
1515 AccessTarget::Member,
1516 NamingClass,
1517 DeclAccessPair::make(TargetDecl, Access),
1518 BaseObjectType);
John McCallc62bb642010-03-24 05:22:00 +00001519 Entity.setDiag(DD.getDiagnostic());
1520 CheckAccess(*this, Loc, Entity);
1521 } else {
John McCalla8ae2222010-04-06 21:38:20 +00001522 AccessTarget Entity(Context,
1523 AccessTarget::Base,
1524 cast<CXXRecordDecl>(TargetD),
1525 cast<CXXRecordDecl>(NamingD),
1526 Access);
John McCallc62bb642010-03-24 05:22:00 +00001527 Entity.setDiag(DD.getDiagnostic());
1528 CheckAccess(*this, Loc, Entity);
1529 }
1530}
1531
John McCall5b0829a2010-02-10 09:31:12 +00001532Sema::AccessResult Sema::CheckUnresolvedLookupAccess(UnresolvedLookupExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001533 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001534 if (!getLangOpts().AccessControl ||
John McCall1064d7e2010-03-16 05:22:47 +00001535 !E->getNamingClass() ||
John McCalla0296f72010-03-19 07:35:19 +00001536 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001537 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001538
John McCalla8ae2222010-04-06 21:38:20 +00001539 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1540 Found, QualType());
John McCall1064d7e2010-03-16 05:22:47 +00001541 Entity.setDiag(diag::err_access) << E->getSourceRange();
1542
1543 return CheckAccess(*this, E->getNameLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001544}
1545
1546/// Perform access-control checking on a previously-unresolved member
1547/// access which has now been resolved to a member.
John McCall5b0829a2010-02-10 09:31:12 +00001548Sema::AccessResult Sema::CheckUnresolvedMemberAccess(UnresolvedMemberExpr *E,
John McCalla0296f72010-03-19 07:35:19 +00001549 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001550 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001551 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001552 return AR_accessible;
John McCall58cc69d2010-01-27 01:50:18 +00001553
John McCalla8ae2222010-04-06 21:38:20 +00001554 QualType BaseType = E->getBaseType();
1555 if (E->isArrow())
1556 BaseType = BaseType->getAs<PointerType>()->getPointeeType();
1557
1558 AccessTarget Entity(Context, AccessTarget::Member, E->getNamingClass(),
1559 Found, BaseType);
John McCall1064d7e2010-03-16 05:22:47 +00001560 Entity.setDiag(diag::err_access) << E->getSourceRange();
1561
1562 return CheckAccess(*this, E->getMemberLoc(), Entity);
John McCall58cc69d2010-01-27 01:50:18 +00001563}
1564
John McCalld4274212012-04-09 20:53:23 +00001565/// Is the given special member function accessible for the purposes of
1566/// deciding whether to define a special member function as deleted?
1567bool Sema::isSpecialMemberAccessibleForDeletion(CXXMethodDecl *decl,
1568 AccessSpecifier access,
1569 QualType objectType) {
1570 // Fast path.
1571 if (access == AS_public || !getLangOpts().AccessControl) return true;
1572
1573 AccessTarget entity(Context, AccessTarget::Member, decl->getParent(),
1574 DeclAccessPair::make(decl, access), objectType);
1575
1576 // Suppress diagnostics.
1577 entity.setDiag(PDiag());
1578
1579 switch (CheckAccess(*this, SourceLocation(), entity)) {
1580 case AR_accessible: return true;
1581 case AR_inaccessible: return false;
1582 case AR_dependent: llvm_unreachable("dependent for =delete computation");
1583 case AR_delayed: llvm_unreachable("cannot delay =delete computation");
1584 }
1585 llvm_unreachable("bad access result");
1586}
1587
John McCall5b0829a2010-02-10 09:31:12 +00001588Sema::AccessResult Sema::CheckDestructorAccess(SourceLocation Loc,
John McCall1064d7e2010-03-16 05:22:47 +00001589 CXXDestructorDecl *Dtor,
John McCall5dadb652012-04-07 03:04:20 +00001590 const PartialDiagnostic &PDiag,
1591 QualType ObjectTy) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001592 if (!getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001593 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001594
John McCall1064d7e2010-03-16 05:22:47 +00001595 // There's never a path involved when checking implicit destructor access.
John McCall6781b052010-02-02 08:45:54 +00001596 AccessSpecifier Access = Dtor->getAccess();
1597 if (Access == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001598 return AR_accessible;
John McCall6781b052010-02-02 08:45:54 +00001599
John McCall1064d7e2010-03-16 05:22:47 +00001600 CXXRecordDecl *NamingClass = Dtor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001601 if (ObjectTy.isNull()) ObjectTy = Context.getTypeDeclType(NamingClass);
1602
John McCalla8ae2222010-04-06 21:38:20 +00001603 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
1604 DeclAccessPair::make(Dtor, Access),
John McCall5dadb652012-04-07 03:04:20 +00001605 ObjectTy);
John McCall1064d7e2010-03-16 05:22:47 +00001606 Entity.setDiag(PDiag); // TODO: avoid copy
1607
1608 return CheckAccess(*this, Loc, Entity);
John McCall6781b052010-02-02 08:45:54 +00001609}
1610
John McCall760af172010-02-01 03:16:54 +00001611/// Checks access to a constructor.
John McCall5b0829a2010-02-10 09:31:12 +00001612Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
Jeffrey Yasskincaa710d2010-06-07 15:58:05 +00001613 CXXConstructorDecl *Constructor,
1614 const InitializedEntity &Entity,
1615 AccessSpecifier Access,
1616 bool IsCopyBindingRefToTemp) {
John McCall5dadb652012-04-07 03:04:20 +00001617 if (!getLangOpts().AccessControl || Access == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001618 return AR_accessible;
John McCall760af172010-02-01 03:16:54 +00001619
Alexis Hunteef8ee02011-06-10 03:50:41 +00001620 PartialDiagnostic PD(PDiag());
Anders Carlssona01874b2010-04-21 18:47:17 +00001621 switch (Entity.getKind()) {
1622 default:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001623 PD = PDiag(IsCopyBindingRefToTemp
1624 ? diag::ext_rvalue_to_reference_access_ctor
1625 : diag::err_access_ctor);
1626
Anders Carlssona01874b2010-04-21 18:47:17 +00001627 break;
John McCall1064d7e2010-03-16 05:22:47 +00001628
Anders Carlsson05bf0092010-04-22 05:40:53 +00001629 case InitializedEntity::EK_Base:
Alexis Hunteef8ee02011-06-10 03:50:41 +00001630 PD = PDiag(diag::err_access_base_ctor);
1631 PD << Entity.isInheritedVirtualBase()
1632 << Entity.getBaseSpecifier()->getType() << getSpecialMember(Constructor);
Anders Carlssona01874b2010-04-21 18:47:17 +00001633 break;
Anders Carlsson05bf0092010-04-22 05:40:53 +00001634
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001635 case InitializedEntity::EK_Member: {
1636 const FieldDecl *Field = cast<FieldDecl>(Entity.getDecl());
Alexis Hunteef8ee02011-06-10 03:50:41 +00001637 PD = PDiag(diag::err_access_field_ctor);
1638 PD << Field->getType() << getSpecialMember(Constructor);
Anders Carlsson4bb6e922010-04-21 20:28:29 +00001639 break;
1640 }
Anders Carlssona01874b2010-04-21 18:47:17 +00001641
Douglas Gregor19666fb2012-02-15 16:57:26 +00001642 case InitializedEntity::EK_LambdaCapture: {
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001643 StringRef VarName = Entity.getCapturedVarName();
Douglas Gregor19666fb2012-02-15 16:57:26 +00001644 PD = PDiag(diag::err_access_lambda_capture);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001645 PD << VarName << Entity.getType() << getSpecialMember(Constructor);
Douglas Gregor19666fb2012-02-15 16:57:26 +00001646 break;
1647 }
1648
Anders Carlsson43c64af2010-04-21 19:52:01 +00001649 }
1650
John McCall5dadb652012-04-07 03:04:20 +00001651 return CheckConstructorAccess(UseLoc, Constructor, Entity, Access, PD);
Alexis Hunteef8ee02011-06-10 03:50:41 +00001652}
1653
1654/// Checks access to a constructor.
1655Sema::AccessResult Sema::CheckConstructorAccess(SourceLocation UseLoc,
1656 CXXConstructorDecl *Constructor,
John McCall5dadb652012-04-07 03:04:20 +00001657 const InitializedEntity &Entity,
Alexis Hunteef8ee02011-06-10 03:50:41 +00001658 AccessSpecifier Access,
John McCall5dadb652012-04-07 03:04:20 +00001659 const PartialDiagnostic &PD) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001660 if (!getLangOpts().AccessControl ||
Alexis Hunteef8ee02011-06-10 03:50:41 +00001661 Access == AS_public)
1662 return AR_accessible;
1663
1664 CXXRecordDecl *NamingClass = Constructor->getParent();
John McCall5dadb652012-04-07 03:04:20 +00001665
1666 // Initializing a base sub-object is an instance method call on an
1667 // object of the derived class. Otherwise, we have an instance method
1668 // call on an object of the constructed type.
1669 CXXRecordDecl *ObjectClass;
1670 if (Entity.getKind() == InitializedEntity::EK_Base) {
1671 ObjectClass = cast<CXXConstructorDecl>(CurContext)->getParent();
1672 } else {
1673 ObjectClass = NamingClass;
1674 }
1675
Alexis Hunteef8ee02011-06-10 03:50:41 +00001676 AccessTarget AccessEntity(Context, AccessTarget::Member, NamingClass,
1677 DeclAccessPair::make(Constructor, Access),
John McCall5dadb652012-04-07 03:04:20 +00001678 Context.getTypeDeclType(ObjectClass));
Alexis Hunteef8ee02011-06-10 03:50:41 +00001679 AccessEntity.setDiag(PD);
1680
Anders Carlssona01874b2010-04-21 18:47:17 +00001681 return CheckAccess(*this, UseLoc, AccessEntity);
John McCall5dadb652012-04-07 03:04:20 +00001682}
John McCall760af172010-02-01 03:16:54 +00001683
John McCallfb6f5262010-03-18 08:19:33 +00001684/// Checks access to an overloaded operator new or delete.
1685Sema::AccessResult Sema::CheckAllocationAccess(SourceLocation OpLoc,
1686 SourceRange PlacementRange,
1687 CXXRecordDecl *NamingClass,
Alexis Huntf91729462011-05-12 22:46:25 +00001688 DeclAccessPair Found,
1689 bool Diagnose) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001690 if (!getLangOpts().AccessControl ||
John McCallfb6f5262010-03-18 08:19:33 +00001691 !NamingClass ||
John McCalla0296f72010-03-19 07:35:19 +00001692 Found.getAccess() == AS_public)
John McCallfb6f5262010-03-18 08:19:33 +00001693 return AR_accessible;
1694
John McCalla8ae2222010-04-06 21:38:20 +00001695 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1696 QualType());
Alexis Huntf91729462011-05-12 22:46:25 +00001697 if (Diagnose)
1698 Entity.setDiag(diag::err_access)
1699 << PlacementRange;
John McCallfb6f5262010-03-18 08:19:33 +00001700
1701 return CheckAccess(*this, OpLoc, Entity);
1702}
1703
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001704/// \brief Checks access to a member.
1705Sema::AccessResult Sema::CheckMemberAccess(SourceLocation UseLoc,
1706 CXXRecordDecl *NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001707 DeclAccessPair Found) {
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001708 if (!getLangOpts().AccessControl ||
1709 !NamingClass ||
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001710 Found.getAccess() == AS_public)
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001711 return AR_accessible;
1712
1713 AccessTarget Entity(Context, AccessTarget::Member, NamingClass,
Eli Friedman3be1a1c2013-10-01 02:44:48 +00001714 Found, QualType());
Alexey Bataev5ec3eb12013-07-19 03:13:43 +00001715
1716 return CheckAccess(*this, UseLoc, Entity);
1717}
1718
John McCall760af172010-02-01 03:16:54 +00001719/// Checks access to an overloaded member operator, including
1720/// conversion operators.
John McCall5b0829a2010-02-10 09:31:12 +00001721Sema::AccessResult Sema::CheckMemberOperatorAccess(SourceLocation OpLoc,
1722 Expr *ObjectExpr,
John McCall1064d7e2010-03-16 05:22:47 +00001723 Expr *ArgExpr,
John McCalla0296f72010-03-19 07:35:19 +00001724 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001725 if (!getLangOpts().AccessControl ||
John McCalla0296f72010-03-19 07:35:19 +00001726 Found.getAccess() == AS_public)
John McCall5b0829a2010-02-10 09:31:12 +00001727 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001728
John McCall30909032011-09-21 08:36:56 +00001729 const RecordType *RT = ObjectExpr->getType()->castAs<RecordType>();
John McCallb3a44002010-01-28 01:42:12 +00001730 CXXRecordDecl *NamingClass = cast<CXXRecordDecl>(RT->getDecl());
1731
John McCalla8ae2222010-04-06 21:38:20 +00001732 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
1733 ObjectExpr->getType());
John McCall1064d7e2010-03-16 05:22:47 +00001734 Entity.setDiag(diag::err_access)
1735 << ObjectExpr->getSourceRange()
1736 << (ArgExpr ? ArgExpr->getSourceRange() : SourceRange());
1737
1738 return CheckAccess(*this, OpLoc, Entity);
John McCall5b0829a2010-02-10 09:31:12 +00001739}
John McCallb3a44002010-01-28 01:42:12 +00001740
John McCalla0a96892012-08-10 03:15:35 +00001741/// Checks access to the target of a friend declaration.
1742Sema::AccessResult Sema::CheckFriendAccess(NamedDecl *target) {
Alp Tokera2794f92014-01-22 07:29:52 +00001743 assert(isa<CXXMethodDecl>(target->getAsFunction()));
John McCalla0a96892012-08-10 03:15:35 +00001744
1745 // Friendship lookup is a redeclaration lookup, so there's never an
1746 // inheritance path modifying access.
1747 AccessSpecifier access = target->getAccess();
1748
1749 if (!getLangOpts().AccessControl || access == AS_public)
1750 return AR_accessible;
1751
Alp Toker2bd4a282014-01-22 07:53:08 +00001752 CXXMethodDecl *method = cast<CXXMethodDecl>(target->getAsFunction());
John McCalla0a96892012-08-10 03:15:35 +00001753 assert(method->getQualifier());
1754
1755 AccessTarget entity(Context, AccessTarget::Member,
1756 cast<CXXRecordDecl>(target->getDeclContext()),
1757 DeclAccessPair::make(target, access),
1758 /*no instance context*/ QualType());
1759 entity.setDiag(diag::err_access_friend_function)
1760 << method->getQualifierLoc().getSourceRange();
1761
1762 // We need to bypass delayed-diagnostics because we might be called
1763 // while the ParsingDeclarator is active.
1764 EffectiveContext EC(CurContext);
1765 switch (CheckEffectiveAccess(*this, EC, target->getLocation(), entity)) {
1766 case AR_accessible: return Sema::AR_accessible;
1767 case AR_inaccessible: return Sema::AR_inaccessible;
1768 case AR_dependent: return Sema::AR_dependent;
1769 }
1770 llvm_unreachable("falling off end");
1771}
1772
John McCall16df1e52010-03-30 21:47:33 +00001773Sema::AccessResult Sema::CheckAddressOfMemberAccess(Expr *OvlExpr,
1774 DeclAccessPair Found) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001775 if (!getLangOpts().AccessControl ||
John McCallb493d532010-03-30 22:20:00 +00001776 Found.getAccess() == AS_none ||
John McCall16df1e52010-03-30 21:47:33 +00001777 Found.getAccess() == AS_public)
1778 return AR_accessible;
1779
John McCall8d08b9b2010-08-27 09:08:28 +00001780 OverloadExpr *Ovl = OverloadExpr::find(OvlExpr).Expression;
John McCall8c12dc42010-04-22 18:44:12 +00001781 CXXRecordDecl *NamingClass = Ovl->getNamingClass();
John McCall16df1e52010-03-30 21:47:33 +00001782
John McCalla8ae2222010-04-06 21:38:20 +00001783 AccessTarget Entity(Context, AccessTarget::Member, NamingClass, Found,
John McCall5dadb652012-04-07 03:04:20 +00001784 /*no instance context*/ QualType());
John McCall16df1e52010-03-30 21:47:33 +00001785 Entity.setDiag(diag::err_access)
1786 << Ovl->getSourceRange();
1787
1788 return CheckAccess(*this, Ovl->getNameLoc(), Entity);
1789}
1790
John McCall5b0829a2010-02-10 09:31:12 +00001791/// Checks access for a hierarchy conversion.
1792///
John McCall5b0829a2010-02-10 09:31:12 +00001793/// \param ForceCheck true if this check should be performed even if access
1794/// control is disabled; some things rely on this for semantics
1795/// \param ForceUnprivileged true if this check should proceed as if the
1796/// context had no special privileges
John McCall5b0829a2010-02-10 09:31:12 +00001797Sema::AccessResult Sema::CheckBaseClassAccess(SourceLocation AccessLoc,
John McCall5b0829a2010-02-10 09:31:12 +00001798 QualType Base,
1799 QualType Derived,
1800 const CXXBasePath &Path,
John McCall1064d7e2010-03-16 05:22:47 +00001801 unsigned DiagID,
John McCall5b0829a2010-02-10 09:31:12 +00001802 bool ForceCheck,
John McCall1064d7e2010-03-16 05:22:47 +00001803 bool ForceUnprivileged) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001804 if (!ForceCheck && !getLangOpts().AccessControl)
John McCall5b0829a2010-02-10 09:31:12 +00001805 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001806
John McCall5b0829a2010-02-10 09:31:12 +00001807 if (Path.Access == AS_public)
1808 return AR_accessible;
John McCallb3a44002010-01-28 01:42:12 +00001809
John McCall5b0829a2010-02-10 09:31:12 +00001810 CXXRecordDecl *BaseD, *DerivedD;
1811 BaseD = cast<CXXRecordDecl>(Base->getAs<RecordType>()->getDecl());
1812 DerivedD = cast<CXXRecordDecl>(Derived->getAs<RecordType>()->getDecl());
John McCall1064d7e2010-03-16 05:22:47 +00001813
John McCalla8ae2222010-04-06 21:38:20 +00001814 AccessTarget Entity(Context, AccessTarget::Base, BaseD, DerivedD,
1815 Path.Access);
John McCall1064d7e2010-03-16 05:22:47 +00001816 if (DiagID)
1817 Entity.setDiag(DiagID) << Derived << Base;
John McCall5b0829a2010-02-10 09:31:12 +00001818
John McCalla8ae2222010-04-06 21:38:20 +00001819 if (ForceUnprivileged) {
1820 switch (CheckEffectiveAccess(*this, EffectiveContext(),
1821 AccessLoc, Entity)) {
1822 case ::AR_accessible: return Sema::AR_accessible;
1823 case ::AR_inaccessible: return Sema::AR_inaccessible;
1824 case ::AR_dependent: return Sema::AR_dependent;
1825 }
1826 llvm_unreachable("unexpected result from CheckEffectiveAccess");
1827 }
John McCall1064d7e2010-03-16 05:22:47 +00001828 return CheckAccess(*this, AccessLoc, Entity);
John McCallb3a44002010-01-28 01:42:12 +00001829}
1830
John McCall553c0792010-01-23 00:46:32 +00001831/// Checks access to all the declarations in the given result set.
John McCall5b0829a2010-02-10 09:31:12 +00001832void Sema::CheckLookupAccess(const LookupResult &R) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001833 assert(getLangOpts().AccessControl
John McCall5b0829a2010-02-10 09:31:12 +00001834 && "performing access check without access control");
1835 assert(R.getNamingClass() && "performing access check without naming class");
1836
John McCall1064d7e2010-03-16 05:22:47 +00001837 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
1838 if (I.getAccess() != AS_public) {
John McCalla8ae2222010-04-06 21:38:20 +00001839 AccessTarget Entity(Context, AccessedEntity::Member,
1840 R.getNamingClass(), I.getPair(),
Erik Verbruggen631dfc62011-09-19 15:10:40 +00001841 R.getBaseObjectType());
John McCall1064d7e2010-03-16 05:22:47 +00001842 Entity.setDiag(diag::err_access);
John McCall1064d7e2010-03-16 05:22:47 +00001843 CheckAccess(*this, R.getNameLoc(), Entity);
1844 }
1845 }
John McCall553c0792010-01-23 00:46:32 +00001846}
Chandler Carruth2d69ec72010-06-28 08:39:25 +00001847
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001848/// Checks access to Decl from the given class. The check will take access
1849/// specifiers into account, but no member access expressions and such.
1850///
1851/// \param Decl the declaration to check if it can be accessed
Dmitri Gribenkodd28e792012-08-24 00:01:24 +00001852/// \param Ctx the class/context from which to start the search
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001853/// \return true if the Decl is accessible from the Class, false otherwise.
Douglas Gregor03ba1882011-11-03 16:51:37 +00001854bool Sema::IsSimplyAccessible(NamedDecl *Decl, DeclContext *Ctx) {
1855 if (CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Ctx)) {
Douglas Gregor3b52b692011-11-03 17:41:55 +00001856 if (!Decl->isCXXClassMember())
Douglas Gregor03ba1882011-11-03 16:51:37 +00001857 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001858
Douglas Gregor03ba1882011-11-03 16:51:37 +00001859 QualType qType = Class->getTypeForDecl()->getCanonicalTypeInternal();
1860 AccessTarget Entity(Context, AccessedEntity::Member, Class,
1861 DeclAccessPair::make(Decl, Decl->getAccess()),
1862 qType);
1863 if (Entity.getAccess() == AS_public)
1864 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001865
Douglas Gregor03ba1882011-11-03 16:51:37 +00001866 EffectiveContext EC(CurContext);
1867 return ::IsAccessible(*this, EC, Entity) != ::AR_inaccessible;
1868 }
1869
Douglas Gregor21ceb182011-11-03 19:00:24 +00001870 if (ObjCIvarDecl *Ivar = dyn_cast<ObjCIvarDecl>(Decl)) {
1871 // @public and @package ivars are always accessible.
1872 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Public ||
1873 Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Package)
1874 return true;
Serge Pavlov64bc7032013-05-07 16:56:03 +00001875
Douglas Gregor21ceb182011-11-03 19:00:24 +00001876 // If we are inside a class or category implementation, determine the
1877 // interface we're in.
1878 ObjCInterfaceDecl *ClassOfMethodDecl = 0;
1879 if (ObjCMethodDecl *MD = getCurMethodDecl())
1880 ClassOfMethodDecl = MD->getClassInterface();
1881 else if (FunctionDecl *FD = getCurFunctionDecl()) {
1882 if (ObjCImplDecl *Impl
1883 = dyn_cast<ObjCImplDecl>(FD->getLexicalDeclContext())) {
1884 if (ObjCImplementationDecl *IMPD
1885 = dyn_cast<ObjCImplementationDecl>(Impl))
1886 ClassOfMethodDecl = IMPD->getClassInterface();
1887 else if (ObjCCategoryImplDecl* CatImplClass
1888 = dyn_cast<ObjCCategoryImplDecl>(Impl))
1889 ClassOfMethodDecl = CatImplClass->getClassInterface();
1890 }
1891 }
1892
1893 // If we're not in an interface, this ivar is inaccessible.
1894 if (!ClassOfMethodDecl)
1895 return false;
1896
1897 // If we're inside the same interface that owns the ivar, we're fine.
Douglas Gregor0b144e12011-12-15 00:29:59 +00001898 if (declaresSameEntity(ClassOfMethodDecl, Ivar->getContainingInterface()))
Douglas Gregor21ceb182011-11-03 19:00:24 +00001899 return true;
1900
1901 // If the ivar is private, it's inaccessible.
1902 if (Ivar->getCanonicalAccessControl() == ObjCIvarDecl::Private)
1903 return false;
1904
1905 return Ivar->getContainingInterface()->isSuperClassOf(ClassOfMethodDecl);
1906 }
1907
Douglas Gregor03ba1882011-11-03 16:51:37 +00001908 return true;
Erik Verbruggen2e657ff2011-10-06 07:27:49 +00001909}