-
Notifications
You must be signed in to change notification settings - Fork 10.5k
/
Copy pathArrays.swift.gyb
883 lines (755 loc) · 25.3 KB
/
Arrays.swift.gyb
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
// RUN: rm -rf %t
// RUN: mkdir -p %t
// RUN: %S/../../utils/gyb %s -o %t/ArrayTraps.swift
// RUN: %S/../../utils/line-directive %t/ArrayTraps.swift -- %target-build-swift %t/ArrayTraps.swift -o %t/a.out
//
// RUN: %S/../../utils/line-directive %t/ArrayTraps.swift -- %target-run %t/a.out
// REQUIRES: executable_test
import StdlibUnittest
import StdlibCollectionUnittest
let CopyToNativeArrayBufferTests = TestSuite("CopyToNativeArrayBufferTests")
CopyToNativeArrayBufferTests.test("Sequence._copyToNativeArrayBuffer()") {
do {
// Call from a static context.
let s =
MinimalSequence(elements: LifetimeTracked(10)..<LifetimeTracked(27))
expectEqual(0, s.timesMakeIteratorCalled.value)
let buffer = s._copyToNativeArrayBuffer()
expectEqual(1, s.timesMakeIteratorCalled.value)
expectEqualSequence(
Array(10..<27),
buffer.map { $0.value })
}
do {
// Call from a generic context.
let wrapped = MinimalSequence(elements: LifetimeTracked(10)..<LifetimeTracked(27))
let s = LoggingSequence(wrapping: wrapped)
expectEqual(0, wrapped.timesMakeIteratorCalled.value)
let buffer = s._copyToNativeArrayBuffer()
expectEqual(1, wrapped.timesMakeIteratorCalled.value)
expectEqualSequence(
Array(10..<27),
buffer.map { $0.value })
}
}
CopyToNativeArrayBufferTests.test("Collection._copyToNativeArrayBuffer()") {
// Check that collections are handled with the collection-specific API. This
// means that we are calling the right default implementation (one for
// collections, not the one for sequences).
do {
// Call from a static context.
let c =
DefaultedCollection(elements: LifetimeTracked(10)..<LifetimeTracked(27))
expectEqual(0, c.timesMakeIteratorCalled.value)
expectEqual(0, c.timesStartIndexCalled.value)
let buffer = c._copyToNativeArrayBuffer()
expectEqual(0, c.timesMakeIteratorCalled.value)
expectNotEqual(0, c.timesStartIndexCalled.value)
expectEqualSequence(
Array(10..<27),
buffer.map { $0.value })
}
do {
// Call from a generic context.
let wrapped =
DefaultedCollection(elements: LifetimeTracked(10)..<LifetimeTracked(27))
let s = LoggingSequence(wrapping: wrapped)
expectEqual(0, wrapped.timesMakeIteratorCalled.value)
expectEqual(0, wrapped.timesStartIndexCalled.value)
let buffer = s._copyToNativeArrayBuffer()
expectEqual(0, wrapped.timesMakeIteratorCalled.value)
expectNotEqual(0, wrapped.timesStartIndexCalled.value)
expectEqualSequence(
Array(10..<27),
buffer.map { $0.value })
}
}
%{
all_array_types = ['ContiguousArray', 'ArraySlice', 'Array']
}%
extension Array {
var identity: UnsafePointer<Void> {
return self._buffer.identity
}
}
extension ArraySlice {
var identity: UnsafePointer<Void> {
return self._buffer.identity
}
}
extension ContiguousArray {
var identity: UnsafePointer<Void> {
return self._buffer.identity
}
}
var ArrayTestSuite = TestSuite("Array")
ArrayTestSuite.test("sizeof") {
var a = [ 10, 20, 30 ]
#if arch(i386) || arch(arm)
expectEqual(4, sizeofValue(a))
#else
expectEqual(8, sizeofValue(a))
#endif
}
ArrayTestSuite.test("valueDestruction") {
var a = [LifetimeTracked]()
for i in 100...110 {
a.append(LifetimeTracked(i))
}
}
//===----------------------------------------------------------------------===//
// Native array tests
// FIXME: incomplete.
//===----------------------------------------------------------------------===//
ArrayTestSuite.test("Native/count/empty") {
let a = [LifetimeTracked]()
expectEqual(0, a.count)
}
ArrayTestSuite.test("Native/count") {
let a = [ LifetimeTracked(10), LifetimeTracked(20), LifetimeTracked(30) ]
expectEqual(3, a.count)
}
ArrayTestSuite.test("Native/isEmpty/empty") {
let a = [LifetimeTracked]()
expectTrue(a.isEmpty)
}
ArrayTestSuite.test("Native/isEmpty") {
let a = [ LifetimeTracked(10), LifetimeTracked(20), LifetimeTracked(30) ]
expectFalse(a.isEmpty)
}
protocol TestProtocol1 {}
% for array_type in all_array_types:
// Check that the generic parameter is called 'Element'.
extension ${array_type} where Element : TestProtocol1 {
var _elementIsTestProtocol1: Bool {
fatalError("not implemented")
}
}
/// Returns an ${array_type} that does not share its buffer with other arrays.
func getFresh${array_type}<S : Sequence>(_ sequence: S)
-> ${array_type}<S.Iterator.Element> {
var result: ${array_type}<S.Iterator.Element> = []
result.reserveCapacity(sequence.underestimatedCount)
for element in sequence {
result.append(element)
}
return result
}
% end
enum EnumWithoutPayloads : Equatable {
case A, B, C, D
}
func == (lhs: EnumWithoutPayloads, rhs: EnumWithoutPayloads) -> Bool {
switch (lhs, rhs) {
case (.A, .A), (.B, .B), (.C, .C), (.D, .D):
return true
default:
return false
}
}
struct SequenceWithCustomUnderestimatedCount : Sequence {
init(_ data: [Int]) {
self._data = MinimalSequence(elements: data.map(OpaqueValue.init))
}
func makeIterator() -> MinimalSequence<OpaqueValue<Int>>.Iterator {
return _data.makeIterator()
}
var underestimatedCount: Int {
SequenceWithCustomUnderestimatedCount.timesUnderestimatedCountWasCalled += 1
return _data.underestimatedCount
}
static var timesUnderestimatedCountWasCalled: Int = 0
let _data: MinimalSequence<OpaqueValue<Int>>
}
% for array_type in all_array_types:
ArrayTestSuite.test("${array_type}/init(Sequence)") {
let base = SequenceWithCustomUnderestimatedCount(
[ 0, 30, 10, 90 ])
SequenceWithCustomUnderestimatedCount.timesUnderestimatedCountWasCalled = 0
let result = ${array_type}(base)
expectEqual([ 0, 30, 10, 90 ], result.map { $0.value })
expectEqual(1, SequenceWithCustomUnderestimatedCount.timesUnderestimatedCountWasCalled)
expectEqualSequence(
[], Array(base).map { $0.value }, "sequence should be consumed")
}
ArrayTestSuite.test("${array_type}/Sliceable/Enums") {
typealias E = EnumWithoutPayloads
do {
let expected = [E.A, E.B, E.C, E.D]
let sliceable = ${array_type}(expected)
checkSliceableWithBidirectionalIndex(expected, sliceable)
}
/*
FIXME: add this test when Array<T> can be conditionally Equatable.
do {
let expected = [[E.A, E.B], [E.B, E.C], [E.D], [E.A, E.B, E.D]]
let sliceable = ${array_type}(expected)
checkSliceableWithBidirectionalIndex(
expected, sliceable, SourceLocStack().withCurrentLoc())
}
*/
}
ArrayTestSuite.test("${array_type}/appendNonUnique") {
var x: ${array_type}<Int> = []
x.reserveCapacity(10002)
let capacity = x.capacity
for _ in 1...10000 {
let y = x
x.append(1)
expectTrue(x.capacity == capacity)
let z = x
x.remove(at: 0)
}
}
ArrayTestSuite.test("${array_type}/emptyAllocation") {
let arr0 = ${array_type}<Int>()
let arr1 = ${array_type}<LifetimeTracked>(repeating: LifetimeTracked(0), count: 0)
// Empty arrays all use the same buffer
expectEqual(arr0._buffer.identity, arr1._buffer.identity)
let arr2: ${array_type}<LifetimeTracked> = []
let emptyLiteralsShareBuffer = arr0._buffer.identity == arr2._buffer.identity
expectTrue(emptyLiteralsShareBuffer)
}
ArrayTestSuite.test("${array_type}/filter") {
do {
let arr: ${array_type}<Int> = []
var result = arr.filter() {
(x: Int) -> Bool in
expectUnreachable()
return true
}
expectType(Array<Int>.self, &result)
expectEqual([], result)
expectEqual(0, result.capacity)
}
do {
let arr: ${array_type}<Int> = [ 0, 30, 10, 90 ]
let result = arr.filter() { (x: Int) -> Bool in true }
expectEqual([ 0, 30, 10, 90 ], result)
expectGE(2 * result.count, result.capacity)
}
do {
let arr: ${array_type}<Int> = [ 0, 30, 10, 90 ]
let result = arr.filter() { (x: Int) -> Bool in false }
expectEqual([], result)
expectGE(2 * result.count, result.capacity)
}
do {
let arr: ${array_type}<Int> = [ 0, 30, 10, 90 ]
let result = arr.filter() { $0 % 3 == 0 }
expectEqual([ 0, 30, 90 ], result)
expectGE(2 * result.count, result.capacity)
}
}
ArrayTestSuite.test("${array_type}/map") {
do {
let arr: ${array_type}<Int> = []
var result = arr.map() {
(x: Int) -> Int16 in
expectUnreachable()
return 42
}
expectType(Array<Int16>.self, &result)
expectEqual([], result)
expectEqual(0, result.capacity)
}
do {
let arr: ${array_type}<Int> = [ 0, 30, 10, 90 ]
let result = arr.map() { $0 + 1 }
expectEqual([ 1, 31, 11, 91 ], result)
expectGE(2 * result.count, result.capacity)
}
}
ArrayTestSuite.test("${array_type}/flatMap") {
let enumerate : Int -> ${array_type}<Int> =
{ return ${array_type}(1..<($0 + 1)) }
expectEqualSequence([], ${array_type}().flatMap(enumerate))
expectEqualSequence([ 1 ], ${array_type}([ 1 ]).flatMap(enumerate))
expectEqualSequence(
[ 1, 1, 2 ],
${array_type}([ 1, 2 ]).flatMap(enumerate))
expectEqualSequence(
[ 1, 1, 1, 2 ],
${array_type}([ 1, 2 ]).flatMap(enumerate).flatMap(enumerate))
}
ArrayTestSuite.test("${array_type}/Mirror") {
do {
let input: ${array_type}<Int> = []
var output = ""
dump(input, to: &output)
let expected =
"- 0 elements\n"
expectEqual(expected, output)
}
do {
let input: ${array_type}<Int> = [ 10, 20, 30, 40 ]
var output = ""
dump(input, to: &output)
let expected =
"▿ 4 elements\n" +
" - 10\n" +
" - 20\n" +
" - 30\n" +
" - 40\n"
expectEqual(expected, output)
}
% if array_type == 'ArraySlice':
do {
let base = [ 10, 20, 30, 40 ]
let input: ArraySlice<Int> = base[1..<3]
var output = ""
dump(input, to: &output)
let expected =
"▿ 2 elements\n" +
" - 20\n" +
" - 30\n"
expectEqual(expected, output)
}
% end
}
% end
% for Kind in ['Array', 'ContiguousArray']:
ArrayTestSuite.test("${Kind}/popLast") {
// Empty
do {
var a = ${Kind}<Int>()
let popped = a.popLast()
expectEmpty(popped)
expectTrue(a.isEmpty)
}
do {
var popped = [Int]()
var a: ${Kind}<Int> = [1010, 2020, 3030]
while let element = a.popLast() {
popped.append(element)
}
expectEqualSequence([1010, 2020, 3030], popped.reversed())
expectTrue(a.isEmpty)
}
}
% end
// Check how removeFirst() affects indices.
% for Kind in ['Array', 'ContiguousArray']:
ArrayTestSuite.test("${Kind}/removeFirst") {
do {
var a: ${Kind}<OpaqueValue<Int>> = ${Kind}([ 1 ].map(OpaqueValue.init))
a.removeFirst()
expectEqual(0, a.startIndex)
}
do {
var a: ${Kind}<OpaqueValue<Int>> = ${Kind}([ 1, 2 ].map(OpaqueValue.init))
a.removeFirst()
expectEqual(0, a.startIndex)
}
}
% end
ArrayTestSuite.test("ArraySlice/removeFirst") {
do {
let a: [OpaqueValue<Int>] = [ 99, 1010, 99 ].map(OpaqueValue.init)
var s = a[1..<2]
expectEqual(1, s.startIndex)
s.removeFirst()
expectEqual(2, s.startIndex)
}
do {
let a: [OpaqueValue<Int>] = [ 99, 1010, 2020, 99 ].map(OpaqueValue.init)
var s = a[1..<2]
expectEqual(1, s.startIndex)
s.removeFirst()
expectEqual(2, s.startIndex)
}
}
//===----------------------------------------------------------------------===//
// _withUnsafeMutableBufferPointerIfSupported()
//===----------------------------------------------------------------------===//
struct WithUnsafeMutableBufferPointerIfSupportedTest {
let sequence: [Int]
let loc: SourceLoc
init(
_ sequence: [Int],
file: String = #file, line: UInt = #line
) {
self.sequence = sequence
self.loc = SourceLoc(file, line, comment: "test data")
}
}
let withUnsafeMutableBufferPointerIfSupportedTests = [
WithUnsafeMutableBufferPointerIfSupportedTest([]),
WithUnsafeMutableBufferPointerIfSupportedTest([ 10 ]),
WithUnsafeMutableBufferPointerIfSupportedTest([ 10, 20, 30, 40, 50 ]),
]
% for array_type in all_array_types:
ArrayTestSuite.test("${array_type}/_withUnsafeMutableBufferPointerIfSupported") {
for test in withUnsafeMutableBufferPointerIfSupportedTests {
var a = getFresh${array_type}(test.sequence.map(OpaqueValue.init))
do {
// Read.
var result = a._withUnsafeMutableBufferPointerIfSupported {
(baseAddress, count) -> OpaqueValue<[OpaqueValue<Int>]> in
let bufferPointer =
UnsafeMutableBufferPointer(start: baseAddress, count: count)
return OpaqueValue(Array(bufferPointer))
}
expectType(Optional<OpaqueValue<Array<OpaqueValue<Int>>>>.self, &result)
expectEqualSequence(test.sequence, result!.value.map { $0.value })
expectEqualSequence(test.sequence, a.map { $0.value })
}
do {
// Read and write.
var result = a._withUnsafeMutableBufferPointerIfSupported {
(baseAddress, count) -> OpaqueValue<Array<OpaqueValue<Int>>> in
let bufferPointer =
UnsafeMutableBufferPointer(start: baseAddress, count: count)
let result = OpaqueValue(Array(bufferPointer))
for i in bufferPointer.indices {
bufferPointer[i] = OpaqueValue(bufferPointer[i].value * 10)
}
return result
}
expectType(Optional<OpaqueValue<Array<OpaqueValue<Int>>>>.self, &result)
expectEqualSequence(test.sequence, result!.value.map { $0.value })
expectEqualSequence(
test.sequence.map { $0 * 10 },
a.map { $0.value })
}
}
// FIXME: tests for arrays bridged from Objective-C.
}
ArrayTestSuite.test("${array_type}/_withUnsafeMutableBufferPointerIfSupported/ReplacingTheBufferTraps/1") {
var a = getFresh${array_type}([ OpaqueValue(10) ])
var result = a._withUnsafeMutableBufferPointerIfSupported {
(baseAddress, count) -> OpaqueValue<Int> in
// buffer = UnsafeMutableBufferPointer(start: buffer.baseAddress, count: 0)
// FIXME: does not trap since the buffer is not passed inout.
// expectCrashLater()
return OpaqueValue(42)
}
}
ArrayTestSuite.test("${array_type}/_withUnsafeMutableBufferPointerIfSupported/ReplacingTheBufferTraps/2") {
var a = getFresh${array_type}([ OpaqueValue(10) ])
var result = a._withUnsafeMutableBufferPointerIfSupported {
(baseAddress, count) -> OpaqueValue<Int> in
// buffer = UnsafeMutableBufferPointer(start: nil, count: 1)
// FIXME: does not trap since the buffer is not passed inout.
// expectCrashLater()
return OpaqueValue(42)
}
}
//===---
// Check that iterators traverse a snapshot of the collection.
//===---
ArrayTestSuite.test(
"${array_type}/mutationDoesNotAffectIterator/subscript/store") {
var arr: ${array_type}<Int> = [ 1010, 1020, 1030 ]
var iter = arr.makeIterator()
arr[0] = 1011
expectEqual([ 1010, 1020, 1030 ], Array(IteratorSequence(iter)))
}
ArrayTestSuite.test(
"${array_type}/mutationDoesNotAffectIterator/subscript/append") {
var arr: ${array_type}<Int> = [ 1010, 1020, 1030 ]
var iter = arr.makeIterator()
arr.append(1040)
expectEqual([ 1010, 1020, 1030 ], Array(IteratorSequence(iter)))
}
ArrayTestSuite.test(
"${array_type}/mutationDoesNotAffectIterator/subscript/replaceSubrange") {
var arr: ${array_type}<Int> = [ 1010, 1020, 1030 ]
var iter = arr.makeIterator()
arr.replaceSubrange(1..<3, with: [ 1040, 1050, 1060 ])
expectEqual([ 1010, 1020, 1030 ], Array(IteratorSequence(iter)))
}
% end
//===----------------------------------------------------------------------===//
// Array and EvilCollection that changes its size while we are not looking
//===----------------------------------------------------------------------===//
let evilBoundsError = "EvilCollection: index out of range"
final class EvilSequence : Sequence {
init(_ growth: Int) {
self.growth = growth
}
var growth: Int
var _count: Int = 20
var underestimatedCount: Int {
defer { _count += growth }
return _count
}
@warn_unused_result
func makeIterator() -> AnyIterator<LifetimeTracked> {
var i = 0
return AnyIterator {
if i >= self._count { return nil }
let result = LifetimeTracked(i)
i += 1
return result
}
}
}
final class EvilCollection : Collection {
func index(after i: Int) -> Int {
return i + 1
}
init(_ growth: Int, boundsChecked: Bool) {
self.growth = growth
self.boundsChecked = boundsChecked
}
var growth: Int
var _count: Int = 20
var boundsChecked: Bool
var startIndex : Int {
_count += growth
return 0
}
var endIndex : Int {
return _count
}
subscript(i: Int) -> LifetimeTracked {
if boundsChecked {
precondition(i >= 0 && i < _count, evilBoundsError)
}
return LifetimeTracked(i)
}
// Default implementation will call _failEarlyRangeCheck,
// passing in a startIndex that will grow _count faster than
// necessary.
func formIndex(after i: inout Int) {
i += 1
}
}
for (step, evilBoundsCheck) in [ (1, true), (-1, false), (-1, true) ] {
let message = step < 0 && evilBoundsCheck
? evilBoundsError
: "invalid Collection: count differed in successive traversals"
let constructionMessage =
/*_isStdlibInternalChecksEnabled() && !evilBoundsCheck && step <= 0
? "_UnsafePartiallyInitializedContiguousArrayBuffer has no more capacity"
:*/ message
// The invalid Collection error is a _debugPreconditon that will only fire
// in a Debug assert configuration.
let expectedToFail = (step < 0 && evilBoundsCheck) ||
_isDebugAssertConfiguration()
let natureOfEvil = step > 0 ? "Growth" : "Shrinkage"
let boundsChecked = evilBoundsCheck ? "BoundsChecked" : "NoBoundsCheck"
let testPrefix = "MemorySafety/\(boundsChecked)/Evil\(natureOfEvil)"
ArrayTestSuite.test("\(testPrefix)/Infrastructure/EvilSequence") {
let evil = EvilSequence(step)
let count0 = evil.underestimatedCount
let count1 = evil.underestimatedCount
expectNotEqual(count0, count1)
if step > 0 {
expectLE(count0, count1)
}
else {
expectGE(count0, count1)
}
}
let t1 = ArrayTestSuite.test("\(testPrefix)/Infrastructure/EvilCollection")
(evilBoundsCheck && _isDebugAssertConfiguration()
? t1.crashOutputMatches(evilBoundsError) : t1)
.code {
let evil = EvilCollection(step, boundsChecked: evilBoundsCheck)
let count0 = evil.count
let count1 = evil.count
expectNotEqual(count0, count1)
if step > 0 {
expectLE(count0, count1)
}
else {
expectGE(count0, count1)
}
if evilBoundsCheck {
expectCrashLater()
}
let x = evil[-1]
_blackHole(x)
}
let t2 = ArrayTestSuite.test("\(testPrefix)/Construction")
(_isDebugAssertConfiguration() && expectedToFail
? t2.crashOutputMatches(constructionMessage) : t2)
.code {
let evil = EvilCollection(step, boundsChecked: evilBoundsCheck)
if expectedToFail {
expectCrashLater()
}
let a = Array(evil)
_blackHole(a)
}
for (op, rangeMax) in ["Grow":0, "Shrink":200] {
let t3 = ArrayTestSuite.test("\(testPrefix)/replaceSubrange/\(op)Unique")
(_isDebugAssertConfiguration() ? t3.crashOutputMatches(message) : t3)
.code {
let evil = EvilCollection(step, boundsChecked: evilBoundsCheck)
var a = Array((0..<200).lazy.map { LifetimeTracked($0) })
if expectedToFail {
expectCrashLater()
}
a.replaceSubrange(0..<rangeMax, with: evil)
}
let t4 = ArrayTestSuite.test("\(testPrefix)/replaceSubrange/\(op)NonUnique")
(_isDebugAssertConfiguration() ? t4.crashOutputMatches(message) : t4)
.code {
let evil = EvilCollection(step, boundsChecked: evilBoundsCheck)
var a = Array((0..<200).lazy.map { LifetimeTracked($0) })
var b = a
if expectedToFail {
expectCrashLater()
}
a.replaceSubrange(0..<rangeMax, with: evil)
_fixLifetime(b)
}
}
ArrayTestSuite.test("\(testPrefix)/SequenceMap")
.skip(.custom(
{ _isFastAssertConfiguration() },
reason: "this trap is not guaranteed to happen in -Ounchecked"))
.code {
let evil = EvilSequence(step)
if step < 0 {
expectCrashLater()
}
let a = evil.map { $0 }
_blackHole(a)
}
ArrayTestSuite.test("\(testPrefix)/CollectionMap")
.code {
let evil = EvilCollection(step, boundsChecked: evilBoundsCheck)
if expectedToFail {
expectCrashLater()
}
let a = evil.map { $0 }
_blackHole(a)
}
ArrayTestSuite.test("\(testPrefix)/FilterAll")
.code {
let evil = EvilCollection(step, boundsChecked: evilBoundsCheck)
let a = evil.filter { _ in true }
_blackHole(a)
}
ArrayTestSuite.test("\(testPrefix)/FilterNone")
.code {
let evil = EvilCollection(step, boundsChecked: evilBoundsCheck)
let a = evil.filter { _ in false }
_blackHole(a)
}
}
//===----------------------------------------------------------------------===//
// Special cases and one-off tests.
//===----------------------------------------------------------------------===//
% for array_type in all_array_types:
ArrayTestSuite.test("${array_type}<Void>/map") {
// This code used to crash because it generated an array of Void with
// stride == 0.
do {
let input: ${array_type}<Void> = [ (), (), () ]
let result = input.map { (_) -> Void in return () }
expectEqual(3, result.count)
}
do {
let input: ${array_type}<OpaqueValue<Int>> = [
OpaqueValue(10), OpaqueValue(20), OpaqueValue(30)
]
let result = input.map { (_) -> Void in return () }
expectEqual(3, result.count)
}
}
% end
//===----------------------------------------------------------------------===//
// MutableCollectionType and RangeReplaceableCollectionType conformance tests.
//===----------------------------------------------------------------------===//
% for array_type in all_array_types:
ArrayTestSuite.test("${array_type}/AssociatedTypes") {
typealias Collection = ${array_type}<OpaqueValue<Int>>
typealias CollectionSlice = ArraySlice<OpaqueValue<Int>>
expectCollectionAssociatedTypes(
collectionType: Collection.self,
iteratorType: IndexingIterator<Collection>.self,
subSequenceType: CollectionSlice.self,
indexType: Int.self,
indexDistanceType: Int.self,
indicesType: CountableRange<Int>.self)
}
% end
% for array_type in all_array_types:
% collection_or_slice = 'Slice' if 'Slice' in array_type else 'Collection'
do {
// `Array`, `ArraySlice`, and `ContiguousArrayBuffer` have no expectation of
// failure for advancing their indexes "out of bounds", because they are just
// `Int`.
var resiliencyChecks = CollectionMisuseResiliencyChecks.all
resiliencyChecks.creatingOutOfBoundsIndicesBehavior = .none
// Test MutableCollectionType conformance with value type elements.
ArrayTestSuite.addMutableRandomAccessCollectionTests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return ${array_type}(elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return ${array_type}(elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in
return ${array_type}(elements)
},
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks,
withUnsafeMutableBufferPointerIsSupported: true,
isFixedLengthCollection: false)
// Test MutableCollectionType conformance with reference type elements.
ArrayTestSuite.addMutableRandomAccessCollectionTests(
makeCollection: { (elements: [LifetimeTracked]) in
return ${array_type}(elements)
},
wrapValue: { (element: OpaqueValue<Int>) in
LifetimeTracked(element.value, identity: element.identity)
},
extractValue: { (element: LifetimeTracked) in
OpaqueValue(element.value, identity: element.identity)
},
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
// FIXME: use LifetimeTracked.
return ${array_type}(elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
makeCollectionOfComparable: { (elements: [MinimalComparableValue]) in
// FIXME: use LifetimeTracked.
return ${array_type}(elements)
},
wrapValueIntoComparable: identityComp,
extractValueFromComparable: identityComp,
resiliencyChecks: resiliencyChecks,
withUnsafeMutableBufferPointerIsSupported: true,
isFixedLengthCollection: false)
// Test RangeReplaceableCollectionType conformance with value type elements.
ArrayTestSuite.addRangeReplaceableRandomAccess${collection_or_slice}Tests(
makeCollection: { (elements: [OpaqueValue<Int>]) in
return ${array_type}(elements)
},
wrapValue: identity,
extractValue: identity,
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
return ${array_type}(elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks)
// Test RangeReplaceableCollectionType conformance with reference type elements.
ArrayTestSuite.addRangeReplaceableRandomAccess${collection_or_slice}Tests(
makeCollection: { (elements: [LifetimeTracked]) in
return ${array_type}(elements)
},
wrapValue: { (element: OpaqueValue<Int>) in LifetimeTracked(element.value) },
extractValue: { (element: LifetimeTracked) in OpaqueValue(element.value) },
makeCollectionOfEquatable: { (elements: [MinimalEquatableValue]) in
// FIXME: use LifetimeTracked.
return ${array_type}(elements)
},
wrapValueIntoEquatable: identityEq,
extractValueFromEquatable: identityEq,
resiliencyChecks: resiliencyChecks)
}
% end
runAllTests()