forked from swiftlang/swift
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTypeCheckSwitchStmt.cpp
1611 lines (1443 loc) · 59.8 KB
/
TypeCheckSwitchStmt.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
//===--- TypeCheckSwitchStmt.cpp - Switch Exhaustiveness and Type Checks --===//
//
// 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 contains an algorithm for checking the exhaustiveness of switches.
//
//===----------------------------------------------------------------------===//
#include "TypeChecker.h"
#include "swift/AST/ASTPrinter.h"
#include "swift/AST/DiagnosticsSema.h"
#include "swift/AST/Pattern.h"
#include <llvm/ADT/APInt.h>
#include <llvm/ADT/APFloat.h>
#include <numeric>
#include <forward_list>
using namespace swift;
#define DEBUG_TYPE "TypeCheckSwitchStmt"
namespace {
struct DenseMapAPIntKeyInfo {
static inline APInt getEmptyKey() { return APInt(); }
static inline APInt getTombstoneKey() {
return APInt::getAllOnesValue(/*bitwidth*/1);
}
static unsigned getHashValue(const APInt &Key) {
return static_cast<unsigned>(hash_value(Key));
}
static bool isEqual(const APInt &LHS, const APInt &RHS) {
return LHS.getBitWidth() == RHS.getBitWidth() && LHS == RHS;
}
};
struct DenseMapAPFloatKeyInfo {
static inline APFloat getEmptyKey() { return APFloat(APFloat::Bogus(), 1); }
static inline APFloat getTombstoneKey() { return APFloat(APFloat::Bogus(), 2); }
static unsigned getHashValue(const APFloat &Key) {
return static_cast<unsigned>(hash_value(Key));
}
static bool isEqual(const APFloat &LHS, const APFloat &RHS) {
return LHS.bitwiseIsEqual(RHS);
}
};
}
namespace {
/// The SpaceEngine encapsulates an algorithm for computing the exhaustiveness
/// of a switch statement using an algebra of spaces described by Fengyun Liu
/// and an algorithm for computing warnings for pattern matching by
/// Luc Maranget.
///
/// The main algorithm centers around the computation of the difference and
/// the containment of the "Spaces" given in each case, which reduces the
/// definition of exhaustiveness to checking if the difference of the space
/// 'S' of the user's written patterns and the space 'T' of the pattern
/// condition is empty.
struct SpaceEngine {
enum class SpaceKind : uint8_t {
Empty,
Type,
Constructor,
Disjunct,
BooleanConstant,
UnknownCase,
};
// The order of cases is used for disjunctions: a disjunction's
// DowngradeToWarning condition is the std::min of its spaces'.
enum class DowngradeToWarning {
No,
ForUnknownCase,
LAST = ForUnknownCase
};
enum UnknownCase_t {
UnknownCase
};
/// A data structure for conveniently pattern-matching on the kinds of
/// two spaces.
struct PairSwitch {
public:
constexpr PairSwitch(SpaceKind pair1, SpaceKind pair2)
: Data(static_cast<uint8_t>(pair1) | (static_cast<uint8_t>(pair2) << 8))
{}
constexpr bool operator==(const PairSwitch other) const {
return Data == other.Data;
}
constexpr operator int() const {
return Data;
}
private:
uint16_t Data;
PairSwitch (const PairSwitch&) = delete;
PairSwitch& operator= (const PairSwitch&) = delete;
};
#define PAIRCASE(XS, YS) case PairSwitch(XS, YS)
class Space final : public RelationalOperationsBase<Space> {
private:
SpaceKind Kind;
llvm::PointerIntPair<Type, 1, bool> TypeAndVal;
// In type space, we reuse HEAD to help us print meaningful name, e.g.,
// tuple element name in fixits.
Identifier Head;
std::forward_list<Space> Spaces;
// NB: This constant is arbitrary. Anecdotally, the Space Engine is
// capable of efficiently handling Spaces of around size 200, but it would
// potentially push an enormous fixit on the user.
static const size_t MAX_SPACE_SIZE = 128;
size_t computeSize(TypeChecker &TC, const DeclContext *DC,
SmallPtrSetImpl<TypeBase *> &cache) const {
switch (getKind()) {
case SpaceKind::Empty:
return 0;
case SpaceKind::BooleanConstant:
return 1;
case SpaceKind::UnknownCase:
return isAllowedButNotRequired() ? 0 : 1;
case SpaceKind::Type: {
if (!canDecompose(getType(), DC)) {
return 1;
}
cache.insert(getType().getPointer());
SmallVector<Space, 4> spaces;
decompose(TC, DC, getType(), spaces);
size_t acc = 0;
for (auto &sp : spaces) {
// Decomposed pattern spaces grow with the sum of the subspaces.
acc += sp.computeSize(TC, DC, cache);
}
cache.erase(getType().getPointer());
return acc;
}
case SpaceKind::Constructor: {
size_t acc = 1;
for (auto &sp : getSpaces()) {
// Break self-recursive references among enum arguments.
if (sp.getKind() == SpaceKind::Type
&& cache.count(sp.getType().getPointer())) {
continue;
}
// Constructor spaces grow with the product of their arguments.
acc *= sp.computeSize(TC, DC, cache);
}
return acc;
}
case SpaceKind::Disjunct: {
size_t acc = 0;
for (auto &sp : getSpaces()) {
// Disjoint grow with the sum of the subspaces.
acc += sp.computeSize(TC, DC, cache);
}
return acc;
}
}
}
explicit Space(Type T, Identifier NameForPrinting)
: Kind(SpaceKind::Type), TypeAndVal(T),
Head(NameForPrinting), Spaces({}){}
explicit Space(UnknownCase_t, bool allowedButNotRequired)
: Kind(SpaceKind::UnknownCase),
TypeAndVal(Type(), allowedButNotRequired), Head(Identifier()),
Spaces({}) {}
explicit Space(Type T, Identifier H, ArrayRef<Space> SP)
: Kind(SpaceKind::Constructor), TypeAndVal(T), Head(H),
Spaces(SP.begin(), SP.end()) {}
explicit Space(Type T, Identifier H, std::forward_list<Space> SP)
: Kind(SpaceKind::Constructor), TypeAndVal(T), Head(H),
Spaces(SP) {}
explicit Space(ArrayRef<Space> SP)
: Kind(SpaceKind::Disjunct), TypeAndVal(Type()),
Head(Identifier()), Spaces(SP.begin(), SP.end()) {}
explicit Space(bool C)
: Kind(SpaceKind::BooleanConstant), TypeAndVal(Type(), C),
Head(Identifier()), Spaces({}) {}
public:
explicit Space()
: Kind(SpaceKind::Empty), TypeAndVal(Type()), Head(Identifier()),
Spaces({}) {}
static Space forType(Type T, Identifier NameForPrinting) {
if (T->isStructurallyUninhabited())
return Space();
return Space(T, NameForPrinting);
}
static Space forUnknown(bool allowedButNotRequired) {
return Space(UnknownCase, allowedButNotRequired);
}
static Space forConstructor(Type T, Identifier H, ArrayRef<Space> SP) {
if (llvm::any_of(SP, std::mem_fn(&Space::isEmpty))) {
// A constructor with an unconstructible parameter can never actually
// be used.
return Space();
}
return Space(T, H, SP);
}
static Space forConstructor(Type T, Identifier H,
std::forward_list<Space> SP) {
// No need to filter SP here; this is only used to copy other
// Constructor spaces.
return Space(T, H, SP);
}
static Space forBool(bool C) {
return Space(C);
}
static Space forDisjunct(ArrayRef<Space> SP) {
SmallVector<Space, 4> spaces(SP.begin(), SP.end());
spaces.erase(
std::remove_if(spaces.begin(), spaces.end(),
[](const Space &space) { return space.isEmpty(); }),
spaces.end());
if (spaces.empty())
return Space();
if (spaces.size() == 1)
return spaces.front();
return Space(spaces);
}
bool operator==(const Space &other) const {
return Kind == other.Kind && TypeAndVal == other.TypeAndVal &&
Head == other.Head && Spaces == other.Spaces;
}
SpaceKind getKind() const { return Kind; }
void dump() const LLVM_ATTRIBUTE_USED;
size_t getSize(TypeChecker &TC, const DeclContext *DC) const {
SmallPtrSet<TypeBase *, 4> cache;
return computeSize(TC, DC, cache);
}
static size_t getMaximumSize() {
return MAX_SPACE_SIZE;
}
bool isEmpty() const { return getKind() == SpaceKind::Empty; }
bool isAllowedButNotRequired() const {
assert(getKind() == SpaceKind::UnknownCase
&& "Wrong kind of space tried to access not-required flag");
return TypeAndVal.getInt();
}
Type getType() const {
assert((getKind() == SpaceKind::Type
|| getKind() == SpaceKind::Constructor)
&& "Wrong kind of space tried to access space type");
return TypeAndVal.getPointer();
}
Identifier getHead() const {
assert(getKind() == SpaceKind::Constructor
&& "Wrong kind of space tried to access head");
return Head;
}
Identifier getPrintingName() const {
assert(getKind() == SpaceKind::Type
&& "Wrong kind of space tried to access printing name");
return Head;
}
const std::forward_list<Space> &getSpaces() const {
assert((getKind() == SpaceKind::Constructor
|| getKind() == SpaceKind::Disjunct)
&& "Wrong kind of space tried to access subspace list");
return Spaces;
}
bool getBoolValue() const {
assert(getKind() == SpaceKind::BooleanConstant
&& "Wrong kind of space tried to access bool value");
return TypeAndVal.getInt();
}
// An optimization that computes if the difference of this space and
// another space is empty.
bool isSubspace(const Space &other, TypeChecker &TC,
const DeclContext *DC) const {
if (this->isEmpty()) {
return true;
}
if (other.isEmpty()) {
return false;
}
switch (PairSwitch(getKind(), other.getKind())) {
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Empty):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Type):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Constructor):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::BooleanConstant):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::UnknownCase): {
// (S1 | ... | Sn) <= S iff (S1 <= S) && ... && (Sn <= S)
for (auto &space : this->getSpaces()) {
if (!space.isSubspace(other, TC, DC)) {
return false;
}
}
return true;
}
PAIRCASE (SpaceKind::Type, SpaceKind::Type): {
// Optimization: Are the types equal? If so, the space is covered.
if (this->getType()->isEqual(other.getType())) {
return true;
}
// (_ : Ty1) <= (_ : Ty2) iff D(Ty1) == D(Ty2)
if (canDecompose(this->getType(), DC)) {
Space or1Space = decompose(TC, DC, this->getType());
if (or1Space.isSubspace(other, TC, DC)) {
return true;
}
}
if (canDecompose(other.getType(), DC)) {
Space or2Space = decompose(TC, DC, other.getType());
return this->isSubspace(or2Space, TC, DC);
}
return true;
}
PAIRCASE (SpaceKind::Type, SpaceKind::Disjunct): {
// (_ : Ty1) <= (S1 | ... | Sn) iff (S1 <= S) || ... || (Sn <= S)
for (auto &dis : other.getSpaces()) {
if (this->isSubspace(dis, TC, DC)) {
return true;
}
}
// (_ : Ty1) <= (S1 | ... | Sn) iff D(Ty1) <= (S1 | ... | Sn)
if (!canDecompose(this->getType(), DC)) {
return false;
}
Space or1Space = decompose(TC, DC, this->getType());
return or1Space.isSubspace(other, TC, DC);
}
PAIRCASE (SpaceKind::Type, SpaceKind::Constructor): {
// (_ : Ty1) <= H(p1 | ... | pn) iff D(Ty1) <= H(p1 | ... | pn)
if (canDecompose(this->getType(), DC)) {
Space or1Space = decompose(TC, DC, this->getType());
return or1Space.isSubspace(other, TC, DC);
}
// An undecomposable type is always larger than its constructor space.
return false;
}
PAIRCASE (SpaceKind::Type, SpaceKind::UnknownCase):
return false;
PAIRCASE (SpaceKind::Constructor, SpaceKind::Type):
// Typechecking guaranteed this constructor is a subspace of the type.
return true;
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::Type):
return true;
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::Type):
return other.getType()->isBool();
PAIRCASE (SpaceKind::Constructor, SpaceKind::Constructor): {
// Optimization: If the constructor heads don't match, subspace is
// impossible.
if (this->Head != other.Head) {
return false;
}
// Special Case: Short-circuit comparisons with payload-less
// constructors.
if (other.getSpaces().empty()) {
return true;
}
// H(a1, ..., an) <= H(b1, ..., bn) iff a1 <= b1 && ... && an <= bn
auto i = this->getSpaces().begin();
auto j = other.getSpaces().begin();
for (; i != this->getSpaces().end() && j != other.getSpaces().end();
++i, ++j) {
if (!(*i).isSubspace(*j, TC, DC)) {
return false;
}
}
return true;
}
PAIRCASE (SpaceKind::Constructor, SpaceKind::UnknownCase):
for (auto ¶m : this->getSpaces()) {
if (param.isSubspace(other, TC, DC)) {
return true;
}
}
return false;
PAIRCASE (SpaceKind::Constructor, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::Disjunct): {
// S <= (S1 | ... | Sn) <= S iff (S <= S1) || ... || (S <= Sn)
for (auto ¶m : other.getSpaces()) {
if (this->isSubspace(param, TC, DC)) {
return true;
}
}
return false;
}
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::BooleanConstant):
return this->getBoolValue() == other.getBoolValue();
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::UnknownCase):
return false;
PAIRCASE (SpaceKind::Empty, SpaceKind::BooleanConstant):
PAIRCASE (SpaceKind::Constructor, SpaceKind::BooleanConstant):
PAIRCASE (SpaceKind::Type, SpaceKind::BooleanConstant):
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::BooleanConstant):
return false;
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::Constructor):
return false;
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::UnknownCase):
if (other.isAllowedButNotRequired())
return this->isAllowedButNotRequired();
return true;
default:
llvm_unreachable("Uncovered pair found while computing subspaces?");
}
}
// Returns the result of subtracting the other space from this space. The
// result is empty if the other space completely covers this space, or
// non-empty if there were any uncovered cases. The difference of spaces
// is the smallest uncovered set of cases. The result is absent if the
// computation had to be abandoned.
//
// \p minusCount is an optional pointer counting the number of
// times minus has run.
// Returns None if the computation "timed out".
Optional<Space> minus(const Space &other, TypeChecker &TC,
const DeclContext *DC, unsigned *minusCount) const {
if (minusCount && TC.getSwitchCheckingInvocationThreshold() &&
(*minusCount)++ >= TC.getSwitchCheckingInvocationThreshold())
return None;
if (this->isEmpty()) {
return Space();
}
if (other.isEmpty()) {
return *this;
}
switch (PairSwitch(this->getKind(), other.getKind())) {
PAIRCASE (SpaceKind::Type, SpaceKind::Type): {
if (this->getType()->isEqual(other.getType())) {
return Space();
}
return *this;
}
PAIRCASE (SpaceKind::Type, SpaceKind::Constructor): {
if (canDecompose(this->getType(), DC)) {
auto decomposition = decompose(TC, DC, this->getType());
return decomposition.minus(other, TC, DC, minusCount);
} else {
return *this;
}
}
PAIRCASE (SpaceKind::Type, SpaceKind::UnknownCase):
// Note: This is not technically correct for decomposable types, but
// you'd only get "typeSpace - unknownCaseSpace" if you haven't tried
// to match any of the decompositions of the space yet. In that case,
// we'd rather not expand the type, because it might be infinitely
// decomposable.
return *this;
PAIRCASE (SpaceKind::Empty, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::Type, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::Constructor, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::Disjunct):
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::Disjunct): {
Space tot = *this;
for (auto s : other.getSpaces()) {
if (auto diff = tot.minus(s, TC, DC, minusCount))
tot = *diff;
else
return None;
}
return tot;
}
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Empty):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Type):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::Constructor):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::BooleanConstant):
PAIRCASE (SpaceKind::Disjunct, SpaceKind::UnknownCase): {
SmallVector<Space, 4> smallSpaces;
for (auto s : this->getSpaces()) {
if (auto diff = s.minus(other, TC, DC, minusCount))
smallSpaces.push_back(*diff);
else
return None;
}
return Space::forDisjunct(smallSpaces);
}
PAIRCASE (SpaceKind::Constructor, SpaceKind::Type):
return Space();
PAIRCASE (SpaceKind::Constructor, SpaceKind::UnknownCase): {
SmallVector<Space, 4> newSubSpaces;
for (auto subSpace : this->getSpaces()) {
auto nextSpace = subSpace.minus(other, TC, DC, minusCount);
if (!nextSpace)
return None;
if (nextSpace.getValue().isEmpty())
return Space();
newSubSpaces.push_back(nextSpace.getValue());
}
return Space::forConstructor(this->getType(), this->getHead(),
newSubSpaces);
}
PAIRCASE (SpaceKind::Constructor, SpaceKind::Constructor): {
// Optimization: If the heads of the constructors don't match then
// the two are disjoint and their difference is the first space.
if (this->Head != other.Head) {
return *this;
}
// Special Case: Short circuit patterns without payloads. Their
// difference is empty.
if (other.getSpaces().empty()) {
return Space();
}
SmallVector<Space, 4> constrSpaces;
bool foundBad = false;
auto i = this->getSpaces().begin();
auto j = other.getSpaces().begin();
for (auto idx = 0;
i != this->getSpaces().end() && j != other.getSpaces().end();
++i, ++j, ++idx) {
auto &s1 = *i;
auto &s2 = *j;
// If one constructor parameter doesn't cover the other then we've
// got to report the uncovered cases in a user-friendly way.
if (!s1.isSubspace(s2, TC, DC)) {
foundBad = true;
}
// Copy the params and replace the parameter at each index with the
// difference of the two spaces. This unpacks one constructor head
// into each parameter.
SmallVector<Space, 4> copyParams(this->getSpaces().begin(),
this->getSpaces().end());
auto reducedSpaceOrNone = s1.minus(s2, TC, DC, minusCount);
if (!reducedSpaceOrNone)
return None;
auto reducedSpace = *reducedSpaceOrNone;
// If one of the constructor parameters is empty it means
// the whole constructor space is empty as well, so we can
// safely skip it.
if (reducedSpace.isEmpty())
continue;
// If reduced produced the same space as original one, we
// should return it directly instead of trying to create
// a disjunction of its sub-spaces because nothing got reduced.
// This is especially helpful when dealing with `unknown` case
// in parameter positions.
if (s1 == reducedSpace)
return *this;
copyParams[idx] = reducedSpace;
Space CS = Space::forConstructor(this->getType(), this->getHead(),
copyParams);
constrSpaces.push_back(CS);
}
if (foundBad) {
return Space::forDisjunct(constrSpaces);
}
return Space();
}
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::BooleanConstant): {
// The difference of boolean constants depends on their values.
if (this->getBoolValue() == other.getBoolValue()) {
return Space();
} else {
return *this;
}
}
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::Type): {
if (other.getType()->isBool()) {
return (getKind() == SpaceKind::BooleanConstant) ? Space() : *this;
}
if (canDecompose(other.getType(), DC)) {
auto decomposition = decompose(TC, DC, other.getType());
return this->minus(decomposition, TC, DC, minusCount);
}
return *this;
}
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::Empty):
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::Constructor):
PAIRCASE (SpaceKind::BooleanConstant, SpaceKind::UnknownCase):
return *this;
PAIRCASE (SpaceKind::Type, SpaceKind::BooleanConstant): {
if (canDecompose(this->getType(), DC)) {
auto orSpace = decompose(TC, DC, this->getType());
return orSpace.minus(other, TC, DC, minusCount);
} else {
return *this;
}
}
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::Type):
return Space();
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::Constructor):
return *this;
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::UnknownCase):
if (other.isAllowedButNotRequired() &&
!this->isAllowedButNotRequired()) {
return *this;
}
return Space();
PAIRCASE (SpaceKind::Empty, SpaceKind::BooleanConstant):
PAIRCASE (SpaceKind::Constructor, SpaceKind::BooleanConstant):
PAIRCASE (SpaceKind::UnknownCase, SpaceKind::BooleanConstant):
return *this;
default:
llvm_unreachable("Uncovered pair found while computing difference?");
}
}
void show(llvm::raw_ostream &buffer, bool forDisplay = true) const {
switch (getKind()) {
case SpaceKind::Empty:
if (forDisplay) {
buffer << "_";
} else {
buffer << "[EMPTY]";
}
break;
case SpaceKind::Disjunct: {
if (forDisplay) {
llvm_unreachable("Attempted to display disjunct to user!");
} else {
buffer << "DISJOIN(";
for (auto &sp : Spaces) {
buffer << "\n";
sp.show(buffer, forDisplay);
buffer << " |";
}
buffer << ")";
}
}
break;
case SpaceKind::BooleanConstant:
buffer << (getBoolValue() ? "true" : "false");
break;
case SpaceKind::Constructor: {
if (!Head.empty()) {
buffer << ".";
buffer << Head.str();
}
if (Spaces.empty()) {
return;
}
buffer << "(";
bool first = true;
for (auto ¶m : Spaces) {
if (!first) {
buffer << ", ";
}
param.show(buffer, forDisplay);
if (first) {
first = false;
}
}
buffer << ")";
}
break;
case SpaceKind::Type: {
Identifier Name = getPrintingName();
if (Name.empty())
buffer << "_";
else
buffer << tok::kw_let << " " << Name.str();
if (!forDisplay) {
buffer << ": ";
getType()->print(buffer);
}
}
break;
case SpaceKind::UnknownCase:
if (forDisplay) {
// We special-case this to use "@unknown default" at the top level.
buffer << "_";
} else {
buffer << "UNKNOWN";
if (isAllowedButNotRequired())
buffer << "(not_required)";
}
break;
}
}
// Decompose a type into its component spaces.
static void decompose(TypeChecker &TC, const DeclContext *DC, Type tp,
SmallVectorImpl<Space> &arr) {
assert(canDecompose(tp, DC) && "Non-decomposable type?");
if (tp->isBool()) {
arr.push_back(Space::forBool(true));
arr.push_back(Space::forBool(false));
} else if (auto *E = tp->getEnumOrBoundGenericEnum()) {
// Look into each case of the enum and decompose it in turn.
auto children = E->getAllElements();
std::transform(children.begin(), children.end(),
std::back_inserter(arr), [&](EnumElementDecl *eed) {
SmallVector<Space, 4> constElemSpaces;
// We need the interface type of this enum case but it may
// not have been computed.
if (!eed->hasInterfaceType()) {
TC.validateDecl(eed);
}
// If there's still no interface type after validation then there's
// not much else we can do here.
if (!eed->hasInterfaceType()) {
return Space();
}
// Don't force people to match unavailable cases; they can't even
// write them.
if (AvailableAttr::isUnavailable(eed)) {
return Space();
}
auto eedTy = tp->getCanonicalType()
->getTypeOfMember(E->getModuleContext(), eed,
eed->getArgumentInterfaceType());
if (eedTy) {
if (auto *TTy = eedTy->getAs<TupleType>()) {
// Decompose the payload tuple into its component type spaces.
llvm::transform(TTy->getElements(),
std::back_inserter(constElemSpaces),
[&](TupleTypeElt elt) {
return Space::forType(elt.getType(), elt.getName());
});
} else if (auto *TTy = dyn_cast<ParenType>(eedTy.getPointer())) {
constElemSpaces.push_back(
Space::forType(TTy->getUnderlyingType(), Identifier()));
}
}
return Space::forConstructor(tp, eed->getName(),
constElemSpaces);
});
if (!E->isFormallyExhaustive(DC)) {
arr.push_back(Space::forUnknown(/*allowedButNotRequired*/false));
} else if (!E->getAttrs().hasAttribute<FrozenAttr>()) {
arr.push_back(Space::forUnknown(/*allowedButNotRequired*/true));
}
} else if (auto *TTy = tp->castTo<TupleType>()) {
// Decompose each of the elements into its component type space.
SmallVector<Space, 4> constElemSpaces;
llvm::transform(TTy->getElements(),
std::back_inserter(constElemSpaces),
[&](TupleTypeElt elt) {
return Space::forType(elt.getType(), elt.getName());
});
// Create an empty constructor head for the tuple space.
arr.push_back(Space::forConstructor(tp, Identifier(),
constElemSpaces));
} else {
llvm_unreachable("Can't decompose type?");
}
}
static Space decompose(TypeChecker &TC, const DeclContext *DC,
Type type) {
SmallVector<Space, 4> spaces;
decompose(TC, DC, type, spaces);
return Space::forDisjunct(spaces);
}
static bool canDecompose(Type tp, const DeclContext *DC) {
return tp->is<TupleType>() || tp->isBool() ||
tp->getEnumOrBoundGenericEnum();
}
// Search the space for a reason to downgrade exhaustiveness errors to
// a warning e.g. 'unknown case' statements.
DowngradeToWarning checkDowngradeToWarning() const {
switch (getKind()) {
case SpaceKind::Type:
case SpaceKind::BooleanConstant:
case SpaceKind::Empty:
return DowngradeToWarning::No;
case SpaceKind::UnknownCase:
return DowngradeToWarning::ForUnknownCase;
case SpaceKind::Constructor: {
auto result = DowngradeToWarning::No;
// Traverse the constructor and its subspaces.
for (const Space &space : getSpaces())
result = std::max(result, space.checkDowngradeToWarning());
return result;
}
case SpaceKind::Disjunct: {
if (getSpaces().empty())
return DowngradeToWarning::No;
// Traverse the disjunct's subspaces.
auto result = DowngradeToWarning::LAST;
for (const Space &space : getSpaces())
result = std::min(result, space.checkDowngradeToWarning());
return result;
}
}
}
};
TypeChecker &TC;
const SwitchStmt *Switch;
const DeclContext *DC;
llvm::DenseMap<APInt, Expr *, ::DenseMapAPIntKeyInfo> IntLiteralCache;
llvm::DenseMap<APFloat, Expr *, ::DenseMapAPFloatKeyInfo> FloatLiteralCache;
llvm::DenseMap<StringRef, Expr *> StringLiteralCache;
SpaceEngine(TypeChecker &C, const SwitchStmt *SS, const DeclContext *DC)
: TC(C), Switch(SS), DC(DC) {}
bool checkRedundantLiteral(const Pattern *Pat, Expr *&PrevPattern) {
if (Pat->getKind() != PatternKind::Expr) {
return false;
}
auto *ExprPat = cast<ExprPattern>(Pat);
auto *MatchExpr = ExprPat->getSubExpr();
if (!MatchExpr || !isa<LiteralExpr>(MatchExpr)) {
return false;
}
auto *EL = cast<LiteralExpr>(MatchExpr);
switch (EL->getKind()) {
case ExprKind::StringLiteral: {
auto *SLE = cast<StringLiteralExpr>(EL);
auto cacheVal =
StringLiteralCache.insert({SLE->getValue(), SLE});
PrevPattern = (cacheVal.first != StringLiteralCache.end())
? cacheVal.first->getSecond()
: nullptr;
return !cacheVal.second;
}
case ExprKind::IntegerLiteral: {
// FIXME: The magic number 128 is bad and we should actually figure out
// the bitwidth. But it's too early in Sema to get it.
auto *ILE = cast<IntegerLiteralExpr>(EL);
auto cacheVal =
IntLiteralCache.insert(
{ILE->getValue(ILE->getDigitsText(), 128, ILE->isNegative()), ILE});
PrevPattern = (cacheVal.first != IntLiteralCache.end())
? cacheVal.first->getSecond()
: nullptr;
return !cacheVal.second;
}
case ExprKind::FloatLiteral: {
// FIXME: Pessimistically using IEEEquad here is bad and we should
// actually figure out the bitwidth. But it's too early in Sema.
auto *FLE = cast<FloatLiteralExpr>(EL);
auto cacheVal =
FloatLiteralCache.insert(
{FLE->getValue(FLE->getDigitsText(),
APFloat::IEEEquad(), FLE->isNegative()), FLE});
PrevPattern = (cacheVal.first != FloatLiteralCache.end())
? cacheVal.first->getSecond()
: nullptr;
return !cacheVal.second;
}
default:
return false;
}
}
/// Estimate how big is the search space that exhaustivity
/// checker needs to cover, based on the total space and information
/// from the `switch` statement itself. Some of the easy situations
/// like `case .foo(let bar)` don't really contribute to the complexity
/// of the search so their sub-space sizes could be excluded from
/// consideration.
///
/// \param total The total space to check.
/// \param covered The space covered by the `case` statements in the switch.
///
/// \returns The size of the search space exhastivity checker has to check.
size_t estimateSearchSpaceSize(const Space &total, const Space &covered) {
switch (PairSwitch(total.getKind(), covered.getKind())) {
PAIRCASE(SpaceKind::Type, SpaceKind::Type): {
return total.getType()->isEqual(covered.getType())
? 0
: total.getSize(TC, DC);
}
PAIRCASE(SpaceKind::Type, SpaceKind::Disjunct):
PAIRCASE(SpaceKind::Type, SpaceKind::Constructor): {
if (!Space::canDecompose(total.getType(), DC))
break;
auto decomposition = Space::decompose(TC, DC, total.getType());
return estimateSearchSpaceSize(decomposition, covered);
}
PAIRCASE(SpaceKind::Disjunct, SpaceKind::Disjunct):
PAIRCASE(SpaceKind::Disjunct, SpaceKind::Constructor): {
auto &spaces = total.getSpaces();
return std::accumulate(spaces.begin(), spaces.end(), 0,
[&](size_t totalSize, const Space &space) {
return totalSize + estimateSearchSpaceSize(
space, covered);
});
}
// Search space size computation is not commutative, because it
// tries to check if space on right-hand side is covering any
// portion of the "total" space on the left.
PAIRCASE(SpaceKind::Constructor, SpaceKind::Disjunct): {
for (const auto &space : covered.getSpaces()) {
// enum E { case foo }
// func bar(_ lhs: E, _ rhs: E) {
// switch (lhs, rhs) {
// case (_, _): break
// }
if (total == space)
return 0;
if (!space.isSubspace(total, TC, DC))
continue;
if (estimateSearchSpaceSize(total, space) == 0)
return 0;
}
break;
}
PAIRCASE(SpaceKind::Constructor, SpaceKind::Constructor): {
if (total.getHead() != covered.getHead())
break;
auto &lhs = total.getSpaces();
auto &rhs = covered.getSpaces();
if (std::distance(lhs.begin(), lhs.end()) !=
std::distance(rhs.begin(), rhs.end()))
return total.getSize(TC, DC);
auto i = lhs.begin();
auto j = rhs.begin();
size_t totalSize = 0;
for (; i != lhs.end() && j != rhs.end(); ++i, ++j) {
// The only light-weight checking we can do
// is when sub-spaces on both sides are types