This repository was archived by the owner on Nov 1, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathSemaAccess.cpp
1920 lines (1613 loc) · 68.4 KB
/
SemaAccess.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===---- SemaAccess.cpp - C++ Access Control -------------------*- C++ -*-===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file provides Sema routines for C++ access control semantics.
//
//===----------------------------------------------------------------------===//
#include "clang/Sema/SemaInternal.h"
#include "clang/AST/ASTContext.h"
#include "clang/AST/CXXInheritance.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclFriend.h"
#include "clang/AST/DeclObjC.h"
#include "clang/AST/DependentDiagnostic.h"
#include "clang/AST/ExprCXX.h"
#include "clang/Sema/DelayedDiagnostic.h"
#include "clang/Sema/Initialization.h"
#include "clang/Sema/Lookup.h"
using namespace clang;
using namespace sema;
/// A copy of Sema's enum without AR_delayed.
enum AccessResult {
AR_accessible,
AR_inaccessible,
AR_dependent
};
/// SetMemberAccessSpecifier - Set the access specifier of a member.
/// Returns true on error (when the previous member decl access specifier
/// is different from the new member decl access specifier).
bool Sema::SetMemberAccessSpecifier(NamedDecl *MemberDecl,
NamedDecl *PrevMemberDecl,
AccessSpecifier LexicalAS) {
if (!PrevMemberDecl) {
// Use the lexical access specifier.
MemberDecl->setAccess(LexicalAS);
return false;
}
// C++ [class.access.spec]p3: When a member is redeclared its access
// specifier must be same as its initial declaration.
if (LexicalAS != AS_none && LexicalAS != PrevMemberDecl->getAccess()) {
Diag(MemberDecl->getLocation(),
diag::err_class_redeclared_with_different_access)
<< MemberDecl << LexicalAS;
Diag(PrevMemberDecl->getLocation(), diag::note_previous_access_declaration)
<< PrevMemberDecl << PrevMemberDecl->getAccess();
MemberDecl->setAccess(LexicalAS);
return true;
}
MemberDecl->setAccess(PrevMemberDecl->getAccess());
return false;
}
static CXXRecordDecl *FindDeclaringClass(NamedDecl *D) {
DeclContext *DC = D->getDeclContext();
// This can only happen at top: enum decls only "publish" their
// immediate members.
if (isa<EnumDecl>(DC))
DC = cast<EnumDecl>(DC)->getDeclContext();
CXXRecordDecl *DeclaringClass = cast<CXXRecordDecl>(DC);
while (DeclaringClass->isAnonymousStructOrUnion())
DeclaringClass = cast<CXXRecordDecl>(DeclaringClass->getDeclContext());
return DeclaringClass;
}
namespace {
struct EffectiveContext {
EffectiveContext() : Inner(nullptr), Dependent(false) {}
explicit EffectiveContext(DeclContext *DC)
: Inner(DC),
Dependent(DC->isDependentContext()) {
// C++11 [class.access.nest]p1:
// A nested class is a member and as such has the same access
// rights as any other member.
// C++11 [class.access]p2:
// A member of a class can also access all the names to which
// the class has access. A local class of a member function
// may access the same names that the member function itself
// may access.
// This almost implies that the privileges of nesting are transitive.
// Technically it says nothing about the local classes of non-member
// functions (which can gain privileges through friendship), but we
// take that as an oversight.
while (true) {
// We want to add canonical declarations to the EC lists for
// simplicity of checking, but we need to walk up through the
// actual current DC chain. Otherwise, something like a local
// extern or friend which happens to be the canonical
// declaration will really mess us up.
if (isa<CXXRecordDecl>(DC)) {
CXXRecordDecl *Record = cast<CXXRecordDecl>(DC);
Records.push_back(Record->getCanonicalDecl());
DC = Record->getDeclContext();
} else if (isa<FunctionDecl>(DC)) {
FunctionDecl *Function = cast<FunctionDecl>(DC);
Functions.push_back(Function->getCanonicalDecl());
if (Function->getFriendObjectKind())
DC = Function->getLexicalDeclContext();
else
DC = Function->getDeclContext();
} else if (DC->isFileContext()) {
break;
} else {
DC = DC->getParent();
}
}
}
bool isDependent() const { return Dependent; }
bool includesClass(const CXXRecordDecl *R) const {
R = R->getCanonicalDecl();
return std::find(Records.begin(), Records.end(), R)
!= Records.end();
}
/// Retrieves the innermost "useful" context. Can be null if we're
/// doing access-control without privileges.
DeclContext *getInnerContext() const {
return Inner;
}
typedef SmallVectorImpl<CXXRecordDecl*>::const_iterator record_iterator;
DeclContext *Inner;
SmallVector<FunctionDecl*, 4> Functions;
SmallVector<CXXRecordDecl*, 4> Records;
bool Dependent;
};
/// Like sema::AccessedEntity, but kindly lets us scribble all over
/// it.
struct AccessTarget : public AccessedEntity {
AccessTarget(const AccessedEntity &Entity)
: AccessedEntity(Entity) {
initialize();
}
AccessTarget(ASTContext &Context,
MemberNonce _,
CXXRecordDecl *NamingClass,
DeclAccessPair FoundDecl,
QualType BaseObjectType)
: AccessedEntity(Context.getDiagAllocator(), Member, NamingClass,
FoundDecl, BaseObjectType) {
initialize();
}
AccessTarget(ASTContext &Context,
BaseNonce _,
CXXRecordDecl *BaseClass,
CXXRecordDecl *DerivedClass,
AccessSpecifier Access)
: AccessedEntity(Context.getDiagAllocator(), Base, BaseClass, DerivedClass,
Access) {
initialize();
}
bool isInstanceMember() const {
return (isMemberAccess() && getTargetDecl()->isCXXInstanceMember());
}
bool hasInstanceContext() const {
return HasInstanceContext;
}
class SavedInstanceContext {
public:
SavedInstanceContext(SavedInstanceContext &&S)
: Target(S.Target), Has(S.Has) {
S.Target = nullptr;
}
~SavedInstanceContext() {
if (Target)
Target->HasInstanceContext = Has;
}
private:
friend struct AccessTarget;
explicit SavedInstanceContext(AccessTarget &Target)
: Target(&Target), Has(Target.HasInstanceContext) {}
AccessTarget *Target;
bool Has;
};
SavedInstanceContext saveInstanceContext() {
return SavedInstanceContext(*this);
}
void suppressInstanceContext() {
HasInstanceContext = false;
}
const CXXRecordDecl *resolveInstanceContext(Sema &S) const {
assert(HasInstanceContext);
if (CalculatedInstanceContext)
return InstanceContext;
CalculatedInstanceContext = true;
DeclContext *IC = S.computeDeclContext(getBaseObjectType());
InstanceContext = (IC ? cast<CXXRecordDecl>(IC)->getCanonicalDecl()
: nullptr);
return InstanceContext;
}
const CXXRecordDecl *getDeclaringClass() const {
return DeclaringClass;
}
/// The "effective" naming class is the canonical non-anonymous
/// class containing the actual naming class.
const CXXRecordDecl *getEffectiveNamingClass() const {
const CXXRecordDecl *namingClass = getNamingClass();
while (namingClass->isAnonymousStructOrUnion())
namingClass = cast<CXXRecordDecl>(namingClass->getParent());
return namingClass->getCanonicalDecl();
}
private:
void initialize() {
HasInstanceContext = (isMemberAccess() &&
!getBaseObjectType().isNull() &&
getTargetDecl()->isCXXInstanceMember());
CalculatedInstanceContext = false;
InstanceContext = nullptr;
if (isMemberAccess())
DeclaringClass = FindDeclaringClass(getTargetDecl());
else
DeclaringClass = getBaseClass();
DeclaringClass = DeclaringClass->getCanonicalDecl();
}
bool HasInstanceContext : 1;
mutable bool CalculatedInstanceContext : 1;
mutable const CXXRecordDecl *InstanceContext;
const CXXRecordDecl *DeclaringClass;
};
}
/// Checks whether one class might instantiate to the other.
static bool MightInstantiateTo(const CXXRecordDecl *From,
const CXXRecordDecl *To) {
// Declaration names are always preserved by instantiation.
if (From->getDeclName() != To->getDeclName())
return false;
const DeclContext *FromDC = From->getDeclContext()->getPrimaryContext();
const DeclContext *ToDC = To->getDeclContext()->getPrimaryContext();
if (FromDC == ToDC) return true;
if (FromDC->isFileContext() || ToDC->isFileContext()) return false;
// Be conservative.
return true;
}
/// Checks whether one class is derived from another, inclusively.
/// Properly indicates when it couldn't be determined due to
/// dependence.
///
/// This should probably be donated to AST or at least Sema.
static AccessResult IsDerivedFromInclusive(const CXXRecordDecl *Derived,
const CXXRecordDecl *Target) {
assert(Derived->getCanonicalDecl() == Derived);
assert(Target->getCanonicalDecl() == Target);
if (Derived == Target) return AR_accessible;
bool CheckDependent = Derived->isDependentContext();
if (CheckDependent && MightInstantiateTo(Derived, Target))
return AR_dependent;
AccessResult OnFailure = AR_inaccessible;
SmallVector<const CXXRecordDecl*, 8> Queue; // actually a stack
while (true) {
if (Derived->isDependentContext() && !Derived->hasDefinition() &&
!Derived->isLambda())
return AR_dependent;
for (const auto &I : Derived->bases()) {
const CXXRecordDecl *RD;
QualType T = I.getType();
if (const RecordType *RT = T->getAs<RecordType>()) {
RD = cast<CXXRecordDecl>(RT->getDecl());
} else if (const InjectedClassNameType *IT
= T->getAs<InjectedClassNameType>()) {
RD = IT->getDecl();
} else {
assert(T->isDependentType() && "non-dependent base wasn't a record?");
OnFailure = AR_dependent;
continue;
}
RD = RD->getCanonicalDecl();
if (RD == Target) return AR_accessible;
if (CheckDependent && MightInstantiateTo(RD, Target))
OnFailure = AR_dependent;
Queue.push_back(RD);
}
if (Queue.empty()) break;
Derived = Queue.pop_back_val();
}
return OnFailure;
}
static bool MightInstantiateTo(Sema &S, DeclContext *Context,
DeclContext *Friend) {
if (Friend == Context)
return true;
assert(!Friend->isDependentContext() &&
"can't handle friends with dependent contexts here");
if (!Context->isDependentContext())
return false;
if (Friend->isFileContext())
return false;
// TODO: this is very conservative
return true;
}
// Asks whether the type in 'context' can ever instantiate to the type
// in 'friend'.
static bool MightInstantiateTo(Sema &S, CanQualType Context, CanQualType Friend) {
if (Friend == Context)
return true;
if (!Friend->isDependentType() && !Context->isDependentType())
return false;
// TODO: this is very conservative.
return true;
}
static bool MightInstantiateTo(Sema &S,
FunctionDecl *Context,
FunctionDecl *Friend) {
if (Context->getDeclName() != Friend->getDeclName())
return false;
if (!MightInstantiateTo(S,
Context->getDeclContext(),
Friend->getDeclContext()))
return false;
CanQual<FunctionProtoType> FriendTy
= S.Context.getCanonicalType(Friend->getType())
->getAs<FunctionProtoType>();
CanQual<FunctionProtoType> ContextTy
= S.Context.getCanonicalType(Context->getType())
->getAs<FunctionProtoType>();
// There isn't any way that I know of to add qualifiers
// during instantiation.
if (FriendTy.getQualifiers() != ContextTy.getQualifiers())
return false;
if (FriendTy->getNumParams() != ContextTy->getNumParams())
return false;
if (!MightInstantiateTo(S, ContextTy->getReturnType(),
FriendTy->getReturnType()))
return false;
for (unsigned I = 0, E = FriendTy->getNumParams(); I != E; ++I)
if (!MightInstantiateTo(S, ContextTy->getParamType(I),
FriendTy->getParamType(I)))
return false;
return true;
}
static bool MightInstantiateTo(Sema &S,
FunctionTemplateDecl *Context,
FunctionTemplateDecl *Friend) {
return MightInstantiateTo(S,
Context->getTemplatedDecl(),
Friend->getTemplatedDecl());
}
static AccessResult MatchesFriend(Sema &S,
const EffectiveContext &EC,
const CXXRecordDecl *Friend) {
if (EC.includesClass(Friend))
return AR_accessible;
if (EC.isDependent()) {
for (const CXXRecordDecl *Context : EC.Records) {
if (MightInstantiateTo(Context, Friend))
return AR_dependent;
}
}
return AR_inaccessible;
}
static AccessResult MatchesFriend(Sema &S,
const EffectiveContext &EC,
CanQualType Friend) {
if (const RecordType *RT = Friend->getAs<RecordType>())
return MatchesFriend(S, EC, cast<CXXRecordDecl>(RT->getDecl()));
// TODO: we can do better than this
if (Friend->isDependentType())
return AR_dependent;
return AR_inaccessible;
}
/// Determines whether the given friend class template matches
/// anything in the effective context.
static AccessResult MatchesFriend(Sema &S,
const EffectiveContext &EC,
ClassTemplateDecl *Friend) {
AccessResult OnFailure = AR_inaccessible;
// Check whether the friend is the template of a class in the
// context chain.
for (SmallVectorImpl<CXXRecordDecl*>::const_iterator
I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
CXXRecordDecl *Record = *I;
// Figure out whether the current class has a template:
ClassTemplateDecl *CTD;
// A specialization of the template...
if (isa<ClassTemplateSpecializationDecl>(Record)) {
CTD = cast<ClassTemplateSpecializationDecl>(Record)
->getSpecializedTemplate();
// ... or the template pattern itself.
} else {
CTD = Record->getDescribedClassTemplate();
if (!CTD) continue;
}
// It's a match.
if (Friend == CTD->getCanonicalDecl())
return AR_accessible;
// If the context isn't dependent, it can't be a dependent match.
if (!EC.isDependent())
continue;
// If the template names don't match, it can't be a dependent
// match.
if (CTD->getDeclName() != Friend->getDeclName())
continue;
// If the class's context can't instantiate to the friend's
// context, it can't be a dependent match.
if (!MightInstantiateTo(S, CTD->getDeclContext(),
Friend->getDeclContext()))
continue;
// Otherwise, it's a dependent match.
OnFailure = AR_dependent;
}
return OnFailure;
}
/// Determines whether the given friend function matches anything in
/// the effective context.
static AccessResult MatchesFriend(Sema &S,
const EffectiveContext &EC,
FunctionDecl *Friend) {
AccessResult OnFailure = AR_inaccessible;
for (SmallVectorImpl<FunctionDecl*>::const_iterator
I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
if (Friend == *I)
return AR_accessible;
if (EC.isDependent() && MightInstantiateTo(S, *I, Friend))
OnFailure = AR_dependent;
}
return OnFailure;
}
/// Determines whether the given friend function template matches
/// anything in the effective context.
static AccessResult MatchesFriend(Sema &S,
const EffectiveContext &EC,
FunctionTemplateDecl *Friend) {
if (EC.Functions.empty()) return AR_inaccessible;
AccessResult OnFailure = AR_inaccessible;
for (SmallVectorImpl<FunctionDecl*>::const_iterator
I = EC.Functions.begin(), E = EC.Functions.end(); I != E; ++I) {
FunctionTemplateDecl *FTD = (*I)->getPrimaryTemplate();
if (!FTD)
FTD = (*I)->getDescribedFunctionTemplate();
if (!FTD)
continue;
FTD = FTD->getCanonicalDecl();
if (Friend == FTD)
return AR_accessible;
if (EC.isDependent() && MightInstantiateTo(S, FTD, Friend))
OnFailure = AR_dependent;
}
return OnFailure;
}
/// Determines whether the given friend declaration matches anything
/// in the effective context.
static AccessResult MatchesFriend(Sema &S,
const EffectiveContext &EC,
FriendDecl *FriendD) {
// Whitelist accesses if there's an invalid or unsupported friend
// declaration.
if (FriendD->isInvalidDecl() || FriendD->isUnsupportedFriend())
return AR_accessible;
if (TypeSourceInfo *T = FriendD->getFriendType())
return MatchesFriend(S, EC, T->getType()->getCanonicalTypeUnqualified());
NamedDecl *Friend
= cast<NamedDecl>(FriendD->getFriendDecl()->getCanonicalDecl());
// FIXME: declarations with dependent or templated scope.
if (isa<ClassTemplateDecl>(Friend))
return MatchesFriend(S, EC, cast<ClassTemplateDecl>(Friend));
if (isa<FunctionTemplateDecl>(Friend))
return MatchesFriend(S, EC, cast<FunctionTemplateDecl>(Friend));
if (isa<CXXRecordDecl>(Friend))
return MatchesFriend(S, EC, cast<CXXRecordDecl>(Friend));
assert(isa<FunctionDecl>(Friend) && "unknown friend decl kind");
return MatchesFriend(S, EC, cast<FunctionDecl>(Friend));
}
static AccessResult GetFriendKind(Sema &S,
const EffectiveContext &EC,
const CXXRecordDecl *Class) {
AccessResult OnFailure = AR_inaccessible;
// Okay, check friends.
for (auto *Friend : Class->friends()) {
switch (MatchesFriend(S, EC, Friend)) {
case AR_accessible:
return AR_accessible;
case AR_inaccessible:
continue;
case AR_dependent:
OnFailure = AR_dependent;
break;
}
}
// That's it, give up.
return OnFailure;
}
namespace {
/// A helper class for checking for a friend which will grant access
/// to a protected instance member.
struct ProtectedFriendContext {
Sema &S;
const EffectiveContext &EC;
const CXXRecordDecl *NamingClass;
bool CheckDependent;
bool EverDependent;
/// The path down to the current base class.
SmallVector<const CXXRecordDecl*, 20> CurPath;
ProtectedFriendContext(Sema &S, const EffectiveContext &EC,
const CXXRecordDecl *InstanceContext,
const CXXRecordDecl *NamingClass)
: S(S), EC(EC), NamingClass(NamingClass),
CheckDependent(InstanceContext->isDependentContext() ||
NamingClass->isDependentContext()),
EverDependent(false) {}
/// Check classes in the current path for friendship, starting at
/// the given index.
bool checkFriendshipAlongPath(unsigned I) {
assert(I < CurPath.size());
for (unsigned E = CurPath.size(); I != E; ++I) {
switch (GetFriendKind(S, EC, CurPath[I])) {
case AR_accessible: return true;
case AR_inaccessible: continue;
case AR_dependent: EverDependent = true; continue;
}
}
return false;
}
/// Perform a search starting at the given class.
///
/// PrivateDepth is the index of the last (least derived) class
/// along the current path such that a notional public member of
/// the final class in the path would have access in that class.
bool findFriendship(const CXXRecordDecl *Cur, unsigned PrivateDepth) {
// If we ever reach the naming class, check the current path for
// friendship. We can also stop recursing because we obviously
// won't find the naming class there again.
if (Cur == NamingClass)
return checkFriendshipAlongPath(PrivateDepth);
if (CheckDependent && MightInstantiateTo(Cur, NamingClass))
EverDependent = true;
// Recurse into the base classes.
for (const auto &I : Cur->bases()) {
// If this is private inheritance, then a public member of the
// base will not have any access in classes derived from Cur.
unsigned BasePrivateDepth = PrivateDepth;
if (I.getAccessSpecifier() == AS_private)
BasePrivateDepth = CurPath.size() - 1;
const CXXRecordDecl *RD;
QualType T = I.getType();
if (const RecordType *RT = T->getAs<RecordType>()) {
RD = cast<CXXRecordDecl>(RT->getDecl());
} else if (const InjectedClassNameType *IT
= T->getAs<InjectedClassNameType>()) {
RD = IT->getDecl();
} else {
assert(T->isDependentType() && "non-dependent base wasn't a record?");
EverDependent = true;
continue;
}
// Recurse. We don't need to clean up if this returns true.
CurPath.push_back(RD);
if (findFriendship(RD->getCanonicalDecl(), BasePrivateDepth))
return true;
CurPath.pop_back();
}
return false;
}
bool findFriendship(const CXXRecordDecl *Cur) {
assert(CurPath.empty());
CurPath.push_back(Cur);
return findFriendship(Cur, 0);
}
};
}
/// Search for a class P that EC is a friend of, under the constraint
/// InstanceContext <= P
/// if InstanceContext exists, or else
/// NamingClass <= P
/// and with the additional restriction that a protected member of
/// NamingClass would have some natural access in P, which implicitly
/// imposes the constraint that P <= NamingClass.
///
/// This isn't quite the condition laid out in the standard.
/// Instead of saying that a notional protected member of NamingClass
/// would have to have some natural access in P, it says the actual
/// target has to have some natural access in P, which opens up the
/// possibility that the target (which is not necessarily a member
/// of NamingClass) might be more accessible along some path not
/// passing through it. That's really a bad idea, though, because it
/// introduces two problems:
/// - Most importantly, it breaks encapsulation because you can
/// access a forbidden base class's members by directly subclassing
/// it elsewhere.
/// - It also makes access substantially harder to compute because it
/// breaks the hill-climbing algorithm: knowing that the target is
/// accessible in some base class would no longer let you change
/// the question solely to whether the base class is accessible,
/// because the original target might have been more accessible
/// because of crazy subclassing.
/// So we don't implement that.
static AccessResult GetProtectedFriendKind(Sema &S, const EffectiveContext &EC,
const CXXRecordDecl *InstanceContext,
const CXXRecordDecl *NamingClass) {
assert(InstanceContext == nullptr ||
InstanceContext->getCanonicalDecl() == InstanceContext);
assert(NamingClass->getCanonicalDecl() == NamingClass);
// If we don't have an instance context, our constraints give us
// that NamingClass <= P <= NamingClass, i.e. P == NamingClass.
// This is just the usual friendship check.
if (!InstanceContext) return GetFriendKind(S, EC, NamingClass);
ProtectedFriendContext PRC(S, EC, InstanceContext, NamingClass);
if (PRC.findFriendship(InstanceContext)) return AR_accessible;
if (PRC.EverDependent) return AR_dependent;
return AR_inaccessible;
}
static AccessResult HasAccess(Sema &S,
const EffectiveContext &EC,
const CXXRecordDecl *NamingClass,
AccessSpecifier Access,
const AccessTarget &Target) {
assert(NamingClass->getCanonicalDecl() == NamingClass &&
"declaration should be canonicalized before being passed here");
if (Access == AS_public) return AR_accessible;
assert(Access == AS_private || Access == AS_protected);
AccessResult OnFailure = AR_inaccessible;
for (EffectiveContext::record_iterator
I = EC.Records.begin(), E = EC.Records.end(); I != E; ++I) {
// All the declarations in EC have been canonicalized, so pointer
// equality from this point on will work fine.
const CXXRecordDecl *ECRecord = *I;
// [B2] and [M2]
if (Access == AS_private) {
if (ECRecord == NamingClass)
return AR_accessible;
if (EC.isDependent() && MightInstantiateTo(ECRecord, NamingClass))
OnFailure = AR_dependent;
// [B3] and [M3]
} else {
assert(Access == AS_protected);
switch (IsDerivedFromInclusive(ECRecord, NamingClass)) {
case AR_accessible: break;
case AR_inaccessible: continue;
case AR_dependent: OnFailure = AR_dependent; continue;
}
// C++ [class.protected]p1:
// An additional access check beyond those described earlier in
// [class.access] is applied when a non-static data member or
// non-static member function is a protected member of its naming
// class. As described earlier, access to a protected member is
// granted because the reference occurs in a friend or member of
// some class C. If the access is to form a pointer to member,
// the nested-name-specifier shall name C or a class derived from
// C. All other accesses involve a (possibly implicit) object
// expression. In this case, the class of the object expression
// shall be C or a class derived from C.
//
// We interpret this as a restriction on [M3].
// In this part of the code, 'C' is just our context class ECRecord.
// These rules are different if we don't have an instance context.
if (!Target.hasInstanceContext()) {
// If it's not an instance member, these restrictions don't apply.
if (!Target.isInstanceMember()) return AR_accessible;
// If it's an instance member, use the pointer-to-member rule
// that the naming class has to be derived from the effective
// context.
// Emulate a MSVC bug where the creation of pointer-to-member
// to protected member of base class is allowed but only from
// static member functions.
if (S.getLangOpts().MSVCCompat && !EC.Functions.empty())
if (CXXMethodDecl* MD = dyn_cast<CXXMethodDecl>(EC.Functions.front()))
if (MD->isStatic()) return AR_accessible;
// Despite the standard's confident wording, there is a case
// where you can have an instance member that's neither in a
// pointer-to-member expression nor in a member access: when
// it names a field in an unevaluated context that can't be an
// implicit member. Pending clarification, we just apply the
// same naming-class restriction here.
// FIXME: we're probably not correctly adding the
// protected-member restriction when we retroactively convert
// an expression to being evaluated.
// We know that ECRecord derives from NamingClass. The
// restriction says to check whether NamingClass derives from
// ECRecord, but that's not really necessary: two distinct
// classes can't be recursively derived from each other. So
// along this path, we just need to check whether the classes
// are equal.
if (NamingClass == ECRecord) return AR_accessible;
// Otherwise, this context class tells us nothing; on to the next.
continue;
}
assert(Target.isInstanceMember());
const CXXRecordDecl *InstanceContext = Target.resolveInstanceContext(S);
if (!InstanceContext) {
OnFailure = AR_dependent;
continue;
}
switch (IsDerivedFromInclusive(InstanceContext, ECRecord)) {
case AR_accessible: return AR_accessible;
case AR_inaccessible: continue;
case AR_dependent: OnFailure = AR_dependent; continue;
}
}
}
// [M3] and [B3] say that, if the target is protected in N, we grant
// access if the access occurs in a friend or member of some class P
// that's a subclass of N and where the target has some natural
// access in P. The 'member' aspect is easy to handle because P
// would necessarily be one of the effective-context records, and we
// address that above. The 'friend' aspect is completely ridiculous
// to implement because there are no restrictions at all on P
// *unless* the [class.protected] restriction applies. If it does,
// however, we should ignore whether the naming class is a friend,
// and instead rely on whether any potential P is a friend.
if (Access == AS_protected && Target.isInstanceMember()) {
// Compute the instance context if possible.
const CXXRecordDecl *InstanceContext = nullptr;
if (Target.hasInstanceContext()) {
InstanceContext = Target.resolveInstanceContext(S);
if (!InstanceContext) return AR_dependent;
}
switch (GetProtectedFriendKind(S, EC, InstanceContext, NamingClass)) {
case AR_accessible: return AR_accessible;
case AR_inaccessible: return OnFailure;
case AR_dependent: return AR_dependent;
}
llvm_unreachable("impossible friendship kind");
}
switch (GetFriendKind(S, EC, NamingClass)) {
case AR_accessible: return AR_accessible;
case AR_inaccessible: return OnFailure;
case AR_dependent: return AR_dependent;
}
// Silence bogus warnings
llvm_unreachable("impossible friendship kind");
}
/// Finds the best path from the naming class to the declaring class,
/// taking friend declarations into account.
///
/// C++0x [class.access.base]p5:
/// A member m is accessible at the point R when named in class N if
/// [M1] m as a member of N is public, or
/// [M2] m as a member of N is private, and R occurs in a member or
/// friend of class N, or
/// [M3] m as a member of N is protected, and R occurs in a member or
/// friend of class N, or in a member or friend of a class P
/// derived from N, where m as a member of P is public, private,
/// or protected, or
/// [M4] there exists a base class B of N that is accessible at R, and
/// m is accessible at R when named in class B.
///
/// C++0x [class.access.base]p4:
/// A base class B of N is accessible at R, if
/// [B1] an invented public member of B would be a public member of N, or
/// [B2] R occurs in a member or friend of class N, and an invented public
/// member of B would be a private or protected member of N, or
/// [B3] R occurs in a member or friend of a class P derived from N, and an
/// invented public member of B would be a private or protected member
/// of P, or
/// [B4] there exists a class S such that B is a base class of S accessible
/// at R and S is a base class of N accessible at R.
///
/// Along a single inheritance path we can restate both of these
/// iteratively:
///
/// First, we note that M1-4 are equivalent to B1-4 if the member is
/// treated as a notional base of its declaring class with inheritance
/// access equivalent to the member's access. Therefore we need only
/// ask whether a class B is accessible from a class N in context R.
///
/// Let B_1 .. B_n be the inheritance path in question (i.e. where
/// B_1 = N, B_n = B, and for all i, B_{i+1} is a direct base class of
/// B_i). For i in 1..n, we will calculate ACAB(i), the access to the
/// closest accessible base in the path:
/// Access(a, b) = (* access on the base specifier from a to b *)
/// Merge(a, forbidden) = forbidden
/// Merge(a, private) = forbidden
/// Merge(a, b) = min(a,b)
/// Accessible(c, forbidden) = false
/// Accessible(c, private) = (R is c) || IsFriend(c, R)
/// Accessible(c, protected) = (R derived from c) || IsFriend(c, R)
/// Accessible(c, public) = true
/// ACAB(n) = public
/// ACAB(i) =
/// let AccessToBase = Merge(Access(B_i, B_{i+1}), ACAB(i+1)) in
/// if Accessible(B_i, AccessToBase) then public else AccessToBase
///
/// B is an accessible base of N at R iff ACAB(1) = public.
///
/// \param FinalAccess the access of the "final step", or AS_public if
/// there is no final step.
/// \return null if friendship is dependent
static CXXBasePath *FindBestPath(Sema &S,
const EffectiveContext &EC,
AccessTarget &Target,
AccessSpecifier FinalAccess,
CXXBasePaths &Paths) {
// Derive the paths to the desired base.
const CXXRecordDecl *Derived = Target.getNamingClass();
const CXXRecordDecl *Base = Target.getDeclaringClass();
// FIXME: fail correctly when there are dependent paths.
bool isDerived = Derived->isDerivedFrom(const_cast<CXXRecordDecl*>(Base),
Paths);
assert(isDerived && "derived class not actually derived from base");
(void) isDerived;
CXXBasePath *BestPath = nullptr;
assert(FinalAccess != AS_none && "forbidden access after declaring class");
bool AnyDependent = false;
// Derive the friend-modified access along each path.
for (CXXBasePaths::paths_iterator PI = Paths.begin(), PE = Paths.end();
PI != PE; ++PI) {
AccessTarget::SavedInstanceContext _ = Target.saveInstanceContext();
// Walk through the path backwards.
AccessSpecifier PathAccess = FinalAccess;
CXXBasePath::iterator I = PI->end(), E = PI->begin();
while (I != E) {
--I;
assert(PathAccess != AS_none);
// If the declaration is a private member of a base class, there
// is no level of friendship in derived classes that can make it
// accessible.
if (PathAccess == AS_private) {
PathAccess = AS_none;
break;
}
const CXXRecordDecl *NC = I->Class->getCanonicalDecl();
AccessSpecifier BaseAccess = I->Base->getAccessSpecifier();
PathAccess = std::max(PathAccess, BaseAccess);
switch (HasAccess(S, EC, NC, PathAccess, Target)) {
case AR_inaccessible: break;
case AR_accessible:
PathAccess = AS_public;
// Future tests are not against members and so do not have
// instance context.
Target.suppressInstanceContext();
break;
case AR_dependent:
AnyDependent = true;
goto Next;
}
}
// Note that we modify the path's Access field to the
// friend-modified access.
if (BestPath == nullptr || PathAccess < BestPath->Access) {
BestPath = &*PI;
BestPath->Access = PathAccess;
// Short-circuit if we found a public path.
if (BestPath->Access == AS_public)
return BestPath;
}
Next: ;
}