Skip to content

Commit c9d3cec

Browse files
committed
This PR completely rewrites how we capture expectation conditions.
### Explanation For example, given the following expectation: ```swift #expect(x.f() == 123) ``` We currently detect that there is a binary operation and emit code that calls the binary operator as a closure and passes the left-hand value and right-hand value, then checks that the result of the operation is `true`. This is sufficient for simpler expressions like that one, but more complex ones (including any that involve `try` or `await` keywords) cannot be expanded correctly. With this PR, such expressions _can_ generally be expanded correctly. The change involves rewriting the macro condition as a closure to which is passed a local, mutable "context" value. Subexpressions of the condition expression are then rewritten by walking the syntax tree of the expression (using typical swift-syntax API) and replacing them with calls into the context value that pass in the value and related state. If the expectation ultimately fails, the collected data is transformed into an instance of the SPI type `Expression` that contains the source code of the expression and interesting subexpressions as well as the runtime values of those subexpressions. Nodes in the syntax tree are identified by a unique ID which is composed of the swift-syntax ID for that node as well as all its parent nodes in a compact bitmask format. These IDs can be transformed into graph/trie key paths when expression/subexpression relationships need to be reconstructed on failure, meaning that a single rewritten node doesn't otherwise need to know its "place" in the overall expression. ### Examples As an example, this expectation… ```swift #expect(g() > 500) ``` … previously expanded to… ```swift Testing.__checkBinaryOperation( g(), { $0 > $1() }, 500, expression: .__fromBinaryOperation( .__fromSyntaxNode("g()"), ">", .__fromSyntaxNode("500") ), comments: [], isRequired: false, sourceLocation: Testing.SourceLocation.__here() ).__expected() ``` … but will now expand to: ```swift Testing.__checkCondition( { (__ec: inout Testing.__ExpectationContext) -> Swift.Bool in __ec(__ec(g(),0x2) > 500,0x0) }, sourceCode: [ 0x0: "g() > 500", 0x2: "g()" ], comments: [], isRequired: false, sourceLocation: Testing.SourceLocation.__here() ).__expected() ``` More interestingly, an expression with side effects or complex nested operations can also be translated. For example, this throwing expression… ```swift #expect((try g() > 500) && true) ``` … was… ```swift Testing.__checkValue( (try g() > 500) && true, expression: .__fromSyntaxNode("(try g() > 500) && true"), comments: [], isRequired: false, sourceLocation: Testing.SourceLocation.__here() ).__expected() ``` … but now becomes: ```swift try Testing.__checkCondition( { (__ec: inout Testing.__ExpectationContext) -> Swift.Bool in try Testing.__requiringTry(__ec(__ec((try __ec(__ec(g(),0x1ba) > 500,0xba)),0x2) && __ec(true,0x400000),0x0)) }, sourceCode: [ 0x0: "(try g() > 500) && true", 0x2: "(try g() > 500)", 0xba: "g() > 500", 0x1ba: "g()", 0x400000: "true" ], comments: [], isRequired: false, sourceLocation: Testing.SourceLocation.__here() ).__expected() ``` ### Caveats There remain a few caveats (that also generally affect the current implementation): - Mutating member functions are syntactically indistinguishable from non-mutating ones and miscompile when rewritten; - Expressions involving move-only types are also indistinguishable, but need lifetime management to be rewritten correctly; and - ~~Expressions where the `try` or `await` keyword is _outside_ the `#expect` macro cannot be expanded correctly because the macro cannot see those keywords during expansion.~~ This is now resolved. - Operations that cause us to capture move-only values (which is disallowed in most contexts) are syntactically indistinguishable from "normal" operations, which causes compilation of such code to fail obscurely. The first issue might be resolvable in the future using pointer tricks, although I don't hold a lot of hope for it. The second issue is probably resolved by non-escaping types. The third issue is an area of active exploration for us and the macros/swift-syntax team. ### Resolved Issues Resolves #162. Resolves rdar://135437448. ### Checklist: - [x] Code and documentation should follow the style of the [Style Guide](https://github.com/apple/swift-testing/blob/main/Documentation/StyleGuide.md). - [x] If public symbols are renamed or modified, DocC references should be updated.
1 parent 06a94d4 commit c9d3cec

39 files changed

+2343
-1702
lines changed

Package.swift

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -186,6 +186,13 @@ let package = Package(
186186
path: "Tests/_MemorySafeTestingTests",
187187
swiftSettings: .packageSettings + [.strictMemorySafety()]
188188
),
189+
.testTarget(
190+
name: "SubexpressionShowcase",
191+
dependencies: [
192+
"Testing",
193+
],
194+
swiftSettings: .packageSettings
195+
),
189196

