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
|
// RUN: %empty-directory(%t)
//
// RUN: %gyb %s -o %t/Runtime.swift
// RUN: %target-build-swift -parse-stdlib -module-name a -enable-experimental-feature Extern %t/Runtime.swift -o %t.out
// RUN: %target-codesign %t.out
// RUN: %target-run %t.out
// REQUIRES: executable_test
// REQUIRES: reflection
import Swift
import StdlibUnittest
import SwiftShims
#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(WASI)
import WASILibc
#elseif canImport(Android)
import Android
#elseif os(Windows)
import CRT
import WinSDK
#else
#error("Unsupported platform")
#endif
@_extern(c, "swift_demangle")
func _stdlib_demangleImpl(
mangledName: UnsafePointer<CChar>?,
mangledNameLength: UInt,
outputBuffer: UnsafeMutablePointer<CChar>?,
outputBufferSize: UnsafeMutablePointer<UInt>?,
flags: UInt32
) -> UnsafeMutablePointer<CChar>?
func _stdlib_demangleName(_ mangledName: String) -> String {
return mangledName.utf8CString.withUnsafeBufferPointer {
(mangledNameUTF8CStr) in
let demangledNamePtr = _stdlib_demangleImpl(
mangledName: mangledNameUTF8CStr.baseAddress,
mangledNameLength: UInt(mangledNameUTF8CStr.count - 1),
outputBuffer: nil,
outputBufferSize: nil,
flags: 0)
if let demangledNamePtr = demangledNamePtr {
let demangledName = String(cString: demangledNamePtr)
_swift_stdlib_free(demangledNamePtr)
return demangledName
}
return mangledName
}
}
var swiftObjectCanaryCount = 0
class SwiftObjectCanary {
init() {
swiftObjectCanaryCount += 1
}
deinit {
swiftObjectCanaryCount -= 1
}
}
struct SwiftObjectCanaryStruct {
var ref = SwiftObjectCanary()
}
var Runtime = TestSuite("Runtime")
Runtime.test("_canBeClass") {
expectEqual(1, _canBeClass(SwiftObjectCanary.self))
expectEqual(0, _canBeClass(SwiftObjectCanaryStruct.self))
typealias SwiftClosure = () -> ()
expectEqual(0, _canBeClass(SwiftClosure.self))
}
//===----------------------------------------------------------------------===//
// The protocol should be defined in the standard library, otherwise the cast
// does not work.
typealias P1 = CustomReflectable
typealias P2 = CustomStringConvertible
protocol Q1 {}
extension P1 {
var success: Bool {
print(String(describing: customMirror))
return String(describing: customMirror) == "Mirror for ()"
}
}
// A small struct that can be stored inline in an opaque buffer.
struct StructConformsToP1 : CustomReflectable, Q1 {
var customMirror: Mirror {
return Mirror(reflecting: ())
}
}
// A small struct that can be stored inline in an opaque buffer.
struct Struct2ConformsToP1<T : CustomReflectable> : CustomReflectable, Q1 {
init(_ value: T) {
self.value = value
}
var customMirror: Mirror {
return value.customMirror
}
var value: T
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct3ConformsToP2 : CustomStringConvertible, Q1 {
var a: UInt64 = 10
var b: UInt64 = 20
var c: UInt64 = 30
var d: UInt64 = 40
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = ""
result += _uint64ToString(a) + " "
result += _uint64ToString(b) + " "
result += _uint64ToString(c) + " "
result += _uint64ToString(d)
return result
}
}
// A large struct that cannot be stored inline in an opaque buffer.
struct Struct4ConformsToP2<T : CustomStringConvertible> : CustomStringConvertible, Q1 {
var value: T
var e: UInt64 = 50
var f: UInt64 = 60
var g: UInt64 = 70
var h: UInt64 = 80
init(_ value: T) {
self.value = value
}
var description: String {
// Don't rely on string interpolation, it uses the casts that we are trying
// to test.
var result = value.description + " "
result += _uint64ToString(e) + " "
result += _uint64ToString(f) + " "
result += _uint64ToString(g) + " "
result += _uint64ToString(h)
return result
}
}
struct StructDoesNotConformToP1 : Q1 {}
class ClassConformsToP1 : CustomReflectable, Q1 {
var customMirror: Mirror {
return Mirror(reflecting: ())
}
}
class Class2ConformsToP1<T : CustomReflectable> : CustomReflectable, Q1 {
init(_ value: T) {
self.value = [value]
}
var customMirror: Mirror {
return value[0].customMirror
}
// FIXME: should be "var value: T", but we don't support it now.
var value: Array<T>
}
class ClassDoesNotConformToP1 : Q1 {}
Runtime.test("dynamicCasting with as") {
let someP1Value = StructConformsToP1()
let someP1Value2 = Struct2ConformsToP1(StructConformsToP1())
let someNotP1Value = StructDoesNotConformToP1()
let someP2Value = Struct3ConformsToP2()
let someP2Value2 = Struct4ConformsToP2(Struct3ConformsToP2())
let someP1Ref = ClassConformsToP1()
let someP1Ref2 = Class2ConformsToP1(ClassConformsToP1())
let someNotP1Ref = ClassDoesNotConformToP1()
expectTrue(someP1Value is P1)
expectTrue(someP1Value2 is P1)
expectFalse(someNotP1Value is P1)
expectTrue(someP2Value is P2)
expectTrue(someP2Value2 is P2)
expectTrue(someP1Ref is P1)
expectTrue(someP1Ref2 is P1)
expectFalse(someNotP1Ref is P1)
expectTrue(someP1Value as P1 is P1)
expectTrue(someP1Value2 as P1 is P1)
expectTrue(someP2Value as P2 is P2)
expectTrue(someP2Value2 as P2 is P2)
expectTrue(someP1Ref as P1 is P1)
expectTrue(someP1Value as Q1 is P1)
expectTrue(someP1Value2 as Q1 is P1)
expectFalse(someNotP1Value as Q1 is P1)
expectTrue(someP2Value as Q1 is P2)
expectTrue(someP2Value2 as Q1 is P2)
expectTrue(someP1Ref as Q1 is P1)
expectTrue(someP1Ref2 as Q1 is P1)
expectFalse(someNotP1Ref as Q1 is P1)
expectTrue(someP1Value as Any is P1)
expectTrue(someP1Value2 as Any is P1)
expectFalse(someNotP1Value as Any is P1)
expectTrue(someP2Value as Any is P2)
expectTrue(someP2Value2 as Any is P2)
expectTrue(someP1Ref as Any is P1)
expectTrue(someP1Ref2 as Any is P1)
expectFalse(someNotP1Ref as Any is P1)
expectTrue(someP1Ref as AnyObject is P1)
expectTrue(someP1Ref2 as AnyObject is P1)
expectFalse(someNotP1Ref as AnyObject is P1)
expectTrue((someP1Value as P1).success)
expectTrue((someP1Value2 as P1).success)
expectEqual("10 20 30 40", (someP2Value as P2).description)
expectEqual("10 20 30 40 50 60 70 80", (someP2Value2 as P2).description)
expectTrue((someP1Ref as P1).success)
expectTrue((someP1Ref2 as P1).success)
expectTrue(((someP1Value as Q1) as! P1).success)
expectTrue(((someP1Value2 as Q1) as! P1).success)
expectEqual("10 20 30 40", ((someP2Value as Q1) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as! P2).description)
expectTrue(((someP1Ref as Q1) as! P1).success)
expectTrue(((someP1Ref2 as Q1) as! P1).success)
expectTrue(((someP1Value as Any) as! P1).success)
expectTrue(((someP1Value2 as Any) as! P1).success)
expectEqual("10 20 30 40", ((someP2Value as Any) as! P2).description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as! P2).description)
expectTrue(((someP1Ref as Any) as! P1).success)
expectTrue(((someP1Ref2 as Any) as! P1).success)
expectTrue(((someP1Ref as AnyObject) as! P1).success)
expectNil((someNotP1Value as? P1))
expectNil((someNotP1Ref as? P1))
expectTrue(((someP1Value as Q1) as? P1)!.success)
expectTrue(((someP1Value2 as Q1) as? P1)!.success)
expectNil(((someNotP1Value as Q1) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Q1) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Q1) as? P2)!.description)
expectTrue(((someP1Ref as Q1) as? P1)!.success)
expectTrue(((someP1Ref2 as Q1) as? P1)!.success)
expectNil(((someNotP1Ref as Q1) as? P1))
expectTrue(((someP1Value as Any) as? P1)!.success)
expectTrue(((someP1Value2 as Any) as? P1)!.success)
expectNil(((someNotP1Value as Any) as? P1))
expectEqual("10 20 30 40", ((someP2Value as Any) as? P2)!.description)
expectEqual("10 20 30 40 50 60 70 80",
((someP2Value2 as Any) as? P2)!.description)
expectTrue(((someP1Ref as Any) as? P1)!.success)
expectTrue(((someP1Ref2 as Any) as? P1)!.success)
expectNil(((someNotP1Ref as Any) as? P1))
expectTrue(((someP1Ref as AnyObject) as? P1)!.success)
expectTrue(((someP1Ref2 as AnyObject) as? P1)!.success)
expectNil(((someNotP1Ref as AnyObject) as? P1))
let doesThrow: (Int) throws -> Int = { $0 }
let doesNotThrow: (String) -> String = { $0 }
_ = doesThrow
expectTrue(doesThrow as Any is (Int) throws -> Int)
expectFalse(doesThrow as Any is (String) throws -> Int)
expectFalse(doesThrow as Any is (String) throws -> String)
expectFalse(doesThrow as Any is (Int) throws -> String)
expectFalse(doesThrow as Any is (Int) -> Int)
expectFalse(doesThrow as Any is (String) throws -> String)
expectFalse(doesThrow as Any is (String) -> String)
expectTrue(doesNotThrow as Any is (String) throws -> String)
expectTrue(doesNotThrow as Any is (String) -> String)
expectFalse(doesNotThrow as Any is (Int) -> String)
expectFalse(doesNotThrow as Any is (Int) -> Int)
expectFalse(doesNotThrow as Any is (String) -> Int)
expectFalse(doesNotThrow as Any is (Int) throws -> Int)
expectFalse(doesNotThrow as Any is (Int) -> Int)
}
extension Int {
class ExtensionClassConformsToP2 : P2 {
var description: String { return "abc" }
}
fileprivate class PrivateExtensionClassConformsToP2 : P2 {
var description: String { return "def" }
}
}
Runtime.test("dynamic cast to existential with cross-module extensions") {
let internalObj = Int.ExtensionClassConformsToP2()
let privateObj = Int.PrivateExtensionClassConformsToP2()
expectTrue(internalObj is P2)
expectTrue(privateObj is P2)
}
class SomeClass {}
struct SomeStruct {}
enum SomeEnum {
case A
init() { self = .A }
}
Runtime.test("typeName") {
expectEqual("a.SomeClass", _typeName(SomeClass.self))
expectEqual("a.SomeStruct", _typeName(SomeStruct.self))
expectEqual("a.SomeEnum", _typeName(SomeEnum.self))
expectEqual("Any.Protocol", _typeName(Any.Protocol.self))
expectEqual("Swift.AnyObject.Protocol", _typeName(AnyObject.Protocol.self))
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(AnyClass.Protocol.self))
expectEqual("Swift.Optional<Swift.AnyObject>.Type", _typeName((AnyObject?).Type.self))
var a: Any = SomeClass()
expectEqual("a.SomeClass", _typeName(type(of: a)))
a = SomeStruct()
expectEqual("a.SomeStruct", _typeName(type(of: a)))
a = SomeEnum()
expectEqual("a.SomeEnum", _typeName(type(of: a)))
a = AnyObject.self
expectEqual("Swift.AnyObject.Protocol", _typeName(type(of: a)))
a = AnyClass.self
expectEqual("Swift.AnyObject.Type.Protocol", _typeName(type(of: a)))
a = (AnyObject?).self
expectEqual("Swift.Optional<Swift.AnyObject>.Type",
_typeName(type(of: a)))
a = Any.self
expectEqual("Any.Protocol", _typeName(type(of: a)))
}
class SomeSubclass : SomeClass {}
protocol SomeProtocol {}
class SomeConformingClass : SomeProtocol {}
class SomeConformingSubclass : SomeConformingClass {}
class UnicodeCläss {}
Runtime.test("typeByName") {
expectTrue(_typeByName("a.SomeClass") == SomeClass.self)
expectTrue(_typeByName("a.SomeSubclass") == SomeSubclass.self)
// name lookup will be via protocol conformance table
expectTrue(_typeByName("a.SomeConformingClass") == SomeConformingClass.self)
expectTrue(_typeByName("a.UnicodeCläss") == UnicodeCläss.self)
}
Runtime.test("demangleName") {
expectEqual("", _stdlib_demangleName(""))
expectEqual("abc", _stdlib_demangleName("abc"))
expectEqual("\0", _stdlib_demangleName("\0"))
expectEqual("Swift.Double", _stdlib_demangleName("$sSdD"))
expectEqual("x.a : x.Foo<x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>, x.Foo<x.Foo<Swift.Int, Swift.Int>, x.Foo<Swift.Int, Swift.Int>>>",
_stdlib_demangleName("$s1x1aAA3FooCyADyADySiSiGADySiSiGGADyADySiSiGADySiSiGGGvp"))
expectEqual("Foobar", _stdlib_demangleName("$s13__lldb_expr_46FoobarCD"))
}
if #available(macOS 11.0, iOS 14.0, tvOS 14.0, watchOS 7.0, visionOS 1.0, *) {
Runtime.test("demangleTruncate") {
// Swift.Int requires 10 bytes to be fully demangled.
let buffer = UnsafeMutableBufferPointer<Int8>.allocate(capacity: 10)
defer { buffer.deallocate() }
// Set last byte to a custom number, that way when we call swift_demangle
// the last byte should be unchanged rather than it being set to 0.
buffer[buffer.count - 1] = 16
// Only give 9 bytes though to exercise that swift_demangle doesn't write past
// the buffer.
var bufferSize = UInt(buffer.count - 1)
let mangled = "$sSi"
mangled.utf8CString.withUnsafeBufferPointer {
_ = _stdlib_demangleImpl(
mangledName: $0.baseAddress,
mangledNameLength: UInt($0.count - 1),
outputBuffer: buffer.baseAddress,
outputBufferSize: &bufferSize,
flags: 0
)
}
expectEqual(String(cString: buffer.baseAddress!), "Swift.In")
expectEqual(bufferSize, 10)
expectEqual(buffer[buffer.count - 1], 16)
}
}
% for optionality in ['', '?']:
Runtime.test("_stdlib_atomicCompareExchangeStrongPtr") {
typealias IntPtr = UnsafeMutablePointer<Int>
let origP1: IntPtr${optionality} = IntPtr(bitPattern: 0x10101010)!
let origP2: IntPtr${optionality} = IntPtr(bitPattern: 0x20202020)!
let origP3: IntPtr${optionality} = IntPtr(bitPattern: 0x30303030)!
do {
var object = origP1
var expected = origP1
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, object)
expectEqual(origP1, expected)
}
do {
var object = origP1
var expected = origP2
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &object, expected: &expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, object)
expectEqual(origP1, expected)
}
struct FooStruct {
var i: Int
var object: IntPtr${optionality}
var expected: IntPtr${optionality}
init(object: IntPtr${optionality}, expected: IntPtr${optionality}) {
self.i = 0
self.object = object
self.expected = expected
}
}
do {
var foo = FooStruct(object: origP1, expected: origP1)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP2)
expectTrue(r)
expectEqual(origP2, foo.object)
expectEqual(origP1, foo.expected)
}
do {
var foo = FooStruct(object: origP1, expected: origP2)
let r = _stdlib_atomicCompareExchangeStrongPtr(
object: &foo.object, expected: &foo.expected, desired: origP3)
expectFalse(r)
expectEqual(origP1, foo.object)
expectEqual(origP1, foo.expected)
}
}
% end
Runtime.test("casting AnyObject to class metatypes") {
do {
let ao: AnyObject = SomeClass()
expectTrue(ao as? Any.Type == nil)
expectTrue(ao as? AnyClass == nil)
}
do {
var a: Any = SomeClass()
expectTrue(a as? Any.Type == nil)
expectTrue(a as? AnyClass == nil)
a = SomeClass.self
expectTrue(a as? Any.Type == SomeClass.self)
expectTrue(a as? AnyClass == SomeClass.self)
expectTrue(a as? SomeClass.Type == SomeClass.self)
}
}
func wantonlyWrapInAny<T>(_ x: T) -> Any {
return x
}
// Because `type(of: x)` and `T.self` have the same type `T.Type` in
// a <T>(x: T) context, both operations must produce the concrete protocol
// type value when `T` is bound to an existential type `P`.
func castWithAbstractionBarrier<T>(_ x: T) -> (
staticWithConcreteType: T.Type,
dynamicWithConcreteType: T.Type,
staticWithErasedType: Any.Type,
dynamicWithErasedType: Any.Type,
dynamicExistentialWithErasedType: Any.Type,
dynamicDoubleWrappedExistentialWithErasedType: Any.Type
) {
return (
staticWithConcreteType: T.self,
dynamicWithConcreteType: type(of: x),
staticWithErasedType: T.self,
dynamicWithErasedType: type(of: x),
dynamicExistentialWithErasedType: type(of: x as Any),
dynamicDoubleWrappedExistentialWithErasedType:
type(of: wantonlyWrapInAny(wantonlyWrapInAny(x)))
)
}
Runtime.test("abstraction barrier on casting generic param bound to existential") {
let c: SomeConformingClass = SomeConformingSubclass()
let x: SomeProtocol = c
let (staticWithConcreteType,
dynamicWithConcreteType,
staticWithErasedType,
dynamicWithErasedType,
dynamicExistentialWithErasedType,
dynamicDoubleWrappedExistentialWithErasedType)
= castWithAbstractionBarrier(x as SomeProtocol)
expectTrue(staticWithConcreteType == SomeProtocol.self)
expectTrue(dynamicWithConcreteType == SomeProtocol.self)
expectTrue(staticWithErasedType == SomeProtocol.self)
expectTrue(dynamicWithErasedType == SomeProtocol.self)
// type(of: x as Any) can be a proper existential type cast
expectTrue(dynamicExistentialWithErasedType == SomeConformingSubclass.self)
expectTrue(dynamicDoubleWrappedExistentialWithErasedType
== SomeConformingSubclass.self)
}
class Malkovich: Malkovichable {
var malkovich: String { return "malkovich" }
}
protocol Malkovichable: AnyObject {
var malkovich: String { get }
}
struct GenericStructWithReferenceStorage<T> {
var a: T
unowned(safe) var unownedConcrete: Malkovich
unowned(unsafe) var unmanagedConcrete: Malkovich
weak var weakConcrete: Malkovich?
unowned(safe) var unownedProto: Malkovichable
unowned(unsafe) var unmanagedProto: Malkovichable
weak var weakProto: Malkovichable?
}
func exerciseReferenceStorageInGenericContext<T>(
_ x: GenericStructWithReferenceStorage<T>,
forceCopy y: GenericStructWithReferenceStorage<T>
) {
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
expectEqual(y.unownedConcrete.malkovich, "malkovich")
expectEqual(y.unmanagedConcrete.malkovich, "malkovich")
expectEqual(y.weakConcrete!.malkovich, "malkovich")
expectEqual(y.unownedProto.malkovich, "malkovich")
expectEqual(y.unmanagedProto.malkovich, "malkovich")
expectEqual(y.weakProto!.malkovich, "malkovich")
}
Runtime.test("Struct layout with reference storage types") {
let malkovich = Malkovich()
let x = GenericStructWithReferenceStorage(a: malkovich,
unownedConcrete: malkovich,
unmanagedConcrete: malkovich,
weakConcrete: malkovich,
unownedProto: malkovich,
unmanagedProto: malkovich,
weakProto: malkovich)
exerciseReferenceStorageInGenericContext(x, forceCopy: x)
expectEqual(x.unownedConcrete.malkovich, "malkovich")
expectEqual(x.unmanagedConcrete.malkovich, "malkovich")
expectEqual(x.weakConcrete!.malkovich, "malkovich")
expectEqual(x.unownedProto.malkovich, "malkovich")
expectEqual(x.unmanagedProto.malkovich, "malkovich")
expectEqual(x.weakProto!.malkovich, "malkovich")
// Make sure malkovich lives long enough.
print(malkovich)
}
var Reflection = TestSuite("Reflection")
func wrap1 (_ x: Any) -> Any { return x }
func wrap2<T>(_ x: T) -> Any { return wrap1(x) }
func wrap3 (_ x: Any) -> Any { return wrap2(x) }
func wrap4<T>(_ x: T) -> Any { return wrap3(x) }
func wrap5 (_ x: Any) -> Any { return wrap4(x) }
class JustNeedAMetatype {}
Reflection.test("nested existential containers") {
let wrapped = wrap5(JustNeedAMetatype.self)
expectEqual("\(wrapped)", "JustNeedAMetatype")
}
Reflection.test("dumpToAStream") {
var output = ""
dump([ 42, 4242 ], to: &output)
expectEqual("▿ 2 elements\n - 42\n - 4242\n", output)
}
class Brilliant {
let first: Int
let second: String
init(_ fst: Int, _ snd: String) {
self.first = fst
self.second = snd
}
}
Reflection.test("ObjectIdentifier/Hashable,Comparable") {
// Check that object identifiers are unique to class instances.
let a = Brilliant(1, "")
let b = Brilliant(2, "")
let c = Brilliant(3, "")
checkHashable(
[a, b, c].map(ObjectIdentifier.init),
equalityOracle: { $0 == $1 })
// Comparable
func isComparable<X : Comparable>(_ x: X) {}
isComparable(ObjectIdentifier(a))
// Check the ObjectIdentifier created is stable
expectTrue(
(ObjectIdentifier(a) < ObjectIdentifier(b))
!= (ObjectIdentifier(a) > ObjectIdentifier(b)))
expectFalse(
ObjectIdentifier(a) >= ObjectIdentifier(b)
&& ObjectIdentifier(a) <= ObjectIdentifier(b))
// Check that ordering is transitive.
expectEqual(
[ ObjectIdentifier(a), ObjectIdentifier(b), ObjectIdentifier(c) ].sorted(),
[ ObjectIdentifier(c), ObjectIdentifier(b), ObjectIdentifier(a) ].sorted())
}
Reflection.test("ObjectIdentifier/CustomDebugStringConvertible") {
let obj1 = Brilliant(1, "")
let obj2 = Brilliant(2, "")
let oi1 = ObjectIdentifier(obj1)
let oi2 = ObjectIdentifier(obj2)
expectEqual(String(reflecting: oi1), String(reflecting: oi1))
expectNotEqual(String(reflecting: oi1), String(reflecting: oi2))
let p1 = UnsafeRawPointer(bitPattern: UInt(bitPattern: oi1))!
expectPrinted("ObjectIdentifier(\(p1))", oi1)
let p2 = UnsafeRawPointer(bitPattern: Int(bitPattern: oi1))!
expectPrinted("ObjectIdentifier(\(p2))", oi1)
}
class C: Q1 & Codable { }
Reflection.test("multiprotocolTypes") {
// https://github.com/apple/swift/issues/50690
// EXC_BAD_ACCESS when calling 'type(of:)' on protocol composition with
// 'Codable'
//
// This use of String(reflecting:) exercises a previously incorrect cast in
// NonFixedExistentialMetatypeBox::Container::getNumWitnessTables.
let obj: Q1 & Codable = C()
let t = type(of: obj)
let x = String(reflecting: t)
expectEqual("a.C", x)
}
var BitTwiddlingTestSuite = TestSuite("BitTwiddling")
BitTwiddlingTestSuite.test("_pointerSize") {
#if _pointerBitWidth(_32)
expectEqual(4, MemoryLayout<Optional<AnyObject>>.size)
#elseif _pointerBitWidth(_64)
expectEqual(8, MemoryLayout<Optional<AnyObject>>.size)
#else
fatalError("implement")
#endif
}
BitTwiddlingTestSuite.test("_isPowerOf2/Int") {
func asInt(_ a: Int) -> Int { return a }
expectFalse(_isPowerOf2(asInt(-1025)))
expectFalse(_isPowerOf2(asInt(-1024)))
expectFalse(_isPowerOf2(asInt(-1023)))
expectFalse(_isPowerOf2(asInt(-4)))
expectFalse(_isPowerOf2(asInt(-3)))
expectFalse(_isPowerOf2(asInt(-2)))
expectFalse(_isPowerOf2(asInt(-1)))
expectFalse(_isPowerOf2(asInt(0)))
expectTrue(_isPowerOf2(asInt(1)))
expectTrue(_isPowerOf2(asInt(2)))
expectFalse(_isPowerOf2(asInt(3)))
expectTrue(_isPowerOf2(asInt(1024)))
#if _pointerBitWidth(_32)
// Not applicable to 32-bit architectures.
#elseif _pointerBitWidth(_64)
expectTrue(_isPowerOf2(asInt(0x8000_0000)))
#else
fatalError("implement")
#endif
expectFalse(_isPowerOf2(Int.min))
expectFalse(_isPowerOf2(Int.max))
}
BitTwiddlingTestSuite.test("_isPowerOf2/UInt") {
func asUInt(_ a: UInt) -> UInt { return a }
expectFalse(_isPowerOf2(asUInt(0)))
expectTrue(_isPowerOf2(asUInt(1)))
expectTrue(_isPowerOf2(asUInt(2)))
expectFalse(_isPowerOf2(asUInt(3)))
expectTrue(_isPowerOf2(asUInt(1024)))
expectTrue(_isPowerOf2(asUInt(0x8000_0000)))
expectFalse(_isPowerOf2(UInt.max))
}
var AvailabilityVersionsTestSuite = TestSuite("AvailabilityVersions")
AvailabilityVersionsTestSuite.test("_stdlib_isOSVersionAtLeast") {
func isAtLeastOS(_ major: Int, _ minor: Int, _ patch: Int) -> Bool {
return Bool(_builtinBooleanLiteral: _stdlib_isOSVersionAtLeast(
major._builtinWordValue,
minor._builtinWordValue,
patch._builtinWordValue))
}
// _stdlib_isOSVersionAtLeast is broken for
// watchOS. rdar://problem/20234735
#if canImport(Darwin) && _runtime(_ObjC)
// This test assumes that no version component on an OS we test upon
// will ever be greater than 1066 and that every major version will always
// be greater than 1.
#if !targetEnvironment(macCatalyst)
expectFalse(isAtLeastOS(1066, 0, 0))
expectTrue(isAtLeastOS(0, 1066, 0))
expectTrue(isAtLeastOS(0, 0, 1066))
#endif
// When using a runtime that's not part of the OS, 9999 is a special version
// that's always available. The _swift_classIsSwiftMask symbol is absent in OS
// libraries, so detect based on that.
let RTLD_DEFAULT = UnsafeMutableRawPointer(bitPattern: -2)
let _swift_classIsSwiftMaskPtr = dlsym(RTLD_DEFAULT, "_swift_classIsSwiftMask")
if _swift_classIsSwiftMaskPtr != nil {
expectTrue(isAtLeastOS(9999, 0, 0))
}
#endif
}
runAllTests()
|