Skip to content

Use a consistent definition for unreachable code in macro expansions. #1166

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion Sources/Testing/ExitTests/ExitTest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -384,7 +384,7 @@ extension ExitTest {
asTypeAt typeAddress: UnsafeRawPointer,
withHintAt hintAddress: UnsafeRawPointer? = nil
) -> CBool {
fatalError("Unimplemented")
swt_unreachable()
}
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/Testing/Expectations/Expectation+Macro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,7 @@ public macro require(
/// macro. Do not use it directly.
@freestanding(expression)
public macro __capturedValue<T>(
_ value: T,
_ value: borrowing T,
_ name: String,
_ expectedType: T.Type
) -> T = #externalMacro(module: "TestingMacros", type: "ExitTestCapturedValueMacro") where T: Sendable & Codable
Expand All @@ -611,7 +611,7 @@ public macro __capturedValue<T>(
_ value: borrowing T,
_ name: String,
_ expectedType: T.Type
) -> Never = #externalMacro(module: "TestingMacros", type: "ExitTestBadCapturedValueMacro") where T: ~Copyable & ~Escapable
) -> T = #externalMacro(module: "TestingMacros", type: "ExitTestBadCapturedValueMacro") where T: ~Copyable & ~Escapable

/// Emit a compile-time diagnostic when a value is captured by an exit test but
/// we inferred the wrong type.
Expand Down
27 changes: 27 additions & 0 deletions Sources/Testing/Expectations/ExpectationChecking+Macro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//

private import _TestingInternals

/// Check that an expectation has passed after a condition has been evaluated
/// and throw an error if it failed.
///
Expand Down Expand Up @@ -1199,6 +1201,31 @@ public func __checkClosureCall<each T>(
sourceLocation: sourceLocation
)
}

/// Check that an expression always exits (terminates the current process) with
/// a given status.
///
/// This overload is used for `await #expect(processExitsWith:) { }` invocations
/// that attempt to capture a non-`Sendable` or non-`Codable` value.
///
/// - Warning: This function is used to implement the `#expect()` and
/// `#require()` macros. Do not call it directly.
@_spi(Experimental)
@_disfavoredOverload
public func __checkClosureCall<each T>(
identifiedBy exitTestID: (UInt64, UInt64, UInt64, UInt64),
encodingCapturedValues capturedValues: (repeat each T),
processExitsWith expectedExitCondition: ExitTest.Condition,
observing observedValues: [any PartialKeyPath<ExitTest.Result> & Sendable] = [],
performing _: @convention(c) () -> Void,
expression: __Expression,
comments: @autoclosure () -> [Comment],
isRequired: Bool,
isolation: isolated (any Actor)? = #isolation,
sourceLocation: SourceLocation
) async -> Result<ExitTest.Result?, any Error> {
swt_unreachable()
}
#endif

// MARK: -
Expand Down
4 changes: 2 additions & 2 deletions Sources/TestingMacros/ConditionMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -441,9 +441,9 @@ extension ExitTestConditionMacro {
// early if found.
guard _diagnoseIssues(with: macro, body: bodyArgumentExpr, in: context) else {
if Self.isThrowing {
return #"{ () async throws -> Testing.ExitTest.Result in Swift.fatalError("Unreachable") }()"#
return .unreachable(as: "Testing.ExitTest.Result", withEffectKeywords: [.async, .throws])
} else {
return #"{ () async -> Testing.ExitTest.Result in Swift.fatalError("Unreachable") }()"#
return .unreachable(as: "Testing.ExitTest.Result", withEffectKeywords: [.async])
}
}

Expand Down
6 changes: 5 additions & 1 deletion Sources/TestingMacros/ExitTestCapturedValueMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,11 @@ public struct ExitTestBadCapturedValueMacro: ExpressionMacro, Sendable {
// Diagnose that the type of 'expr' is invalid.
context.diagnose(.capturedValueMustBeSendableAndCodable(expr, name: nameExpr))

return #"Swift.fatalError("Unsupported")"#
var type: TypeSyntax?
if let typeExpr = arguments[2].expression.as(MemberAccessExprSyntax.self)?.base?.as(TupleExprSyntax.self)?.elements.first?.expression {
type = "\(typeExpr.trimmed)"
}
return .unreachable(as: type)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -178,3 +178,36 @@ extension FunctionParameterSyntax {
return baseType.trimmedDescription
}
}

// MARK: -

extension ExprSyntax {
/// Get an expression representing an unreachable code path.
///
/// - Parameters:
/// - type: The type to infer for the resulting expression. If `nil`, no
/// type (other than `Swift.Never`) is inferred.
/// - effectKeywords: Zero or more effect keywords to apply to the
/// expression (e.g. `throws` if the expression should be treated as
/// throwing.)
///
/// Use this expression when a macro will emit an error diagnostic but the
/// compiler still requires us to produce a valid expression.
static func unreachable(as type: TypeSyntax? = nil, withEffectKeywords effectKeywords: [Keyword] = []) -> Self {
let returnClause = type.map { type in
ReturnClauseSyntax(
leadingTrivia: .space,
arrow: .arrowToken(trailingTrivia: .space),
type: type.trimmed
)
}
var effectSpecifiers = TypeEffectSpecifiersSyntax(throwsClause: nil)
if effectKeywords.contains(.async) {
effectSpecifiers.asyncSpecifier = .keyword(.async)
}
if effectKeywords.contains(.throws) {
effectSpecifiers.throwsClause = ThrowsClauseSyntax(throwsSpecifier: .keyword(.throws))
}
return #"{ () \#(effectSpecifiers) \#(returnClause) in Swift.fatalError("Unreachable") }()"#
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ struct CapturedValueInfo {

init(_ capture: ClosureCaptureSyntax, in context: some MacroExpansionContext) {
self.capture = capture
self.expression = #"Swift.fatalError("Unsupported")"#
self.expression = .unreachable()
self.type = "Swift.Never"

// We don't support capture specifiers at this time.
Expand Down
2 changes: 1 addition & 1 deletion Sources/TestingMacros/TagMacro.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ public struct TagMacro: PeerMacro, AccessorMacro, Sendable {
/// This property is used rather than simply returning the empty array in
/// order to suppress a compiler diagnostic about not producing any accessors.
private static var _fallbackAccessorDecls: [AccessorDeclSyntax] {
[#"get { Swift.fatalError("Unreachable") }"#]
[#"get { \#(ExprSyntax.unreachable()) }"#]
}

public static func expansion(
Expand Down