190197
.macro(
191198
name: "TestingMacros",

Sources/Testing/CMakeLists.txt

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ add_library(Testing
5252
Expectations/Expectation.swift
5353
Expectations/Expectation+Macro.swift
5454
Expectations/ExpectationChecking+Macro.swift
55+
Expectations/ExpectationContext.swift
5556
Issues/Confirmation.swift
5657
Issues/ErrorSnapshot.swift
5758
Issues/Issue.swift
@@ -74,7 +75,7 @@ add_library(Testing
7475
SourceAttribution/Backtrace+Symbolication.swift
7576
SourceAttribution/CustomTestStringConvertible.swift
7677
SourceAttribution/Expression.swift
77-
SourceAttribution/Expression+Macro.swift
78+
SourceAttribution/ExpressionID.swift
7879
SourceAttribution/SourceBounds.swift
7980
SourceAttribution/SourceContext.swift
8081
SourceAttribution/SourceLocation.swift

Sources/Testing/Events/Recorder/Event.ConsoleOutputRecorder.swift

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -187,7 +187,7 @@ extension Event.Symbol {
187187
case .attachment:
188188
return "\(_ansiEscapeCodePrefix)94m\(symbolCharacter)\(_resetANSIEscapeCode)"
189189
case .details:
190-
return symbolCharacter
190+
return "\(symbolCharacter)"
191191
}
192192
}
193193
return symbolCharacter

Sources/Testing/ExitTests/ExitTest.swift

Lines changed: 10 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -464,17 +464,16 @@ extension ExitTest {
464464
/// This function contains the common implementation for all
465465
/// `await #expect(processExitsWith:) { }` invocations regardless of calling
466466
/// convention.
467-
func callExitTest(
467+
nonisolated(nonsending) func callExitTest(
468468
identifiedBy exitTestID: (UInt64, UInt64, UInt64, UInt64),
469469
encodingCapturedValues capturedValues: [ExitTest.CapturedValue],
470470
processExitsWith expectedExitCondition: ExitTest.Condition,
471471
observing observedValues: [any PartialKeyPath<ExitTest.Result> & Sendable],
472-
expression: __Expression,
472+
sourceCode: @escaping @autoclosure @Sendable () -> KeyValuePairs<__ExpressionID, String>,
473473
comments: @autoclosure () -> [Comment],
474474
isRequired: Bool,
475-
isolation: isolated (any Actor)? = #isolation,
476475
sourceLocation: SourceLocation
477-
) async -> Result<ExitTest.Result?, any Error> {
476+
) async -> Result<ExitTest.Result?, ExpectationFailedError> {
478477
guard let configuration = Configuration.current ?? Configuration.all.first else {
479478
preconditionFailure("A test must be running on the current task to use #expect(processExitsWith:).")
480479
}
@@ -527,27 +526,14 @@ func callExitTest(
527526
}
528527

529528
// Plumb the exit test's result through the general expectation machinery.
530-
func expressionWithCapturedRuntimeValues() -> __Expression {
531-
var expression = expression.capturingRuntimeValues(result.exitStatus)
532-
533-
expression.subexpressions = [expectedExitCondition.exitStatus, result.exitStatus]
534-
.compactMap { exitStatus in
535-
guard let exitStatus, let exitStatusName = exitStatus.name else {
536-
return nil
537-
}
538-
return __Expression(
539-
exitStatusName,
540-
runtimeValue: __Expression.Value(describing: exitStatus.code)
541-
)
542-
}
543-
544-
return expression
545-
}
546-
return __checkValue(
529+
let expectationContext = __ExpectationContext<Bool>(
530+
sourceCode: [.root: String(describingForTest: expectedExitCondition)],
531+
runtimeValues: [.root: { Expression.Value(reflecting: result.exitStatus) }]
532+
)
533+
return check(
547534
expectedExitCondition.isApproximatelyEqual(to: result.exitStatus),
548-
expression: expression,
549-
expressionWithCapturedRuntimeValues: expressionWithCapturedRuntimeValues(),
550-
mismatchedExitConditionDescription: #"expected exit status "\#(expectedExitCondition)", but "\#(result.exitStatus)" was reported instead"#,
535+
expectationContext: expectationContext,
536+
mismatchedErrorDescription: nil,
551537
comments: comments(),
552538
isRequired: isRequired,
553539
sourceLocation: sourceLocation

Sources/Testing/Expectations/Expectation+Macro.swift

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -66,10 +66,10 @@
6666
/// running in the current task and an instance of ``ExpectationFailedError`` is
6767
/// thrown.
6868
@freestanding(expression) public macro require<T>(
69-
_ optionalValue: T?,
69+
_ optionalValue: consuming T?,
7070
_ comment: @autoclosure () -> Comment? = nil,
7171
sourceLocation: SourceLocation = #_sourceLocation
72-
) -> T = #externalMacro(module: "TestingMacros", type: "RequireMacro")
72+
) -> T = #externalMacro(module: "TestingMacros", type: "UnwrapMacro") where T: ~Copyable
7373

7474
/// Unwrap an optional boolean value or, if it is `nil`, fail and throw an
7575
/// error.
@@ -89,7 +89,7 @@
8989
/// running in the current task and an instance of ``ExpectationFailedError`` is
9090
/// thrown.
9191
///
92-
/// This overload of ``require(_:_:sourceLocation:)-6w9oo`` checks if
92+
/// This overload of ``require(_:_:sourceLocation:)-5l63q`` checks if
9393
/// `optionalValue` may be ambiguous (i.e. it is unclear if the developer
9494
/// intended to check for a boolean value or unwrap an optional boolean value)
9595
/// and provides additional compile-time diagnostics when it is.
@@ -118,16 +118,16 @@ public macro require(
118118
/// running in the current task and an instance of ``ExpectationFailedError`` is
119119
/// thrown.
120120
///
121-
/// This overload of ``require(_:_:sourceLocation:)-6w9oo`` is used when a
121+
/// This overload of ``require(_:_:sourceLocation:)-5l63q`` is used when a
122122
/// non-optional, non-`Bool` value is passed to `#require()`. It emits a warning
123123
/// diagnostic indicating that the expectation is redundant.
124124
@freestanding(expression)
125125
@_documentation(visibility: private)
126126
public macro require<T>(
127-
_ optionalValue: T,
127+
_ optionalValue: consuming T,
128128
_ comment: @autoclosure () -> Comment? = nil,
129129
sourceLocation: SourceLocation = #_sourceLocation
130-
) -> T = #externalMacro(module: "TestingMacros", type: "NonOptionalRequireMacro")
130+
) -> T = #externalMacro(module: "TestingMacros", type: "NonOptionalRequireMacro") where T: ~Copyable
131131

132132
// MARK: - Matching errors by type
133133

Sources/Testing/Expectations/Expectation.swift

Lines changed: 6 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,14 +12,14 @@
1212
public struct Expectation: Sendable {
1313
/// The expression evaluated by this expectation.
1414
@_spi(ForToolsIntegrationOnly)
15-
public var evaluatedExpression: Expression
15+
public internal(set) var evaluatedExpression: Expression
1616

1717
/// A description of the error mismatch that occurred, if any.
1818
///
1919
/// If this expectation passed, the value of this property is `nil` because no
2020
/// error mismatch occurred.
2121
@_spi(Experimental) @_spi(ForToolsIntegrationOnly)
22-
public var mismatchedErrorDescription: String?
22+
public internal(set) var mismatchedErrorDescription: String?
2323

2424
/// A description of the difference between the operands in the expression
2525
/// evaluated by this expectation, if the difference could be determined.
@@ -28,14 +28,9 @@ public struct Expectation: Sendable {
2828
/// the difference is only computed when necessary to assist with diagnosing
2929
/// test failures.
3030
@_spi(Experimental) @_spi(ForToolsIntegrationOnly)
31-
public var differenceDescription: String?
32-
33-
/// A description of the exit condition that was expected to be matched.
34-
///
35-
/// If this expectation passed, the value of this property is `nil` because no
36-
/// exit test failed.
37-
@_spi(Experimental) @_spi(ForToolsIntegrationOnly)
38-
public var mismatchedExitConditionDescription: String?
31+
public var differenceDescription: String? {
32+
evaluatedExpression.differenceDescription
33+
}
3934

4035
/// Whether the expectation passed or failed.
4136
///
@@ -100,7 +95,7 @@ extension Expectation {
10095
/// - Parameter expectation: The real expectation.
10196
public init(snapshotting expectation: borrowing Expectation) {
10297
self.evaluatedExpression = expectation.evaluatedExpression
103-
self.mismatchedErrorDescription = expectation.mismatchedErrorDescription ?? expectation.mismatchedExitConditionDescription
98+
self.mismatchedErrorDescription = expectation.mismatchedErrorDescription
10499
self.differenceDescription = expectation.differenceDescription
105100
self.isPassing = expectation.isPassing
106101
self.isRequired = expectation.isRequired

0 commit comments

Comments
 (0)