-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathTypeCheckAccess.cpp
2684 lines (2373 loc) · 106 KB
/
TypeCheckAccess.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
//===--- TypeCheckAccess.cpp - Type Checking for Access Control -----------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements access control checking.
//
//===----------------------------------------------------------------------===//
#include "TypeCheckAccess.h"
#include "TypeAccessScopeChecker.h"
#include "TypeCheckAvailability.h"
#include "TypeCheckUnsafe.h"
#include "TypeChecker.h"
#include "swift/AST/ASTVisitor.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/ClangModuleLoader.h"
#include "swift/AST/DeclExportabilityVisitor.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Import.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/Basic/Assertions.h"
#include "clang/AST/DeclCXX.h"
#include "clang/AST/DeclObjC.h"
using namespace swift;
#define DEBUG_TYPE "TypeCheckAccess"
namespace {
/// Calls \p callback for each type in each requirement provided by
/// \p source.
static void forAllRequirementTypes(
WhereClauseOwner &&source,
llvm::function_ref<void(Type, TypeRepr *)> callback) {
std::move(source).visitRequirements(TypeResolutionStage::Interface,
[&](const Requirement &req, RequirementRepr *reqRepr) {
switch (req.getKind()) {
case RequirementKind::SameShape:
case RequirementKind::Conformance:
case RequirementKind::SameType:
case RequirementKind::Superclass:
callback(req.getFirstType(),
RequirementRepr::getFirstTypeRepr(reqRepr));
callback(req.getSecondType(),
RequirementRepr::getSecondTypeRepr(reqRepr));
break;
case RequirementKind::Layout:
callback(req.getFirstType(),
RequirementRepr::getFirstTypeRepr(reqRepr));
break;
}
return false;
});
}
/// \see checkTypeAccess
using CheckTypeAccessCallback =
void(AccessScope, const TypeRepr *, DowngradeToWarning, ImportAccessLevel);
class AccessControlCheckerBase {
protected:
bool checkUsableFromInline;
void checkTypeAccessImpl(
Type type, TypeRepr *typeRepr, AccessScope contextAccessScope,
const DeclContext *useDC, bool mayBeInferred,
llvm::function_ref<CheckTypeAccessCallback> diagnose);
void checkTypeAccess(
Type type, TypeRepr *typeRepr, const ValueDecl *context,
bool mayBeInferred,
llvm::function_ref<CheckTypeAccessCallback> diagnose);
void checkTypeAccess(
const TypeLoc &TL, const ValueDecl *context, bool mayBeInferred,
llvm::function_ref<CheckTypeAccessCallback> diagnose) {
return checkTypeAccess(TL.getType(), TL.getTypeRepr(), context,
mayBeInferred, diagnose);
}
void checkRequirementAccess(
WhereClauseOwner &&source,
AccessScope accessScope,
const DeclContext *useDC,
llvm::function_ref<CheckTypeAccessCallback> diagnose) {
forAllRequirementTypes(std::move(source), [&](Type type, TypeRepr *typeRepr) {
checkTypeAccessImpl(type, typeRepr, accessScope, useDC,
/*mayBeInferred*/false, diagnose);
});
}
AccessControlCheckerBase(bool checkUsableFromInline)
: checkUsableFromInline(checkUsableFromInline) {}
public:
void checkGenericParamAccess(
const GenericContext *ownerCtx,
const Decl *ownerDecl,
AccessScope accessScope,
AccessLevel contextAccess);
void checkGenericParamAccess(
const GenericContext *ownerCtx,
const ValueDecl *ownerDecl);
void checkGlobalActorAccess(const Decl *D);
};
} // end anonymous namespace
/// Searches the given type representation for a `DeclRefTypeRepr` that is
/// bound to a type declaration with the given access scope. The type
/// representation is searched in source order. For example, nodes in
/// `A<T>.B<U>` will be checked in the following order: `ATBU`.
static const DeclRefTypeRepr *
findTypeDeclWithAccessScope(TypeRepr *TR, AccessScope accessScope,
const DeclContext *useDC,
bool treatUsableFromInlineAsPublic) {
if (!TR) {
return nullptr;
}
class Finder : public ASTWalker {
AccessScope accessScope;
const DeclContext *useDC;
bool treatUsableFromInlineAsPublic;
const DeclRefTypeRepr *theFind;
public:
explicit Finder(AccessScope accessScope, const DeclContext *useDC,
bool treatUsableFromInlineAsPublic)
: accessScope(accessScope), useDC(useDC),
treatUsableFromInlineAsPublic(treatUsableFromInlineAsPublic),
theFind(nullptr) {}
const DeclRefTypeRepr *getFind() const { return theFind; }
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::ArgumentsAndExpansion;
}
QualifiedIdentTypeReprWalkingScheme
getQualifiedIdentTypeReprWalkingScheme() const override {
return QualifiedIdentTypeReprWalkingScheme::SourceOrderRecursive;
}
PreWalkAction walkToTypeReprPre(TypeRepr *TR) override {
auto *declRefTR = dyn_cast<DeclRefTypeRepr>(TR);
if (!declRefTR)
return Action::Continue();
const ValueDecl *VD = declRefTR->getBoundDecl();
if (!VD)
return Action::Continue();
if (VD->getFormalAccessScope(useDC, treatUsableFromInlineAsPublic) !=
accessScope)
return Action::Continue();
theFind = declRefTR;
return Action::Stop();
}
} walker(accessScope, useDC, treatUsableFromInlineAsPublic);
TR->walk(walker);
return walker.getFind();
}
/// Checks if the access scope of the type described by \p TL contains
/// \p contextAccessScope. If it isn't, calls \p diagnose with a TypeRepr
/// representing the offending part of \p TL.
///
/// The TypeRepr passed to \p diagnose may be null, in which case a particular
/// part of the type that caused the problem could not be found. The DeclContext
/// is never null.
///
/// If \p type might be partially inferred even when \p typeRepr is present
/// (such as for properties), pass \c true for \p mayBeInferred. (This does not
/// include implicitly providing generic parameters for the Self type, such as
/// using `Array` to mean `Array<Element>` in an extension of Array.) If
/// \p typeRepr is known to be absent, it's okay to pass \c false for
/// \p mayBeInferred.
void AccessControlCheckerBase::checkTypeAccessImpl(
Type type, TypeRepr *typeRepr, AccessScope contextAccessScope,
const DeclContext *useDC, bool mayBeInferred,
llvm::function_ref<CheckTypeAccessCallback> diagnose) {
auto &Context = useDC->getASTContext();
if (Context.isAccessControlDisabled())
return;
// Don't spend time checking local declarations; this is always valid by the
// time we get to this point.
if (contextAccessScope.isInContext() &&
contextAccessScope.getDeclContext()->isLocalContext())
return;
// Report where it was imported from.
if (contextAccessScope.isPublicOrPackage()) {
auto report = [&](const DeclRefTypeRepr *typeRepr, const ValueDecl *VD) {
// Remember that the module defining the decl must be imported publicly.
recordRequiredImportAccessLevelForDecl(
VD, useDC, contextAccessScope.accessLevelForDiagnostics(),
[&](AttributedImport<ImportedModule> attributedImport) {
SourceLoc diagLoc =
typeRepr ? typeRepr->getLoc() : extractNearestSourceLoc(useDC);
ModuleDecl *importedVia = attributedImport.module.importedModule,
*sourceModule = VD->getModuleContext();
Context.Diags.diagnose(diagLoc, diag::module_api_import, VD,
importedVia, sourceModule,
importedVia == sourceModule,
/*isImplicit*/ !typeRepr);
});
};
if (typeRepr) {
typeRepr->walk(DeclRefTypeReprFinder([&](const DeclRefTypeRepr *TR) {
const ValueDecl *VD = TR->getBoundDecl();
report(TR, VD);
return true;
}));
} else if (type) {
type.walk(SimpleTypeDeclFinder([&](const ValueDecl *VD) {
report(/*typeRepr=*/nullptr, VD);
return TypeWalker::Action::Continue;
}));
}
};
AccessScope problematicAccessScope = AccessScope::getPublic();
if (type) {
std::optional<AccessScope> typeAccessScope =
TypeAccessScopeChecker::getAccessScope(type, useDC,
checkUsableFromInline);
// Note: This means that the type itself is invalid for this particular
// context, because it references declarations from two incompatible scopes.
// In this case we should have diagnosed the bad reference already.
if (!typeAccessScope.has_value())
return;
problematicAccessScope = *typeAccessScope;
}
auto downgradeToWarning = DowngradeToWarning::No;
// Check if type can be referenced in this context.
// - hasEqualDeclContextWith checks for matching scopes (public to public,
// internal to the same module, private to same scope, etc.)
// - isChildOf checks for use of public in internal, etc.
if (contextAccessScope.hasEqualDeclContextWith(problematicAccessScope) ||
contextAccessScope.isChildOf(problematicAccessScope)) {
// /Also/ check the TypeRepr, if present. This can be important when we're
// unable to preserve typealias sugar that's present in the TypeRepr.
if (!typeRepr)
return;
auto typeReprAccessScope =
TypeAccessScopeChecker::getAccessScope(typeRepr, useDC,
checkUsableFromInline);
if (!typeReprAccessScope.has_value())
return;
if (contextAccessScope.hasEqualDeclContextWith(*typeReprAccessScope) ||
contextAccessScope.isChildOf(*typeReprAccessScope)) {
// Only if both the Type and the TypeRepr follow the access rules can
// we exit; otherwise we have to emit a diagnostic.
return;
}
problematicAccessScope = *typeReprAccessScope;
} else {
// The type violates the rules of access control (with or without taking the
// TypeRepr into account).
if (typeRepr && mayBeInferred &&
!Context.LangOpts.isSwiftVersionAtLeast(5) &&
!useDC->getParentModule()->isResilient()) {
// Swift 4.2 and earlier didn't check the Type when a TypeRepr was
// present. However, this is a major hole when generic parameters are
// inferred:
//
// public let foo: Optional = VeryPrivateStruct()
//
// Downgrade the error to a warning in this case for source compatibility.
std::optional<AccessScope> typeReprAccessScope =
TypeAccessScopeChecker::getAccessScope(typeRepr, useDC,
checkUsableFromInline);
assert(typeReprAccessScope && "valid Type but not valid TypeRepr?");
if (contextAccessScope.hasEqualDeclContextWith(*typeReprAccessScope) ||
contextAccessScope.isChildOf(*typeReprAccessScope)) {
downgradeToWarning = DowngradeToWarning::Yes;
}
}
}
const DeclRefTypeRepr *complainRepr = findTypeDeclWithAccessScope(
typeRepr, problematicAccessScope, useDC, checkUsableFromInline);
ImportAccessLevel complainImport = std::nullopt;
if (complainRepr) {
const ValueDecl *VD = complainRepr->getBoundDecl();
assert(VD &&
"findTypeDeclWithAccessScope should return bound TypeReprs only");
complainImport = VD->getImportAccessFrom(useDC);
// Don't complain about an import that doesn't restrict the access
// level of the decl. This can happen with imported `package` decls.
if (complainImport.has_value() &&
complainImport->accessLevel >= VD->getFormalAccess())
complainImport = std::nullopt;
}
diagnose(problematicAccessScope, complainRepr, downgradeToWarning,
complainImport);
}
/// Checks if the access scope of the type described by \p TL is valid for the
/// type to be the type of \p context. If it isn't, calls \p diagnose with a
/// TypeRepr representing the offending part of \p TL.
///
/// The TypeRepr passed to \p diagnose may be null, in which case a particular
/// part of the type that caused the problem could not be found.
///
/// If \p type might be partially inferred even when \p typeRepr is present
/// (such as for properties), pass \c true for \p mayBeInferred. (This does not
/// include implicitly providing generic parameters for the Self type, such as
/// using `Array` to mean `Array<Element>` in an extension of Array.) If
/// \p typeRepr is known to be absent, it's okay to pass \c false for
/// \p mayBeInferred.
void AccessControlCheckerBase::checkTypeAccess(
Type type, TypeRepr *typeRepr, const ValueDecl *context, bool mayBeInferred,
llvm::function_ref<CheckTypeAccessCallback> diagnose) {
assert(!isa<ParamDecl>(context));
const DeclContext *DC = context->getDeclContext();
AccessScope contextAccessScope =
context->getFormalAccessScope(
context->getDeclContext(), checkUsableFromInline);
checkTypeAccessImpl(type, typeRepr, contextAccessScope, DC, mayBeInferred,
diagnose);
}
/// Highlights the given TypeRepr, and adds a note pointing to the type's
/// declaration if possible.
///
/// Just flushes \p diag as is if \p complainRepr is null.
static void highlightOffendingType(InFlightDiagnostic &diag,
const TypeRepr *complainRepr) {
if (!complainRepr) {
diag.flush();
return;
}
diag.highlight(complainRepr->getSourceRange());
diag.flush();
if (auto *declRefTR = dyn_cast<DeclRefTypeRepr>(complainRepr)) {
const ValueDecl *VD = declRefTR->getBoundDecl();
VD->diagnose(diag::kind_declared_here, DescriptiveDeclKind::Type);
}
}
/// Emit a note on \p limitImport when it restricted the access level
/// of a type.
static void noteLimitingImport(const Decl *userDecl, ASTContext &ctx,
const ImportAccessLevel limitImport,
const Decl *complainDecl) {
if (!limitImport.has_value())
return;
assert(limitImport->accessLevel != AccessLevel::Public &&
"a public import shouldn't limit the access level of a decl");
if (complainDecl) {
// When using an IDE in a large file the decl_import_via_here note
// may be easy to miss on the import. Duplicate the information on the
// error line as well so it can't be missed.
if (userDecl)
userDecl->diagnose(diag::decl_import_via_local, complainDecl,
limitImport->accessLevel,
limitImport->module.importedModule);
if (limitImport->importLoc.isValid())
ctx.Diags.diagnose(limitImport->importLoc, diag::decl_import_via_here,
complainDecl, limitImport->accessLevel,
limitImport->module.importedModule);
} else if (limitImport->importLoc.isValid()) {
ctx.Diags.diagnose(limitImport->importLoc, diag::module_imported_here,
limitImport->module.importedModule,
limitImport->accessLevel);
}
}
static void noteLimitingImport(const Decl *userDecl, ASTContext &ctx,
const ImportAccessLevel limitImport,
const TypeRepr *complainRepr) {
const Decl *complainDecl = nullptr;
if (auto *declRefTR = dyn_cast_or_null<DeclRefTypeRepr>(complainRepr))
complainDecl = declRefTR->getBoundDecl();
noteLimitingImport(userDecl, ctx, limitImport, complainDecl);
}
static void noteLimitingImport(const Decl *userDecl,
const ImportAccessLevel limitImport,
const TypeRepr *complainRepr) {
noteLimitingImport(userDecl, userDecl->getASTContext(), limitImport,
complainRepr);
}
void AccessControlCheckerBase::checkGenericParamAccess(
const GenericContext *ownerCtx,
const Decl *ownerDecl,
AccessScope accessScope,
AccessLevel contextAccess) {
if (!ownerCtx->isGenericContext())
return;
// This must stay in sync with diag::generic_param_access.
enum class ACEK {
Parameter = 0,
Requirement
} accessControlErrorKind;
auto minAccessScope = AccessScope::getPublic();
const TypeRepr *complainRepr = nullptr;
auto downgradeToWarning = DowngradeToWarning::Yes;
ImportAccessLevel minImportLimit = std::nullopt;
auto callbackACEK = ACEK::Parameter;
auto callback = [&](AccessScope typeAccessScope,
const TypeRepr *thisComplainRepr,
DowngradeToWarning thisDowngrade,
ImportAccessLevel importLimit) {
if (typeAccessScope.isChildOf(minAccessScope) ||
(thisDowngrade == DowngradeToWarning::No &&
downgradeToWarning == DowngradeToWarning::Yes) ||
(!complainRepr &&
typeAccessScope.hasEqualDeclContextWith(minAccessScope))) {
minAccessScope = typeAccessScope;
complainRepr = thisComplainRepr;
accessControlErrorKind = callbackACEK;
downgradeToWarning = thisDowngrade;
minImportLimit = importLimit;
}
};
auto *DC = ownerDecl->getDeclContext();
if (auto params = ownerCtx->getGenericParams()) {
for (auto param : *params) {
auto inheritedEntries = param->getInherited().getEntries();
if (inheritedEntries.empty())
continue;
assert(inheritedEntries.size() == 1);
checkTypeAccessImpl(inheritedEntries.front().getType(),
inheritedEntries.front().getTypeRepr(), accessScope,
DC, /*mayBeInferred*/ false, callback);
}
}
callbackACEK = ACEK::Requirement;
if (ownerCtx->getTrailingWhereClause()) {
checkRequirementAccess(WhereClauseOwner(
const_cast<GenericContext *>(ownerCtx)),
accessScope, DC, callback);
}
if (minAccessScope.isPublic())
return;
// FIXME: Promote these to an error in the next -swift-version break.
if (isa<SubscriptDecl>(ownerDecl) || isa<TypeAliasDecl>(ownerDecl))
downgradeToWarning = DowngradeToWarning::Yes;
auto &Context = ownerDecl->getASTContext();
if (checkUsableFromInline) {
if (!Context.isSwiftVersionAtLeast(5))
downgradeToWarning = DowngradeToWarning::Yes;
auto diagID = diag::generic_param_usable_from_inline;
if (downgradeToWarning == DowngradeToWarning::Yes)
diagID = diag::generic_param_usable_from_inline_warn;
auto diag =
Context.Diags.diagnose(ownerDecl, diagID, ownerDecl->getDescriptiveKind(),
accessControlErrorKind == ACEK::Requirement);
highlightOffendingType(diag, complainRepr);
noteLimitingImport(/*userDecl*/nullptr, Context, minImportLimit, complainRepr);
return;
}
auto minAccess = minAccessScope.accessLevelForDiagnostics();
bool isExplicit =
ownerDecl->getAttrs().hasAttribute<AccessControlAttr>() ||
isa<ProtocolDecl>(DC);
auto diagID = diag::generic_param_access;
if (downgradeToWarning == DowngradeToWarning::Yes)
diagID = diag::generic_param_access_warn;
auto diag = Context.Diags.diagnose(
ownerDecl, diagID, ownerDecl->getDescriptiveKind(), isExplicit,
contextAccess, minAccess, isa<FileUnit>(DC),
accessControlErrorKind == ACEK::Requirement);
highlightOffendingType(diag, complainRepr);
noteLimitingImport(/*userDecl*/nullptr, Context, minImportLimit, complainRepr);
}
void AccessControlCheckerBase::checkGenericParamAccess(
const GenericContext *ownerCtx,
const ValueDecl *ownerDecl) {
checkGenericParamAccess(ownerCtx, ownerDecl,
ownerDecl->getFormalAccessScope(
nullptr, checkUsableFromInline),
ownerDecl->getFormalAccess());
}
void AccessControlCheckerBase::checkGlobalActorAccess(const Decl *D) {
auto VD = dyn_cast<ValueDecl>(D);
if (!VD)
return;
auto globalActorAttr = D->getGlobalActorAttr();
if (!globalActorAttr)
return;
auto customAttr = globalActorAttr->first;
auto globalActorDecl = globalActorAttr->second;
checkTypeAccess(
customAttr->getType(), customAttr->getTypeRepr(), VD,
/*mayBeInferred*/ false,
[&](AccessScope typeAccessScope, const TypeRepr *complainRepr,
DowngradeToWarning downgradeToWarning, ImportAccessLevel importLimit) {
if (checkUsableFromInline) {
auto diag = D->diagnose(diag::global_actor_not_usable_from_inline,
VD);
highlightOffendingType(diag, complainRepr);
noteLimitingImport(D, importLimit, complainRepr);
return;
}
auto typeAccess = typeAccessScope.accessLevelForDiagnostics();
bool isExplicit = D->getAttrs().hasAttribute<AccessControlAttr>();
auto declAccess = isExplicit
? VD->getFormalAccess()
: typeAccessScope.requiredAccessForDiagnostics();
auto diag = D->diagnose(diag::global_actor_access, declAccess, VD,
typeAccess, globalActorDecl->getName());
highlightOffendingType(diag, complainRepr);
noteLimitingImport(D, importLimit, complainRepr);
});
}
namespace {
class AccessControlChecker : public AccessControlCheckerBase,
public DeclVisitor<AccessControlChecker> {
public:
AccessControlChecker(bool allowUsableFromInline)
: AccessControlCheckerBase(allowUsableFromInline) {}
AccessControlChecker()
: AccessControlCheckerBase(/*checkUsableFromInline=*/false) {}
void visit(Decl *D) {
if (D->isInvalid() || D->isImplicit())
return;
DeclVisitor<AccessControlChecker>::visit(D);
checkGlobalActorAccess(D);
checkAttachedMacrosAccess(D);
}
// Force all kinds to be handled at a lower level.
void visitDecl(Decl *D) = delete;
void visitValueDecl(ValueDecl *D) = delete;
#define UNREACHABLE(KIND, REASON) \
void visit##KIND##Decl(KIND##Decl *D) { \
llvm_unreachable(REASON); \
}
UNREACHABLE(Import, "cannot appear in a type context")
UNREACHABLE(Extension, "cannot appear in a type context")
UNREACHABLE(TopLevelCode, "cannot appear in a type context")
UNREACHABLE(Operator, "cannot appear in a type context")
UNREACHABLE(PrecedenceGroup, "cannot appear in a type context")
UNREACHABLE(Module, "cannot appear in a type context")
UNREACHABLE(Param, "does not have access control")
UNREACHABLE(GenericTypeParam, "does not have access control")
UNREACHABLE(Missing, "does not have access control")
UNREACHABLE(MissingMember, "does not have access control")
UNREACHABLE(MacroExpansion, "does not have access control")
UNREACHABLE(BuiltinTuple, "BuiltinTupleDecl should not show up here")
#undef UNREACHABLE
#define UNINTERESTING(KIND) \
void visit##KIND##Decl(KIND##Decl *D) {}
UNINTERESTING(EnumCase) // Handled at the EnumElement level.
UNINTERESTING(Var) // Handled at the PatternBinding level.
UNINTERESTING(Destructor) // Always correct.
UNINTERESTING(Accessor) // Handled by the Var or Subscript.
/// \see visitPatternBindingDecl
void checkNamedPattern(const NamedPattern *NP, bool isTypeContext,
const llvm::DenseSet<const VarDecl *> &seenVars) {
const VarDecl *theVar = NP->getDecl();
if (seenVars.count(theVar) || theVar->isInvalid())
return;
Type interfaceType = theVar->getInterfaceType();
checkTypeAccess(interfaceType, nullptr, theVar,
/*mayBeInferred*/false,
[&](AccessScope typeAccessScope,
const TypeRepr *complainRepr,
DowngradeToWarning downgradeToWarning,
ImportAccessLevel importLimit) {
auto typeAccess = typeAccessScope.accessLevelForDiagnostics();
bool isExplicit = theVar->getAttrs().hasAttribute<AccessControlAttr>() ||
isa<ProtocolDecl>(theVar->getDeclContext());
auto theVarAccess =
isExplicit ? theVar->getFormalAccess()
: typeAccessScope.requiredAccessForDiagnostics();
auto diagID = diag::pattern_type_access_inferred;
if (downgradeToWarning == DowngradeToWarning::Yes)
diagID = diag::pattern_type_access_inferred_warn;
auto &DE = theVar->getASTContext().Diags;
DE.diagnose(NP->getLoc(), diagID, theVar->isLet(),
isTypeContext, isExplicit, theVarAccess,
isa<FileUnit>(theVar->getDeclContext()),
typeAccess, interfaceType);
// As we pass in a null typeRepr the complainRepr will always be null.
// Extract the module import from the interface type instead.
const Decl *complainDecl = nullptr;
ImportAccessLevel complainImport = std::nullopt;
interfaceType.walk(SimpleTypeDeclFinder([&](const ValueDecl *VD) {
ImportAccessLevel import = VD->getImportAccessFrom(theVar->getDeclContext());
if (import.has_value() && import->accessLevel < VD->getFormalAccess()) {
complainDecl = VD;
complainImport = import;
return TypeWalker::Action::Stop;
}
return TypeWalker::Action::Continue;
}));
noteLimitingImport(theVar, theVar->getASTContext(), complainImport,
complainDecl);
});
}
void checkTypedPattern(const TypedPattern *TP, bool isTypeContext,
llvm::DenseSet<const VarDecl *> &seenVars) {
VarDecl *anyVar = nullptr;
TP->forEachVariable([&](VarDecl *V) {
seenVars.insert(V);
anyVar = V;
});
if (!anyVar)
return;
checkTypeAccess(TP->hasType() ? TP->getType() : Type(),
TP->getTypeRepr(), anyVar, /*mayBeInferred*/true,
[&](AccessScope typeAccessScope,
const TypeRepr *complainRepr,
DowngradeToWarning downgradeToWarning,
ImportAccessLevel importLimit) {
auto typeAccess = typeAccessScope.accessLevelForDiagnostics();
bool isExplicit = anyVar->getAttrs().hasAttribute<AccessControlAttr>() ||
isa<ProtocolDecl>(anyVar->getDeclContext());
auto diagID = diag::pattern_type_access;
if (downgradeToWarning == DowngradeToWarning::Yes)
diagID = diag::pattern_type_access_warn;
auto anyVarAccess =
isExplicit ? anyVar->getFormalAccess()
: typeAccessScope.requiredAccessForDiagnostics();
auto &DE = anyVar->getASTContext().Diags;
auto diag = DE.diagnose(
TP->getLoc(), diagID, anyVar->isLet(), isTypeContext, isExplicit,
anyVarAccess, isa<FileUnit>(anyVar->getDeclContext()), typeAccess);
highlightOffendingType(diag, complainRepr);
noteLimitingImport(anyVar, importLimit, complainRepr);
});
// Check the property wrapper types.
for (auto attr : anyVar->getAttachedPropertyWrappers()) {
checkTypeAccess(attr->getType(), attr->getTypeRepr(), anyVar,
/*mayBeInferred=*/false,
[&](AccessScope typeAccessScope,
const TypeRepr *complainRepr,
DowngradeToWarning downgradeToWarning,
ImportAccessLevel importLimit) {
auto typeAccess = typeAccessScope.accessLevelForDiagnostics();
bool isExplicit =
anyVar->getAttrs().hasAttribute<AccessControlAttr>() ||
isa<ProtocolDecl>(anyVar->getDeclContext());
auto anyVarAccess =
isExplicit ? anyVar->getFormalAccess()
: typeAccessScope.requiredAccessForDiagnostics();
auto diag = anyVar->diagnose(diag::property_wrapper_type_access,
anyVar->isLet(),
isTypeContext,
isExplicit,
anyVarAccess,
isa<FileUnit>(anyVar->getDeclContext()),
typeAccess);
highlightOffendingType(diag, complainRepr);
noteLimitingImport(anyVar, importLimit, complainRepr);
});
}
}
void visitPatternBindingDecl(PatternBindingDecl *PBD) {
bool isTypeContext = PBD->getDeclContext()->isTypeContext();
llvm::DenseSet<const VarDecl *> seenVars;
for (auto idx : range(PBD->getNumPatternEntries())) {
PBD->getPattern(idx)->forEachNode([&](const Pattern *P) {
if (auto *NP = dyn_cast<NamedPattern>(P)) {
// Only check individual variables if we didn't check an enclosing
// TypedPattern.
checkNamedPattern(NP, isTypeContext, seenVars);
return;
}
auto *TP = dyn_cast<TypedPattern>(P);
if (!TP)
return;
checkTypedPattern(TP, isTypeContext, seenVars);
});
seenVars.clear();
}
}
void visitTypeAliasDecl(TypeAliasDecl *TAD) {
checkGenericParamAccess(TAD, TAD);
checkTypeAccess(TAD->getUnderlyingType(),
TAD->getUnderlyingTypeRepr(), TAD, /*mayBeInferred*/false,
[&](AccessScope typeAccessScope,
const TypeRepr *complainRepr,
DowngradeToWarning downgradeToWarning,
ImportAccessLevel importLimit) {
auto typeAccess = typeAccessScope.accessLevelForDiagnostics();
bool isExplicit =
TAD->getAttrs().hasAttribute<AccessControlAttr>() ||
isa<ProtocolDecl>(TAD->getDeclContext());
auto diagID = diag::type_alias_underlying_type_access;
if (downgradeToWarning == DowngradeToWarning::Yes)
diagID = diag::type_alias_underlying_type_access_warn;
auto aliasAccess = isExplicit
? TAD->getFormalAccess()
: typeAccessScope.requiredAccessForDiagnostics();
auto diag = TAD->diagnose(diagID, isExplicit, aliasAccess, typeAccess,
isa<FileUnit>(TAD->getDeclContext()));
highlightOffendingType(diag, complainRepr);
noteLimitingImport(TAD, importLimit, complainRepr);
});
}
void visitOpaqueTypeDecl(OpaqueTypeDecl *OTD) {
// TODO(opaque): The constraint class/protocols on the opaque interface, as
// well as the naming decl for the opaque type, need to be accessible.
}
void visitAssociatedTypeDecl(AssociatedTypeDecl *assocType) {
// This must stay in sync with diag::associated_type_access.
enum {
ACEK_DefaultDefinition = 0,
ACEK_Requirement
} accessControlErrorKind;
auto minAccessScope = AccessScope::getPublic();
const TypeRepr *complainRepr = nullptr;
auto downgradeToWarning = DowngradeToWarning::No;
ImportAccessLevel minImportLimit = std::nullopt;
for (TypeLoc requirement : assocType->getInherited().getEntries()) {
checkTypeAccess(requirement, assocType, /*mayBeInferred*/false,
[&](AccessScope typeAccessScope,
const TypeRepr *thisComplainRepr,
DowngradeToWarning downgradeDiag,
ImportAccessLevel importLimit) {
if (typeAccessScope.isChildOf(minAccessScope) ||
(!complainRepr &&
typeAccessScope.hasEqualDeclContextWith(minAccessScope))) {
minAccessScope = typeAccessScope;
complainRepr = thisComplainRepr;
accessControlErrorKind = ACEK_Requirement;
downgradeToWarning = downgradeDiag;
minImportLimit = importLimit;
}
});
}
checkTypeAccess(assocType->getDefaultDefinitionType(),
assocType->getDefaultDefinitionTypeRepr(), assocType,
/*mayBeInferred*/false,
[&](AccessScope typeAccessScope,
const TypeRepr *thisComplainRepr,
DowngradeToWarning downgradeDiag,
ImportAccessLevel importLimit) {
if (typeAccessScope.isChildOf(minAccessScope) ||
(!complainRepr &&
typeAccessScope.hasEqualDeclContextWith(minAccessScope))) {
minAccessScope = typeAccessScope;
complainRepr = thisComplainRepr;
accessControlErrorKind = ACEK_DefaultDefinition;
downgradeToWarning = downgradeDiag;
minImportLimit = importLimit;
}
});
checkRequirementAccess(assocType,
assocType->getFormalAccessScope(),
assocType->getDeclContext(),
[&](AccessScope typeAccessScope,
const TypeRepr *thisComplainRepr,
DowngradeToWarning downgradeDiag,
ImportAccessLevel importLimit) {
if (typeAccessScope.isChildOf(minAccessScope) ||
(!complainRepr &&
typeAccessScope.hasEqualDeclContextWith(minAccessScope))) {
minAccessScope = typeAccessScope;
complainRepr = thisComplainRepr;
accessControlErrorKind = ACEK_Requirement;
downgradeToWarning = downgradeDiag;
minImportLimit = importLimit;
// Swift versions before 5.0 did not check requirements on the
// protocol's where clause, so emit a warning.
if (!assocType->getASTContext().isSwiftVersionAtLeast(5))
downgradeToWarning = DowngradeToWarning::Yes;
}
});
if (!minAccessScope.isPublic()) {
auto minAccess = minAccessScope.accessLevelForDiagnostics();
auto diagID = diag::associated_type_access;
if (downgradeToWarning == DowngradeToWarning::Yes)
diagID = diag::associated_type_access_warn;
auto diag = assocType->diagnose(diagID, assocType->getFormalAccess(),
minAccess, accessControlErrorKind);
highlightOffendingType(diag, complainRepr);
noteLimitingImport(assocType, minImportLimit, complainRepr);
}
}
void visitEnumDecl(EnumDecl *ED) {
checkGenericParamAccess(ED, ED);
if (ED->hasRawType()) {
Type rawType = ED->getRawType();
auto inheritedEntries = ED->getInherited().getEntries();
auto rawTypeLocIter = std::find_if(inheritedEntries.begin(),
inheritedEntries.end(),
[&](TypeLoc inherited) {
if (!inherited.wasValidated())
return false;
return inherited.getType().getPointer() == rawType.getPointer();
});
if (rawTypeLocIter == inheritedEntries.end())
return;
checkTypeAccess(rawType, rawTypeLocIter->getTypeRepr(), ED,
/*mayBeInferred*/false,
[&](AccessScope typeAccessScope,
const TypeRepr *complainRepr,
DowngradeToWarning downgradeToWarning,
ImportAccessLevel importLimit) {
auto typeAccess = typeAccessScope.accessLevelForDiagnostics();
bool isExplicit = ED->getAttrs().hasAttribute<AccessControlAttr>();
auto diagID = diag::enum_raw_type_access;
if (downgradeToWarning == DowngradeToWarning::Yes)
diagID = diag::enum_raw_type_access_warn;
auto enumDeclAccess = isExplicit
? ED->getFormalAccess()
: typeAccessScope.requiredAccessForDiagnostics();
auto diag = ED->diagnose(diagID, isExplicit, enumDeclAccess, typeAccess,
isa<FileUnit>(ED->getDeclContext()));
highlightOffendingType(diag, complainRepr);
noteLimitingImport(ED, importLimit, complainRepr);
});
}
}
void visitStructDecl(StructDecl *SD) {
checkGenericParamAccess(SD, SD);
}
void visitClassDecl(ClassDecl *CD) {
checkGenericParamAccess(CD, CD);
if (const NominalTypeDecl *superclassDecl = CD->getSuperclassDecl()) {
// Be slightly defensive here in the presence of badly-ordered
// inheritance clauses.
auto inheritedEntries = CD->getInherited().getEntries();
auto superclassLocIter = std::find_if(inheritedEntries.begin(),
inheritedEntries.end(),
[&](TypeLoc inherited) {
if (!inherited.wasValidated())
return false;
Type ty = inherited.getType();
if (ty->is<ProtocolCompositionType>())
if (auto superclass = ty->getExistentialLayout().explicitSuperclass)
ty = superclass;
return ty->getAnyNominal() == superclassDecl;
});
// Soundness check: we couldn't find the superclass for whatever reason
// (possibly because it's synthetic or something), so don't bother
// checking it.
if (superclassLocIter == inheritedEntries.end())
return;
auto outerDowngradeToWarning = DowngradeToWarning::No;
if (superclassDecl->isGenericContext() &&
!CD->getASTContext().isSwiftVersionAtLeast(5)) {
// Swift 4 failed to properly check this if the superclass was generic,
// because the above loop was too strict.
outerDowngradeToWarning = DowngradeToWarning::Yes;
}
checkTypeAccess(CD->getSuperclass(), superclassLocIter->getTypeRepr(), CD,
/*mayBeInferred*/false,
[&](AccessScope typeAccessScope,
const TypeRepr *complainRepr,
DowngradeToWarning downgradeToWarning,
ImportAccessLevel importLimit) {
auto typeAccess = typeAccessScope.accessLevelForDiagnostics();
bool isExplicit = CD->getAttrs().hasAttribute<AccessControlAttr>();
auto diagID = diag::class_super_access;
if (downgradeToWarning == DowngradeToWarning::Yes ||
outerDowngradeToWarning == DowngradeToWarning::Yes)
diagID = diag::class_super_access_warn;
auto classDeclAccess = isExplicit
? CD->getFormalAccess()
: typeAccessScope.requiredAccessForDiagnostics();
auto diag =
CD->diagnose(diagID, isExplicit, classDeclAccess, typeAccess,
isa<FileUnit>(CD->getDeclContext()),
superclassLocIter->getTypeRepr() != complainRepr);
highlightOffendingType(diag, complainRepr);
noteLimitingImport(CD, importLimit, complainRepr);
});
}
}
void visitProtocolDecl(ProtocolDecl *proto) {
// This must stay in sync with diag::protocol_access.
enum {
PCEK_Refine = 0,
PCEK_Requirement
} protocolControlErrorKind;
auto minAccessScope = AccessScope::getPublic();
const TypeRepr *complainRepr = nullptr;
auto downgradeToWarning = DowngradeToWarning::No;
ImportAccessLevel minImportLimit = std::nullopt;
DescriptiveDeclKind declKind = DescriptiveDeclKind::Protocol;
// FIXME: Hack to ensure that we've computed the types involved here.
auto inheritedTypes = proto->getInherited();
for (auto i : inheritedTypes.getIndices()) {
(void)inheritedTypes.getResolvedType(i);
}
auto declKindForType = [](Type type) -> DescriptiveDeclKind {
// If this is an existential type, use the decl kind of
// its constraint type.
if (auto existential = type->getAs<ExistentialType>())
type = existential->getConstraintType();
if (isa<TypeAliasType>(type.getPointer()))
return DescriptiveDeclKind::TypeAlias;
else if (auto nominal = type->getAnyNominal())
return nominal->getDescriptiveKind();
else
return DescriptiveDeclKind::Type;
};
for (TypeLoc requirement : proto->getInherited().getEntries()) {
checkTypeAccess(requirement, proto, /*mayBeInferred*/false,