-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathASTVerifier.cpp
3908 lines (3377 loc) · 130 KB
/
ASTVerifier.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
//===--- Verifier.cpp - AST Invariant Verification ------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2018 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 a verifier of AST invariants.
//
//===----------------------------------------------------------------------===//
#include "swift/AST/ASTContext.h"
#include "swift/AST/ASTWalker.h"
#include "swift/AST/AccessScope.h"
#include "swift/AST/AvailabilityScope.h"
#include "swift/AST/Decl.h"
#include "swift/AST/Effects.h"
#include "swift/AST/ExistentialLayout.h"
#include "swift/AST/Expr.h"
#include "swift/AST/ForeignAsyncConvention.h"
#include "swift/AST/ForeignErrorConvention.h"
#include "swift/AST/GenericEnvironment.h"
#include "swift/AST/GenericSignature.h"
#include "swift/AST/Initializer.h"
#include "swift/AST/MacroDiscriminatorContext.h"
#include "swift/AST/Module.h"
#include "swift/AST/NameLookup.h"
#include "swift/AST/ParameterList.h"
#include "swift/AST/Pattern.h"
#include "swift/AST/PrettyStackTrace.h"
#include "swift/AST/ProtocolConformance.h"
#include "swift/AST/SourceFile.h"
#include "swift/AST/Stmt.h"
#include "swift/AST/TypeCheckRequests.h"
#include "swift/AST/TypeRepr.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Subsystems.h"
#include "llvm/ADT/SmallBitVector.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <functional>
#include <type_traits>
using namespace swift;
namespace {
template<typename T>
struct ASTNodeBase {};
#define EXPR(ID, PARENT) \
template<> \
struct ASTNodeBase<ID ## Expr *> { \
typedef PARENT BaseTy; \
};
#define ABSTRACT_EXPR(ID, PARENT) EXPR(ID, PARENT)
#include "swift/AST/ExprNodes.def"
#define STMT(ID, PARENT) \
template<> \
struct ASTNodeBase<ID ## Stmt *> { \
typedef PARENT BaseTy; \
};
#include "swift/AST/StmtNodes.def"
#define DECL(ID, PARENT) \
template<> \
struct ASTNodeBase<ID ## Decl *> { \
typedef PARENT BaseTy; \
};
#define ABSTRACT_DECL(ID, PARENT) DECL(ID, PARENT)
#include "swift/AST/DeclNodes.def"
#define PATTERN(ID, PARENT) \
template<> \
struct ASTNodeBase<ID ## Pattern *> { \
typedef PARENT BaseTy; \
};
#include "swift/AST/PatternNodes.def"
template <typename Ty>
struct is_apply_expr
: public std::integral_constant<
bool,
std::is_same<Ty, CallExpr>::value ||
std::is_same<Ty, PrefixUnaryExpr>::value ||
std::is_same<Ty, PostfixUnaryExpr>::value ||
std::is_same<Ty, BinaryExpr>::value ||
std::is_same<Ty, DotSyntaxCallExpr>::value ||
std::is_same<Ty, ConstructorRefCallExpr>::value> {};
template <typename Ty>
struct is_subscript_expr
: public std::integral_constant<
bool, std::is_same<Ty, SubscriptExpr>::value ||
std::is_same<Ty, DynamicSubscriptExpr>::value> {};
template <typename Ty>
struct is_autoclosure_expr
: public std::integral_constant<bool,
std::is_same<Ty, AutoClosureExpr>::value> {
};
template <typename Ty>
struct is_apply_subscript_or_autoclosure_expr
: public std::integral_constant<bool, is_apply_expr<Ty>::value ||
is_subscript_expr<Ty>::value ||
is_autoclosure_expr<Ty>::value> {
};
template <typename Verifier, typename Kind>
ASTWalker::PreWalkResult<Expr *> dispatchVisitPreExprHelper(
Verifier &V,
typename std::enable_if<
is_apply_expr<typename std::remove_pointer<Kind>::type>::value,
Kind>::type node) {
if (V.shouldVerify(node)) {
// Record any inout_to_pointer or array_to_pointer that we see in
// the proper position.
V.maybeRecordValidPointerConversion(node->getArgs());
return ASTWalker::Action::Continue(node);
}
V.cleanup(node);
return ASTWalker::Action::SkipNode(node);
}
template <typename Verifier, typename Kind>
ASTWalker::PreWalkResult<Expr *> dispatchVisitPreExprHelper(
Verifier &V,
typename std::enable_if<
is_subscript_expr<typename std::remove_pointer<Kind>::type>::value,
Kind>::type node) {
if (V.shouldVerify(node)) {
// Record any inout_to_pointer or array_to_pointer that we see in
// the proper position.
V.maybeRecordValidPointerConversion(node->getArgs());
return ASTWalker::Action::Continue(node);
}
V.cleanup(node);
return ASTWalker::Action::SkipNode(node);
}
template <typename Verifier, typename Kind>
ASTWalker::PreWalkResult<Expr *> dispatchVisitPreExprHelper(
Verifier &V,
typename std::enable_if<
is_autoclosure_expr<typename std::remove_pointer<Kind>::type>::value,
Kind>::type node) {
if (V.shouldVerify(node)) {
// Record any inout_to_pointer or array_to_pointer that we see in
// the proper position.
V.maybeRecordValidPointerConversionForArg(node->getSingleExpressionBody());
return ASTWalker::Action::Continue(node);
}
V.cleanup(node);
return ASTWalker::Action::SkipNode(node);
}
template <typename Verifier, typename Kind>
ASTWalker::PreWalkResult<Expr *> dispatchVisitPreExprHelper(
Verifier &V, typename std::enable_if<
!is_apply_subscript_or_autoclosure_expr<
typename std::remove_pointer<Kind>::type>::value,
Kind>::type node) {
if (V.shouldVerify(node)) {
return ASTWalker::Action::Continue(node);
}
V.cleanup(node);
return ASTWalker::Action::SkipNode(node);
}
namespace {
// Retrieve the "overridden" declaration of this declaration, but only if
// it's already been computed.
template <typename T> T *getOverriddenDeclIfAvailable(T *decl) {
if (!decl->overriddenDeclsComputed())
return nullptr;
return cast_or_null<T>(decl->getOverriddenDecl());
}
} // namespace
class Verifier : public ASTWalker {
PointerUnion<ModuleDecl *, SourceFile *> M;
ASTContext &Ctx;
llvm::raw_ostream &Out;
const bool HadError;
SmallVector<bool, 8> InImplicitBraceStmt;
/// The stack of functions we're visiting.
SmallVector<DeclContext *, 4> Functions;
/// The stack of scopes we're visiting.
using ScopeLike = llvm::PointerUnion<DeclContext *, BraceStmt *>;
SmallVector<ScopeLike, 4> Scopes;
/// The stack of declaration contexts we're visiting. The primary
/// archetypes from the innermost generic environment are in scope.
SmallVector<DeclContext *, 2> Generics;
/// The set of all opened existential and opened pack element generic
/// environments that are currently in scope.
llvm::DenseSet<GenericEnvironment *> LocalGenerics;
/// We track the pack expansion expressions in ForEachStmts, because
/// their local generics remain in scope until the end of the statement.
llvm::DenseSet<PackExpansionExpr *> ForEachPatternSequences;
/// The stack of optional evaluations active at this point.
SmallVector<OptionalEvaluationExpr *, 4> OptionalEvaluations;
/// The set of opaque value expressions active at this point.
llvm::DenseMap<OpaqueValueExpr *, unsigned> OpaqueValues;
/// The set of inout to pointer expr that match the following pattern:
///
/// (call-expr
/// (brace-stmt
/// ... maybe other arguments ...
/// (inject_into_optional
/// (inout_to_pointer ...))
/// ... maybe other arguments ...))
///
/// Any other inout to pointer expr that we see is invalid and the verifier
/// will assert.
llvm::DenseSet<InOutToPointerExpr *> ValidInOutToPointerExprs;
llvm::DenseSet<ArrayToPointerExpr *> ValidArrayToPointerExprs;
/// A key into ClosureDiscriminators is a combination of a
/// ("canonicalized") local DeclContext* and a flag for whether to
/// use the explicit closure sequence (false) or the implicit
/// closure sequence (true).
typedef llvm::PointerIntPair<DeclContext *, 1, bool> ClosureDiscriminatorKey;
llvm::DenseMap<ClosureDiscriminatorKey, SmallBitVector>
ClosureDiscriminators;
DeclContext *CanonicalTopLevelSubcontext = nullptr;
typedef std::pair</*MacroDiscriminatorContext*/const void *, Identifier>
MacroExpansionDiscriminatorKey;
llvm::DenseMap<MacroExpansionDiscriminatorKey, SmallBitVector>
MacroExpansionDiscriminators;
Verifier(PointerUnion<ModuleDecl *, SourceFile *> M, DeclContext *DC)
: M(M),
Ctx(M.is<ModuleDecl *>() ? M.get<ModuleDecl *>()->getASTContext()
: M.get<SourceFile *>()->getASTContext()),
Out(llvm::errs()), HadError(Ctx.hadError()) {
pushScope(DC);
}
/// Emit an error message and abort, optionally dumping the expression.
/// \param E if non-null, the expression to dump() followed by a new-line.
void error(llvm::StringRef msg, Expr *E = nullptr) {
Out << msg << "\n";
if (E) {
E->dump(Out);
Out << "\n";
}
abort();
}
ModuleDecl *getModuleContext() const {
if (auto sourceFile = M.dyn_cast<SourceFile *>())
return sourceFile->getParentModule();
return M.get<ModuleDecl *>();
}
public:
Verifier(ModuleDecl *M, DeclContext *DC)
: Verifier(PointerUnion<ModuleDecl *, SourceFile *>(M), DC) {}
Verifier(SourceFile &SF, DeclContext *DC) : Verifier(&SF, DC) {}
static Verifier forDecl(const Decl *D) {
DeclContext *DC = D->getDeclContext();
DeclContext *topDC = DC->getModuleScopeContext();
if (auto SF = dyn_cast<SourceFile>(topDC))
return Verifier(*SF, DC);
return Verifier(topDC->getParentModule(), DC);
}
MacroWalking getMacroWalkingBehavior() const override {
return MacroWalking::None;
}
PreWalkResult<Expr *> walkToExprPre(Expr *E) override {
switch (E->getKind()) {
#define DISPATCH(ID) return dispatchVisitPreExpr(static_cast<ID##Expr*>(E))
#define EXPR(ID, PARENT) \
case ExprKind::ID: \
DISPATCH(ID);
#define UNCHECKED_EXPR(ID, PARENT) \
case ExprKind::ID: \
assert((HadError || !M.is<SourceFile*>() || \
M.get<SourceFile*>()->ASTStage < SourceFile::TypeChecked) && \
#ID "in wrong phase");\
DISPATCH(ID);
#include "swift/AST/ExprNodes.def"
#undef DISPATCH
}
llvm_unreachable("not all cases handled!");
}
PostWalkResult<Expr *> walkToExprPost(Expr *E) override {
switch (E->getKind()) {
#define DISPATCH(ID) return dispatchVisitPost(static_cast<ID##Expr*>(E))
#define EXPR(ID, PARENT) \
case ExprKind::ID: \
DISPATCH(ID);
#define UNCHECKED_EXPR(ID, PARENT) \
case ExprKind::ID: \
assert((HadError || !M.is<SourceFile*>() || \
M.get<SourceFile*>()->ASTStage < SourceFile::TypeChecked) && \
#ID "in wrong phase");\
DISPATCH(ID);
#include "swift/AST/ExprNodes.def"
#undef DISPATCH
}
llvm_unreachable("not all cases handled!");
}
PreWalkResult<Stmt *> walkToStmtPre(Stmt *S) override {
switch (S->getKind()) {
#define DISPATCH(ID) return dispatchVisitPreStmt(static_cast<ID##Stmt*>(S))
#define STMT(ID, PARENT) \
case StmtKind::ID: \
DISPATCH(ID);
#include "swift/AST/StmtNodes.def"
#undef DISPATCH
}
llvm_unreachable("not all cases handled!");
}
PostWalkResult<Stmt *> walkToStmtPost(Stmt *S) override {
switch (S->getKind()) {
#define DISPATCH(ID) return dispatchVisitPost(static_cast<ID##Stmt*>(S))
#define STMT(ID, PARENT) \
case StmtKind::ID: \
DISPATCH(ID);
#include "swift/AST/StmtNodes.def"
#undef DISPATCH
}
llvm_unreachable("not all cases handled!");
}
PreWalkResult<Pattern *> walkToPatternPre(Pattern *P) override {
switch (P->getKind()) {
#define DISPATCH(ID) \
return dispatchVisitPrePattern(static_cast<ID##Pattern*>(P))
#define PATTERN(ID, PARENT) \
case PatternKind::ID: \
DISPATCH(ID);
#include "swift/AST/PatternNodes.def"
#undef DISPATCH
}
llvm_unreachable("not all cases handled!");
}
PostWalkResult<Pattern *> walkToPatternPost(Pattern *P) override {
switch (P->getKind()) {
#define DISPATCH(ID) \
return dispatchVisitPost(static_cast<ID##Pattern*>(P))
#define PATTERN(ID, PARENT) \
case PatternKind::ID: \
DISPATCH(ID);
#include "swift/AST/PatternNodes.def"
#undef DISPATCH
}
llvm_unreachable("not all cases handled!");
}
PreWalkAction walkToDeclPre(Decl *D) override {
switch (D->getKind()) {
#define DISPATCH(ID) return dispatchVisitPre(static_cast<ID##Decl*>(D))
#define DECL(ID, PARENT) \
case DeclKind::ID: \
DISPATCH(ID);
#include "swift/AST/DeclNodes.def"
#undef DISPATCH
}
llvm_unreachable("not all cases handled!");
}
PostWalkAction walkToDeclPost(Decl *D) override {
switch (D->getKind()) {
#define DISPATCH(ID) return dispatchVisitPost(static_cast<ID##Decl*>(D)).Action
#define DECL(ID, PARENT) \
case DeclKind::ID: \
DISPATCH(ID);
#include "swift/AST/DeclNodes.def"
#undef DISPATCH
}
llvm_unreachable("Unhandled declaration kind");
}
/// Helper template for dispatching pre-visitation.
/// If we're visiting in pre-order, don't validate the node yet;
/// just check whether we should stop further descent.
template <class T> PreWalkAction dispatchVisitPre(T node) {
if (shouldVerify(node))
return Action::Continue();
cleanup(node);
return Action::SkipNode();
}
/// Helper template for dispatching pre-visitation.
///
/// If we're visiting in pre-order, don't validate the node yet;
/// just check whether we should stop further descent.
template <class T> PreWalkResult<Expr *> dispatchVisitPreExpr(T node) {
return dispatchVisitPreExprHelper<Verifier, T>(*this, node);
}
/// Helper template for dispatching pre-visitation.
/// If we're visiting in pre-order, don't validate the node yet;
/// just check whether we should stop further descent.
template <class T> PreWalkResult<Stmt *> dispatchVisitPreStmt(T node) {
if (shouldVerify(node))
return Action::Continue(node);
cleanup(node);
return Action::SkipNode(node);
}
/// Helper template for dispatching pre-visitation.
/// If we're visiting in pre-order, don't validate the node yet;
/// just check whether we should stop further descent.
template <class T>
PreWalkResult<Pattern *> dispatchVisitPrePattern(T node) {
if (shouldVerify(node))
return Action::Continue(node);
cleanup(node);
return Action::SkipNode(node);
}
/// Helper template for dispatching post-visitation.
template <class T> PostWalkResult<T> dispatchVisitPost(T node) {
// Verify source ranges if the AST node was parsed from source.
auto *SF = M.dyn_cast<SourceFile *>();
if (SF) {
// If we are inside an implicit BraceStmt, don't verify source
// locations. LLDB creates implicit BraceStmts which contain a mix of
// generated/user-written code.
if (InImplicitBraceStmt.empty() || !InImplicitBraceStmt.back())
checkSourceRanges(node);
}
// Check that nodes marked invalid have the correct type.
checkErrors(node);
// Always verify the node as a parsed node.
verifyParsed(node);
// If we've checked types already, do some extra verification.
if (!SF || SF->ASTStage >= SourceFile::TypeChecked) {
verifyCheckedAlways(node);
if (!HadError && shouldVerifyChecked(node))
verifyChecked(node);
}
// Clean up anything that we've placed into a stack to check.
cleanup(node);
// Always continue.
return Action::Continue(node);
}
// Default cases for whether we should verify within the given subtree.
bool shouldVerify(Expr *E) { return true; }
bool shouldVerify(Stmt *S) { return true; }
bool shouldVerify(Pattern *S) { return true; }
bool shouldVerify(Decl *S) { return true; }
bool shouldVerify(TypeAliasDecl *typealias) {
// Don't verify type aliases formed by the debugger; they violate some
// AST invariants involving archetypes.
if (typealias->isDebuggerAlias()) return false;
return true;
}
// Default cases for whether we should verify a checked subtree.
bool shouldVerifyChecked(Expr *E) {
if (!E->getType()) {
// For @objc enums, we serialize the pre-type-checked integer
// literal raw values, and thus when they are deserialized
// they do not have a type on them.
if (!isa<IntegerLiteralExpr>(E) && !isa<MacroExpansionExpr>(E)) {
Out << "expression has no type\n";
E->dump(Out);
abort();
}
}
return true;
}
bool shouldVerifyChecked(Stmt *S) { return true; }
bool shouldVerifyChecked(Pattern *S) { return true; }
bool shouldVerifyChecked(Decl *S) { return true; }
// Only verify functions if they have bodies we can safely walk.
// FIXME: This is a bit of a hack; we should be able to check the
// invariants of a parsed body as well.
bool shouldVerify(AbstractFunctionDecl *afd) {
switch (afd->getBodyKind()) {
case AbstractFunctionDecl::BodyKind::None:
case AbstractFunctionDecl::BodyKind::TypeChecked:
case AbstractFunctionDecl::BodyKind::SILSynthesize:
case AbstractFunctionDecl::BodyKind::Deserialized:
return true;
case AbstractFunctionDecl::BodyKind::Unparsed:
case AbstractFunctionDecl::BodyKind::Parsed:
case AbstractFunctionDecl::BodyKind::Synthesize:
if (auto SF = dyn_cast<SourceFile>(afd->getModuleScopeContext())) {
return SF->ASTStage < SourceFile::TypeChecked;
}
return false;
}
llvm_unreachable("unhandled kind");
}
// Default cases for cleaning up as we exit a node.
void cleanup(Expr *E) { }
void cleanup(Stmt *S) { }
void cleanup(Pattern *P) { }
void cleanup(Decl *D) { }
// Base cases for the various stages of verification.
void verifyParsed(Expr *E) {}
void verifyParsed(Stmt *S) {}
void verifyParsed(Pattern *P) {}
void verifyParsed(Decl *D) {
PrettyStackTraceDecl debugStack("verifying ", D);
if (!D->getDeclContext()) {
Out << "every Decl should have a DeclContext\n";
abort();
}
if (auto *DC = dyn_cast<DeclContext>(D)) {
if (D->getDeclContext() != DC->getParent()) {
Out << "Decl's DeclContext not in sync with DeclContext's parent\n";
D->getDeclContext()->printContext(Out);
DC->getParent()->printContext(Out);
abort();
}
}
}
template<typename T>
void verifyParsedBase(T ASTNode) {
verifyParsed(cast<typename ASTNodeBase<T>::BaseTy>(ASTNode));
}
/// @{
/// These verification functions are always run on type checked ASTs
/// (even if there were errors).
void verifyCheckedAlways(Expr *E) {
if (E->getType())
verifyChecked(E->getType());
}
void verifyCheckedAlways(Stmt *S) {}
void verifyCheckedAlways(Pattern *P) {
if (P->hasType() && !P->getDelayedInterfaceType())
verifyChecked(P->getType());
}
void verifyCheckedAlways(Decl *D) {
}
template<typename T>
void verifyCheckedAlwaysBase(T ASTNode) {
verifyCheckedAlways(cast<typename ASTNodeBase<T>::BaseTy>(ASTNode));
}
/// @}
/// @{
/// These verification functions are run on type checked ASTs if there were
/// no errors.
void verifyChecked(Expr *E) {
// Some imported expressions don't have types, even in checked mode.
// TODO: eliminate all these
if (!E->getType()) {
// For @objc enums, we serialize the pre-type-checked integer
// literal raw values, and thus when they are deserialized
// they do not have a type on them.
if (!isa<IntegerLiteralExpr>(E)) {
Out << "expression has no type\n";
E->dump(Out);
abort();
}
return;
}
}
void verifyChecked(Pattern *P) {
if (!P->hasType()) {
Out << "pattern has no type\n";
P->dump(Out);
abort();
}
}
void verifyChecked(Stmt *S) {}
void verifyChecked(Decl *D) {}
void verifyChecked(Type type) {
llvm::SmallPtrSet<ArchetypeType *, 4> visitedArchetypes;
verifyChecked(type, visitedArchetypes);
}
void
verifyChecked(Type type,
llvm::SmallPtrSetImpl<ArchetypeType *> &visitedArchetypes) {
if (!type)
return;
// Check for type variables that escaped the type checker.
if (type->hasTypeVariable()) {
Out << "a type variable escaped the type checker\n";
abort();
}
// Check for invalid pack expansion shape types.
if (auto *expansion = type->getAs<PackExpansionType>()) {
auto countType = expansion->getCountType();
if (!(countType->is<PackType>() ||
countType->is<PackArchetypeType>() ||
countType->isRootParameterPack())) {
Out << "non-pack shape type: " << countType->getString() << "\n";
abort();
}
}
if (!type->hasArchetype())
return;
bool foundError = type->getCanonicalType().findIf([&](Type type) -> bool {
if (auto archetype = type->getAs<ArchetypeType>()) {
// Opaque archetypes are globally available. We don't need to check
// them here.
if (isa<OpaqueTypeArchetypeType>(archetype))
return false;
// Only visit each archetype once.
if (!visitedArchetypes.insert(archetype).second)
return false;
// We should know about archetypes corresponding to opened
// existential archetypes.
if (isa<LocalArchetypeType>(archetype)) {
if (LocalGenerics.count(archetype->getGenericEnvironment()) == 0) {
Out << "Found local archetype " << archetype
<< " outside its defining scope\n";
return true;
}
return false;
}
// Otherwise, the archetype needs to be from this scope.
if (Generics.empty() || !Generics.back()) {
Out << "AST verification error: archetype outside of generic "
"context: " << archetype << "\n";
return true;
}
// Get the archetype's generic signature.
GenericEnvironment *archetypeEnv = archetype->getGenericEnvironment();
auto archetypeSig = archetypeEnv->getGenericSignature();
auto genericCtx = Generics.back();
GenericSignature genericSig = genericCtx->getGenericSignatureOfContext();
if (genericSig.getPointer() != archetypeSig.getPointer()) {
Out << "Archetype " << archetype->getString() << " not allowed "
<< "in this context\n";
Out << "Archetype generic signature: "
<< archetypeSig->getAsString() << "\n";
Out << "Context generic signature: "
<< genericSig->getAsString() << "\n";
return true;
}
// Mapping the archetype out and back in should produce the
// same archetype.
auto interfaceType = archetype->getInterfaceType();
auto contextType = archetypeEnv->mapTypeIntoContext(interfaceType);
if (!contextType->isEqual(archetype)) {
Out << "Archetype " << archetype->getString() << " does not appear"
<< " inside its own generic environment\n";
Out << "Interface type: " << interfaceType.getString() << "\n";
Out << "Contextual type: " << contextType.getString() << "\n";
return true;
}
}
return false;
});
if (foundError)
abort();
}
template<typename T>
void verifyCheckedBase(T ASTNode) {
verifyChecked(cast<typename ASTNodeBase<T>::BaseTy>(ASTNode));
}
/// @}
// Specialized verifiers.
void pushScope(DeclContext *scope) {
Scopes.push_back(scope);
Generics.push_back(scope);
}
void pushScope(BraceStmt *scope) {
Scopes.push_back(scope);
}
void popScope(DeclContext *scope) {
assert(Scopes.back().get<DeclContext*>() == scope);
assert(Generics.back() == scope);
Scopes.pop_back();
Generics.pop_back();
}
void popScope(BraceStmt *scope) {
assert(Scopes.back().get<BraceStmt*>() == scope);
Scopes.pop_back();
}
void pushFunction(DeclContext *functionScope) {
pushScope(functionScope);
Functions.push_back(functionScope);
}
void popFunction(DeclContext *functionScope) {
assert(Functions.back() == functionScope);
Functions.pop_back();
popScope(functionScope);
}
#define FUNCTION_LIKE(NODE) \
bool shouldVerify(NODE *fn) { \
pushFunction(fn); \
return shouldVerify(cast<ASTNodeBase<NODE*>::BaseTy>(fn));\
} \
void cleanup(NODE *fn) { \
popFunction(fn); \
}
#define TYPE_LIKE(NODE) \
bool shouldVerify(NODE *dc) { \
pushScope(dc); \
if (dc->hasLazyMembers()) \
return false; \
if (dc->hasUnparsedMembers()) \
return false; \
return shouldVerify(cast<ASTNodeBase<NODE*>::BaseTy>(dc));\
} \
void cleanup(NODE *dc) { \
popScope(dc); \
}
FUNCTION_LIKE(AbstractClosureExpr)
FUNCTION_LIKE(ConstructorDecl)
FUNCTION_LIKE(DestructorDecl)
FUNCTION_LIKE(FuncDecl)
FUNCTION_LIKE(EnumElementDecl)
FUNCTION_LIKE(SubscriptDecl)
FUNCTION_LIKE(MacroDecl)
TYPE_LIKE(NominalTypeDecl)
TYPE_LIKE(ExtensionDecl)
#undef TYPE_LIKE
#undef FUNCTION_LIKE
bool shouldVerify(BraceStmt *BS) {
pushScope(BS);
InImplicitBraceStmt.push_back(BS->isImplicit());
return shouldVerify(cast<Stmt>(BS));
}
void cleanup(BraceStmt *BS) {
InImplicitBraceStmt.pop_back();
popScope(BS);
}
bool shouldVerify(ForEachStmt *S) {
if (!shouldVerify(cast<Stmt>(S)))
return false;
if (auto *expansion =
dyn_cast<PackExpansionExpr>(S->getParsedSequence())) {
if (!shouldVerify(expansion)) {
return false;
}
assert(ForEachPatternSequences.count(expansion) == 0);
ForEachPatternSequences.insert(expansion);
}
if (!S->getElementExpr())
return true;
assert(!OpaqueValues.count(S->getElementExpr()));
OpaqueValues[S->getElementExpr()] = 0;
return true;
}
void cleanup(ForEachStmt *S) {
if (auto *expansion =
dyn_cast<PackExpansionExpr>(S->getParsedSequence())) {
assert(ForEachPatternSequences.count(expansion) != 0);
ForEachPatternSequences.erase(expansion);
// Clean up for real.
cleanup(expansion);
}
if (!S->getElementExpr())
return;
assert(OpaqueValues.count(S->getElementExpr()));
OpaqueValues.erase(S->getElementExpr());
}
bool shouldVerify(InterpolatedStringLiteralExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
if (!expr->getInterpolationExpr())
return true;
assert(!OpaqueValues.count(expr->getInterpolationExpr()));
OpaqueValues[expr->getInterpolationExpr()] = 0;
return true;
}
void cleanup(InterpolatedStringLiteralExpr *expr) {
if (!expr->getInterpolationExpr())
return;
assert(OpaqueValues.count(expr->getInterpolationExpr()));
OpaqueValues.erase(expr->getInterpolationExpr());
}
bool shouldVerify(PropertyWrapperValuePlaceholderExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
assert(expr->getOpaqueValuePlaceholder());
assert(!OpaqueValues.count(expr->getOpaqueValuePlaceholder()));
OpaqueValues[expr->getOpaqueValuePlaceholder()] = 0;
return true;
}
void cleanup(PropertyWrapperValuePlaceholderExpr *expr) {
assert(OpaqueValues.count(expr->getOpaqueValuePlaceholder()));
OpaqueValues.erase(expr->getOpaqueValuePlaceholder());
}
void pushLocalGenerics(GenericEnvironment *env) {
assert(LocalGenerics.count(env)==0);
LocalGenerics.insert(env);
}
void popLocalGenerics(GenericEnvironment *env) {
assert(LocalGenerics.count(env)==1);
LocalGenerics.erase(env);
}
bool shouldVerify(OpenExistentialExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
// In rare instances we clear the opaque value because we no
// longer have a subexpression that references it.
if (!expr->getOpaqueValue())
return true;
assert(!OpaqueValues.count(expr->getOpaqueValue()));
OpaqueValues[expr->getOpaqueValue()] = 0;
pushLocalGenerics(expr->getOpenedArchetype()->getGenericEnvironment());
return true;
}
void cleanup(OpenExistentialExpr *expr) {
// In rare instances we clear the opaque value because we no
// longer have a subexpression that references it.
if (!expr->getOpaqueValue())
return;
assert(OpaqueValues.count(expr->getOpaqueValue()));
OpaqueValues.erase(expr->getOpaqueValue());
popLocalGenerics(expr->getOpenedArchetype()->getGenericEnvironment());
}
bool shouldVerify(PackExpansionExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
// Don't push local generics again when we visit the expr inside
// the ForEachStmt.
if (auto *genericEnv = expr->getGenericEnvironment())
if (ForEachPatternSequences.count(expr) == 0)
pushLocalGenerics(genericEnv);
return true;
}
void cleanup(PackExpansionExpr *expr) {
// If this is a pack iteration pattern, don't pop local generics
// until we exit the ForEachStmt.
if (auto *genericEnv = expr->getGenericEnvironment())
if (ForEachPatternSequences.count(expr) == 0)
popLocalGenerics(genericEnv);
}
bool shouldVerify(MakeTemporarilyEscapableExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
assert(!OpaqueValues.count(expr->getOpaqueValue()));
OpaqueValues[expr->getOpaqueValue()] = 0;
return true;
}
void cleanup(MakeTemporarilyEscapableExpr *expr) {
assert(OpaqueValues.count(expr->getOpaqueValue()));
OpaqueValues.erase(expr->getOpaqueValue());
}
// Register the OVEs in a DestructureTupleExpr.
bool shouldVerify(DestructureTupleExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
for (auto *opaqueElt : expr->getDestructuredElements()) {
assert(!OpaqueValues.count(opaqueElt));
OpaqueValues[opaqueElt] = 0;
}
return true;
}
void cleanup(DestructureTupleExpr *expr) {
for (auto *opaqueElt : expr->getDestructuredElements()) {
assert(OpaqueValues.count(opaqueElt));
OpaqueValues.erase(opaqueElt);
}
}
// Keep a stack of the currently-live optional evaluations.
bool shouldVerify(OptionalEvaluationExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
OptionalEvaluations.push_back(expr);
return true;
}
void cleanup(OptionalEvaluationExpr *expr) {
assert(OptionalEvaluations.back() == expr);
OptionalEvaluations.pop_back();
}
// Register the OVEs in a collection upcast.
bool shouldVerify(CollectionUpcastConversionExpr *expr) {
if (!shouldVerify(cast<Expr>(expr)))
return false;
if (auto keyConversion = expr->getKeyConversion())
OpaqueValues[keyConversion.OrigValue] = 0;
if (auto valueConversion = expr->getValueConversion())
OpaqueValues[valueConversion.OrigValue] = 0;
return true;
}
void cleanup(CollectionUpcastConversionExpr *expr) {
if (auto keyConversion = expr->getKeyConversion())
OpaqueValues.erase(keyConversion.OrigValue);
if (auto valueConversion = expr->getValueConversion())
OpaqueValues.erase(valueConversion.OrigValue);
}
/// Canonicalize the given DeclContext pointer, in terms of
/// producing something that can be looked up in
/// ClosureDiscriminators.
DeclContext *getCanonicalDeclContext(DeclContext *DC) {
// All we really need to do is use a single TopLevelCodeDecl.
if (auto topLevel = dyn_cast<TopLevelCodeDecl>(DC)) {
if (!CanonicalTopLevelSubcontext)
CanonicalTopLevelSubcontext = topLevel;
return CanonicalTopLevelSubcontext;
}
// TODO: check for uniqueness of initializer contexts?