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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151
|
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2023 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 Swift project authors
//
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// - Parameters:
/// - condition: The condition to be evaluated.
/// - expression: The expression, corresponding to `condition`, that is being
/// evaluated (if available at compile time.)
/// - expressionWithCapturedRuntimeValues: The expression, corresponding to
/// `condition` and with runtime values captured, that is being evaluated
/// (if available at compile time.)
/// - difference: The difference between the operands in `condition`, if
/// available. Most callers should pass `nil`.
/// - comments: An array of comments describing the expectation. This array
/// may be empty.
/// - isRequired: Whether or not the expectation is required. The value of
/// this argument does not affect whether or not an error is thrown on
/// failure.
/// - sourceLocation: The source location of the expectation.
///
/// - Returns: A `Result<Void, any Error>`. If `condition` is `true`, the result
/// is `.success`. If `condition` is `false`, the result is an instance of
/// ``ExpectationFailedError`` describing the failure.
///
/// If the condition evaluates to `false`, an ``Issue`` is recorded for the test
/// that is running in the current task.
///
/// The odd error-handling convention in this function is necessary so that we
/// don't accidentally suppress errors thrown from subexpressions inside the
/// condition. For example, assuming there is a function
/// `func f() throws -> Bool`, the following calls should _not_ throw an
/// instance of ``ExpectationFailedError``, but should also not prevent an error
/// from being thrown by `f()`:
///
/// ```swift
/// try #expect(f))
/// #expect(try f())
/// ```
///
/// And the following call should generate a compile-time error:
///
/// ```swift
/// #expect(f()) // ERROR: Call can throw but is not marked with 'try'
/// ```
///
/// By _returning_ the error this function "throws", we can customize whether or
/// not we throw that error during macro resolution without affecting any errors
/// thrown by the condition expression passed to it.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkValue(
_ condition: Bool,
expression: __Expression,
expressionWithCapturedRuntimeValues: @autoclosure () -> __Expression? = nil,
mismatchedErrorDescription: @autoclosure () -> String? = nil,
difference: @autoclosure () -> String? = nil,
mismatchedExitConditionDescription: @autoclosure () -> String? = nil,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> {
// If the expression being evaluated is a negation (!x instead of x), flip
// the condition here so that we evaluate it in the correct sense. We loop
// in case of multiple prefix operators (!!(a == b), for example.)
var condition = condition
do {
var expression: __Expression? = expression
while case let .negation(subexpression, _) = expression?.kind {
defer {
expression = subexpression
}
condition = !condition
}
}
// Capture the correct expression in the expectation.
var expression = expression
if !condition, let expressionWithCapturedRuntimeValues = expressionWithCapturedRuntimeValues() {
expression = expressionWithCapturedRuntimeValues
if expression.runtimeValue == nil, case .negation = expression.kind {
expression = expression.capturingRuntimeValue(condition)
}
}
// Post an event for the expectation regardless of whether or not it passed.
// If the current event handler is not configured to handle events of this
// kind, this event is discarded.
lazy var expectation = Expectation(evaluatedExpression: expression, isPassing: condition, isRequired: isRequired, sourceLocation: sourceLocation)
if Configuration.deliverExpectationCheckedEvents {
Event.post(.expectationChecked(expectation))
}
// Early exit if the expectation passed.
if condition {
return .success(())
}
// Since this expectation failed, populate its optional fields which are
// only evaluated and included lazily upon failure.
expectation.mismatchedErrorDescription = mismatchedErrorDescription()
expectation.differenceDescription = difference()
expectation.mismatchedExitConditionDescription = mismatchedExitConditionDescription()
// Ensure the backtrace is captured here so it has fewer extraneous frames
// from the testing framework which aren't relevant to the user.
let backtrace = Backtrace.current()
Issue.record(.expectationFailed(expectation), comments: comments(), backtrace: backtrace, sourceLocation: sourceLocation)
return .failure(ExpectationFailedError(expectation: expectation))
}
// MARK: - Binary operators
/// Call a binary operator, passing the left-hand and right-hand arguments.
///
/// - Parameters:
/// - lhs: The left-hand argument to `op`.
/// - op: The binary operator to call.
/// - rhs: The right-hand argument to `op`. This closure may be invoked zero
/// or one time, but not twice or more.
///
/// - Returns: A tuple containing the result of calling `op` and the value of
/// `rhs` (or `nil` if it was not evaluated.)
///
/// - Throws: Whatever is thrown by `op`.
private func _callBinaryOperator<T, U, R>(
_ lhs: T,
_ op: (T, () -> U) -> R,
_ rhs: () -> U
) -> (result: R, rhs: U?) {
// The compiler normally doesn't allow a nonescaping closure to call another
// nonescaping closure, but our use cases are safe (e.g. `true && false`) and
// we cannot force one function or the other to be escaping. Use
// withoutActuallyEscaping() to tell the compiler that what we're doing is
// okay. SEE: https://github.com/swiftlang/swift-evolution/blob/main/proposals/0176-enforce-exclusive-access-to-memory.md#restrictions-on-recursive-uses-of-non-escaping-closures
var rhsValue: U?
let result: R = withoutActuallyEscaping(rhs) { rhs in
op(lhs, {
if rhsValue == nil {
rhsValue = rhs()
}
return rhsValue!
})
}
return (result, rhsValue)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used by binary operators such as `>`:
///
/// ```swift
/// #expect(2 > 1)
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkBinaryOperation<T, U>(
_ lhs: T, _ op: (T, () -> U) -> Bool, _ rhs: @autoclosure () -> U,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> {
let (condition, rhs) = _callBinaryOperator(lhs, op, rhs)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, rhs),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
// MARK: - Function calls
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used by function calls:
///
/// ```swift
/// #expect(x.update(i))
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, each U>(
_ lhs: T, calling functionCall: (T, repeat each U) throws -> Bool, _ arguments: repeat each U,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<Void, any Error> {
let condition = try functionCall(lhs, repeat each arguments)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, repeat each arguments),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
#if !SWT_FIXED_122011759
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0>(
_ lhs: T, calling functionCall: (T, Arg0) throws -> Bool, _ argument0: Arg0,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<Void, any Error> {
let condition = try functionCall(lhs, argument0)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0, Arg1>(
_ lhs: T, calling functionCall: (T, Arg0, Arg1) throws -> Bool, _ argument0: Arg0, _ argument1: Arg1,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<Void, any Error> {
let condition = try functionCall(lhs, argument0, argument1)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0, argument1),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0, Arg1, Arg2>(
_ lhs: T, calling functionCall: (T, Arg0, Arg1, Arg2) throws -> Bool, _ argument0: Arg0, _ argument1: Arg1, _ argument2: Arg2,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<Void, any Error> {
let condition = try functionCall(lhs, argument0, argument1, argument2)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0, argument1, argument2),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0, Arg1, Arg2, Arg3>(
_ lhs: T, calling functionCall: (T, Arg0, Arg1, Arg2, Arg3) throws -> Bool, _ argument0: Arg0, _ argument1: Arg1, _ argument2: Arg2, _ argument3: Arg3,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<Void, any Error> {
let condition = try functionCall(lhs, argument0, argument1, argument2, argument3)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0, argument1, argument2, argument3),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
#endif
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used by function calls where the arguments are all `inout`:
///
/// ```swift
/// #expect(x.update(&i))
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkInoutFunctionCall<T, /*each*/ U>(
_ lhs: T, calling functionCall: (T, inout /*repeat each*/ U) throws -> Bool, _ arguments: inout /*repeat each*/ U,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<Void, any Error> {
let condition = try functionCall(lhs, /*repeat each*/ &arguments)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, /*repeat each*/ arguments),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used to conditionally unwrap optional values produced from
/// expanded function calls:
///
/// ```swift
/// let z = try #require(x.update(i))
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, each U, R>(
_ lhs: T, calling functionCall: (T, repeat each U) throws -> R?, _ arguments: repeat each U,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<R, any Error> {
let optionalValue = try functionCall(lhs, repeat each arguments)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, repeat each arguments),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
#if !SWT_FIXED_122011759
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0, R>(
_ lhs: T, calling functionCall: (T, Arg0) throws -> R?, _ argument0: Arg0,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<R, any Error> {
let optionalValue = try functionCall(lhs, argument0)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0, Arg1, R>(
_ lhs: T, calling functionCall: (T, Arg0, Arg1) throws -> R?, _ argument0: Arg0, _ argument1: Arg1,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<R, any Error> {
let optionalValue = try functionCall(lhs, argument0, argument1)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0, argument1),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0, Arg1, Arg2, R>(
_ lhs: T, calling functionCall: (T, Arg0, Arg1, Arg2) throws -> R?, _ argument0: Arg0, _ argument1: Arg1, _ argument2: Arg2,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<R, any Error> {
let optionalValue = try functionCall(lhs, argument0, argument1, argument2)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0, argument1, argument2),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload works around a bug in variadic generics that may cause a
/// miscompile when an argument to a function is a C string converted from a
/// Swift string (e.g. the arguments to `fopen("/file/path", "wb")`.)
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkFunctionCall<T, Arg0, Arg1, Arg2, Arg3, R>(
_ lhs: T, calling functionCall: (T, Arg0, Arg1, Arg2, Arg3) throws -> R?, _ argument0: Arg0, _ argument1: Arg1, _ argument2: Arg2, _ argument3: Arg3,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<R, any Error> {
let optionalValue = try functionCall(lhs, argument0, argument1, argument2, argument3)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, argument0, argument1, argument2, argument3),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
#endif
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used to conditionally unwrap optional values produced from
/// expanded function calls where the arguments are all `inout`:
///
/// ```swift
/// let z = try #require(x.update(&i))
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkInoutFunctionCall<T, /*each*/ U, R>(
_ lhs: T, calling functionCall: (T, inout /*repeat each*/ U) throws -> R?, _ arguments: inout /*repeat each*/ U,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) rethrows -> Result<R, any Error> {
let optionalValue = try functionCall(lhs, /*repeat each*/ &arguments)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, /*repeat each*/ arguments),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
// MARK: - Property access
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used by property accesses:
///
/// ```swift
/// #expect(x.isFoodTruck)
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkPropertyAccess<T>(
_ lhs: T, getting memberAccess: (T) -> Bool,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> {
let condition = memberAccess(lhs)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, condition),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used to conditionally unwrap optional values produced from
/// expanded property accesses:
///
/// ```swift
/// let z = try #require(x.nearestFoodTruck)
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkPropertyAccess<T, U>(
_ lhs: T, getting memberAccess: (T) -> U?,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<U, any Error> {
let optionalValue = memberAccess(lhs)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, optionalValue as U??),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
// MARK: - Collection diffing
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used to implement difference-reporting support when
/// comparing collections.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkBinaryOperation<T>(
_ lhs: T, _ op: (T, () -> T) -> Bool, _ rhs: @autoclosure () -> T,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> where T: BidirectionalCollection, T.Element: Equatable {
let (condition, rhs) = _callBinaryOperator(lhs, op, rhs)
func difference() -> String? {
guard let rhs else {
return nil
}
let difference = lhs.difference(from: rhs)
let insertions = difference.insertions.map(\.element)
let removals = difference.removals.map(\.element)
switch (!insertions.isEmpty, !removals.isEmpty) {
case (true, true):
return "inserted \(insertions), removed \(removals)"
case (true, false):
return "inserted \(insertions)"
case (false, true):
return "removed \(removals)"
case (false, false):
return ""
}
}
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, rhs),
difference: difference(),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is necessary because `String` satisfies the requirements for
/// the difference-calculating overload above, but the output from that overload
/// may be unexpectedly complex.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkBinaryOperation(
_ lhs: String, _ op: (String, () -> String) -> Bool, _ rhs: @autoclosure () -> String,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> {
let (condition, rhs) = _callBinaryOperator(lhs, op, rhs)
return __checkValue(
condition,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs, rhs),
difference: nil,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used for `v is T` expressions.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkCast<V, T>(
_ value: V,
is _: T.Type,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> {
return __checkValue(
value is T,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(value, type(of: value as Any)),
difference: nil,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
// MARK: - Optional unwrapping
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used to conditionally unwrap optional values:
///
/// ```swift
/// let x: Int? = ...
/// let y = try #require(x)
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkValue<T>(
_ optionalValue: T?,
expression: __Expression,
expressionWithCapturedRuntimeValues: @autoclosure () -> __Expression? = nil,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<T, any Error> {
// The double-optional below is because capturingRuntimeValue() takes optional
// values and interprets nil as "no value available". Rather, if optionalValue
// is `nil`, we want to actually store `nil` as the expression's evaluated
// value. The outer optional satisfies the generic constraint of
// capturingRuntimeValue(), and the inner optional represents the actual value
// (`nil`) that will be captured.
__checkValue(
optionalValue != nil,
expression: expression,
expressionWithCapturedRuntimeValues: (expressionWithCapturedRuntimeValues() ?? expression).capturingRuntimeValue(optionalValue as T??),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
).map {
optionalValue.unsafelyUnwrapped
}
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used to conditionally unwrap optional values using the `??`
/// operator:
///
/// ```swift
/// let x: Int? = ...
/// let y: Int? = ...
/// let z = try #require(x ?? y)
/// ```
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkBinaryOperation<T>(
_ lhs: T?, _ op: (T?, () -> T?) -> T?, _ rhs: @autoclosure () -> T?,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<T, any Error> {
let (optionalValue, rhs) = _callBinaryOperator(lhs, op, rhs)
return __checkValue(
optionalValue,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(lhs as T??, rhs as T??),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
/// This overload is used for `v as? T` expressions.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkCast<V, T>(
_ value: V,
as _: T.Type,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<T, any Error> {
// NOTE: this call to __checkValue() does not go through the optional
// bottleneck because we do not want to capture the nil value on failure (it
// looks odd in test output.)
let optionalValue = value as? T
return __checkValue(
optionalValue != nil,
expression: expression,
expressionWithCapturedRuntimeValues: expression.capturingRuntimeValues(value, type(of: value as Any)),
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
).map {
optionalValue.unsafelyUnwrapped
}
}
// MARK: - Matching errors by type
/// Check that an expression always throws an error.
///
/// This overload is used for `#expect(throws:) { }` invocations that take error
/// types.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall<E>(
throws errorType: E.Type,
performing body: () throws -> some Any,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> where E: Error {
if errorType == Never.self {
__checkClosureCall(
throws: Never.self,
performing: body,
expression: expression,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
} else {
__checkClosureCall(
performing: body,
throws: { $0 is E },
mismatchExplanation: { "expected error of type \(errorType), but \(_description(of: $0)) was thrown instead" },
expression: expression,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
}
/// Check that an expression always throws an error.
///
/// This overload is used for `await #expect(throws:) { }` invocations that take
/// error types.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall<E>(
throws errorType: E.Type,
performing body: () async throws -> sending some Any,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
isolation: isolated (any Actor)? = #isolation,
sourceLocation: SourceLocation
) async -> Result<Void, any Error> where E: Error {
if errorType == Never.self {
await __checkClosureCall(
throws: Never.self,
performing: body,
expression: expression,
comments: comments(),
isRequired: isRequired,
isolation: isolation,
sourceLocation: sourceLocation
)
} else {
await __checkClosureCall(
performing: body,
throws: { $0 is E },
mismatchExplanation: { "expected error of type \(errorType), but \(_description(of: $0)) was thrown instead" },
expression: expression,
comments: comments(),
isRequired: isRequired,
isolation: isolation,
sourceLocation: sourceLocation
)
}
}
// MARK: - Matching Never.self
/// Check that an expression never throws an error.
///
/// This overload is used for `#expect(throws: Never.self) { }`. It cannot be
/// implemented directly in terms of the other overloads because it checks for
/// the _absence_ of an error rather than an error that matches some predicate.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall(
throws _: Never.Type,
performing body: () throws -> some Any,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> {
var success = true
var mismatchExplanationValue: String? = nil
do {
_ = try body()
} catch {
success = false
mismatchExplanationValue = "an error was thrown when none was expected: \(_description(of: error))"
}
return __checkValue(
success,
expression: expression,
mismatchedErrorDescription: mismatchExplanationValue,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expression never throws an error.
///
/// This overload is used for `await #expect(throws: Never.self) { }`. It cannot
/// be implemented directly in terms of the other overloads because it checks
/// for the _absence_ of an error rather than an error that matches some
/// predicate.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall(
throws _: Never.Type,
performing body: () async throws -> sending some Any,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
isolation: isolated (any Actor)? = #isolation,
sourceLocation: SourceLocation
) async -> Result<Void, any Error> {
var success = true
var mismatchExplanationValue: String? = nil
do {
_ = try await body()
} catch {
success = false
mismatchExplanationValue = "an error was thrown when none was expected: \(_description(of: error))"
}
return __checkValue(
success,
expression: expression,
mismatchedErrorDescription: mismatchExplanationValue,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
// MARK: - Matching instances of equatable errors
/// Check that an expression always throws an error.
///
/// This overload is used for `#expect(throws:) { }` invocations that take error
/// instances.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall<E>(
throws error: E,
performing body: () throws -> some Any,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> where E: Error & Equatable {
__checkClosureCall(
performing: body,
throws: { true == (($0 as? E) == error) },
mismatchExplanation: { "expected error \(_description(of: error)), but \(_description(of: $0)) was thrown instead" },
expression: expression,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expression always throws an error.
///
/// This overload is used for `await #expect(throws:) { }` invocations that take
/// error instances.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall<E>(
throws error: E,
performing body: () async throws -> sending some Any,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
isolation: isolated (any Actor)? = #isolation,
sourceLocation: SourceLocation
) async -> Result<Void, any Error> where E: Error & Equatable {
await __checkClosureCall(
performing: body,
throws: { true == (($0 as? E) == error) },
mismatchExplanation: { "expected error \(_description(of: error)), but \(_description(of: $0)) was thrown instead" },
expression: expression,
comments: comments(),
isRequired: isRequired,
isolation: isolation,
sourceLocation: sourceLocation
)
}
// MARK: - Arbitrary error matching
/// Check that an expression always throws an error.
///
/// This overload is used for `#expect { } throws: { }` invocations.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall<R>(
performing body: () throws -> R,
throws errorMatcher: (any Error) throws -> Bool,
mismatchExplanation: ((any Error) -> String)? = nil,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) -> Result<Void, any Error> {
var errorMatches = false
var mismatchExplanationValue: String? = nil
var expression = expression
do {
let result = try body()
var explanation = "an error was expected but none was thrown"
if R.self != Void.self {
explanation += " and \"\(result)\" was returned"
}
mismatchExplanationValue = explanation
} catch {
expression = expression.capturingRuntimeValues(error)
let secondError = Issue.withErrorRecording(at: sourceLocation) {
errorMatches = try errorMatcher(error)
}
if let secondError {
mismatchExplanationValue = "a second error \(_description(of: secondError)) was thrown when checking error \(_description(of: error))"
} else if !errorMatches {
mismatchExplanationValue = mismatchExplanation?(error) ?? "unexpected error \(_description(of: error)) was thrown"
}
}
return __checkValue(
errorMatches,
expression: expression,
mismatchedErrorDescription: mismatchExplanationValue,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
/// Check that an expression always throws an error.
///
/// This overload is used for `await #expect { } throws: { }` invocations.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
public func __checkClosureCall<R>(
performing body: () async throws -> sending R,
throws errorMatcher: (any Error) async throws -> Bool,
mismatchExplanation: ((any Error) -> String)? = nil,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
isolation: isolated (any Actor)? = #isolation,
sourceLocation: SourceLocation
) async -> Result<Void, any Error> {
var errorMatches = false
var mismatchExplanationValue: String? = nil
var expression = expression
do {
let result = try await body()
var explanation = "an error was expected but none was thrown"
if R.self != Void.self {
explanation += " and \"\(result)\" was returned"
}
mismatchExplanationValue = explanation
} catch {
expression = expression.capturingRuntimeValues(error)
let secondError = await Issue.withErrorRecording(at: sourceLocation) {
errorMatches = try await errorMatcher(error)
}
if let secondError {
mismatchExplanationValue = "a second error \(_description(of: secondError)) was thrown when checking error \(_description(of: error))"
} else if !errorMatches {
mismatchExplanationValue = mismatchExplanation?(error) ?? "unexpected error \(_description(of: error)) was thrown"
}
}
return __checkValue(
errorMatches,
expression: expression,
mismatchedErrorDescription: mismatchExplanationValue,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
// MARK: - Exit tests
#if !SWT_NO_EXIT_TESTS
/// Check that an expression always exits (terminates the current process) with
/// a given status.
///
/// This overload is used for `await #expect(exitsWith:) { }` invocations. Note
/// that the `body` argument is thin here because it cannot meaningfully capture
/// state from the enclosing context.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
@_spi(Experimental)
public func __checkClosureCall(
exitsWith expectedExitCondition: ExitCondition,
performing body: @convention(thin) () async -> Void,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
sourceLocation: SourceLocation
) async -> Result<Void, any Error> {
await callExitTest(
exitsWith: expectedExitCondition,
performing: { await body() },
expression: expression,
comments: comments(),
isRequired: isRequired,
sourceLocation: sourceLocation
)
}
#endif
// MARK: -
/// Generate a description of an error that includes its type name if not
/// already present.
///
/// - Parameters:
/// - error: The error to describe.
///
/// - Returns: A string equivalent to `String(describing: error)` with
/// information about its type added if not already present.
private func _description(of error: some Error) -> String {
let errorDescription = "\"\(error)\""
let errorType = type(of: error as Any)
if #available(_regexAPI, *) {
if errorDescription.contains(String(describing: errorType)) {
return errorDescription
}
}
return "\(errorDescription) of type \(errorType)"
}
|