Skip to content

Commit 266b53b

Browse files
committed
Store test content in a custom metadata section.
This PR uses the experimental symbol linkage margers feature in the Swift compiler to emit metadata about tests (and exit tests) into a dedicated section of the test executable being built. At runtime, we discover that section and read out the tests from it. This has several benefits over our current model, which involves walking Swift's type metadata table looking for types that conform to a protocol: 1. We don't need to define that protocol as public API in Swift Testing, 1. We don't need to emit type metadata (much larger than what we really need) for every test function, 1. We don't need to duplicate a large chunk of the Swift ABI sources in order to walk the type metadata table correctly, and 1. Almost all the new code is written in Swift, whereas the code it is intended to replace could not be fully represented in Swift and needed to be written in C++. The change also opens up the possibility of supporting generic types in the future because we can emit metadata without needing to emit a nested type (which is not always valid in a generic context.) That's a "future direction" and not covered by this PR specifically. I've defined a layout for entries in the new `swift5_tests` section that should be flexible enough for us in the short-to-medium term and which lets us define additional arbitrary test content record types. The layout of this section is covered in depth in the new [TestContent.md](Documentation/ABI/TestContent.md) article. This functionality is only available if a test target enables the experimental `"SymbolLinkageMarkers"` feature. We continue to emit protocol-conforming types for now—that code will be removed if and when the experimental feature is properly supported (modulo us adopting relevant changes to the feature's API.) #735 swiftlang/swift#76698 swiftlang/swift#78411
1 parent a7b5435 commit 266b53b

18 files changed

+399
-52
lines changed

Documentation/Porting.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -145,8 +145,10 @@ to load that information:
145145
+ let resourceName: Str255 = switch kind {
146146
+ case .testContent:
147147
+ "__swift5_tests"
148+
+#if !SWT_NO_LEGACY_TEST_DISCOVERY
148149
+ case .typeMetadata:
149150
+ "__swift5_types"
151+
+#endif
150152
+ }
151153
+
152154
+ let oldRefNum = CurResFile()
@@ -219,15 +221,19 @@ diff --git a/Sources/_TestingInternals/Discovery.cpp b/Sources/_TestingInternals
219221
+#elif defined(macintosh)
220222
+extern "C" const char testContentSectionBegin __asm__("...");
221223
+extern "C" const char testContentSectionEnd __asm__("...");
224+
+#if !defined(SWT_NO_LEGACY_TEST_DISCOVERY)
222225
+extern "C" const char typeMetadataSectionBegin __asm__("...");
223226
+extern "C" const char typeMetadataSectionEnd __asm__("...");
227+
+#endif
224228
#else
225229
#warning Platform-specific implementation missing: Runtime test discovery unavailable (static)
226230
static const char testContentSectionBegin = 0;
227231
static const char& testContentSectionEnd = testContentSectionBegin;
232+
#if !defined(SWT_NO_LEGACY_TEST_DISCOVERY)
228233
static const char typeMetadataSectionBegin = 0;
229234
static const char& typeMetadataSectionEnd = testContentSectionBegin;
230235
#endif
236+
#endif
231237
```
232238

233239
These symbols must have unique addresses corresponding to the first byte of the

Package.swift

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -165,6 +165,8 @@ extension Array where Element == PackageDescription.SwiftSetting {
165165
.enableExperimentalFeature("AccessLevelOnImport"),
166166
.enableUpcomingFeature("InternalImportsByDefault"),
167167

168+
.enableExperimentalFeature("SymbolLinkageMarkers"),
169+
168170
.define("SWT_TARGET_OS_APPLE", .when(platforms: [.macOS, .iOS, .macCatalyst, .watchOS, .tvOS, .visionOS])),
169171

170172
.define("SWT_NO_EXIT_TESTS", .when(platforms: [.iOS, .watchOS, .tvOS, .visionOS, .wasi, .android])),

Sources/Testing/Discovery+Platform.swift

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,10 @@ struct SectionBounds: Sendable {
2727
/// The test content metadata section.
2828
case testContent
2929

30+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
3031
/// The type metadata section.
3132
case typeMetadata
33+
#endif
3234
}
3335

3436
/// All section bounds of the given kind found in the current process.
@@ -60,8 +62,10 @@ extension SectionBounds.Kind {
6062
switch self {
6163
case .testContent:
6264
("__DATA_CONST", "__swift5_tests")
65+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
6366
case .typeMetadata:
6467
("__TEXT", "__swift5_types")
68+
#endif
6569
}
6670
}
6771
}
@@ -165,8 +169,10 @@ private func _sectionBounds(_ kind: SectionBounds.Kind) -> [SectionBounds] {
165169
let range = switch context.pointee.kind {
166170
case .testContent:
167171
sections.swift5_tests
172+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
168173
case .typeMetadata:
169174
sections.swift5_type_metadata
175+
#endif
170176
}
171177
let start = UnsafeRawPointer(bitPattern: range.start)
172178
let size = Int(clamping: range.length)
@@ -255,8 +261,10 @@ private func _sectionBounds(_ kind: SectionBounds.Kind) -> some Sequence<Section
255261
let sectionName = switch kind {
256262
case .testContent:
257263
".sw5test"
264+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
258265
case .typeMetadata:
259266
".sw5tymd"
267+
#endif
260268
}
261269
return HMODULE.all.lazy.compactMap { _findSection(named: sectionName, in: $0) }
262270
}

Sources/Testing/ExitTests/ExitTest.swift

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -243,6 +243,40 @@ extension ExitTest: TestContent {
243243
}
244244

245245
typealias TestContentAccessorHint = ID
246+
247+
/// Store the test generator function into the given memory.
248+
///
249+
/// - Parameters:
250+
/// - outValue: The uninitialized memory to store the exit test into.
251+
/// - id: The unique identifier of the exit test to store.
252+
/// - body: The body closure of the exit test to store.
253+
/// - typeAddress: A pointer to the expected type of the exit test as passed
254+
/// to the test content record calling this function.
255+
/// - hintAddress: A pointer to an instance of ``ID`` to use as a hint.
256+
///
257+
/// - Returns: Whether or not an exit test was stored into `outValue`.
258+
///
259+
/// - Warning: This function is used to implement the `#expect(exitsWith:)`
260+
/// macro. Do not use it directly.
261+
public static func __store(
262+
_ id: (UInt64, UInt64),
263+
_ body: @escaping @Sendable () async throws -> Void,
264+
into outValue: UnsafeMutableRawPointer,
265+
asTypeAt typeAddress: UnsafeRawPointer,
266+
withHintAt hintAddress: UnsafeRawPointer? = nil
267+
) -> CBool {
268+
let callerExpectedType = TypeInfo(describing: typeAddress.load(as: Any.Type.self))
269+
let selfType = TypeInfo(describing: Self.self)
270+
guard callerExpectedType == selfType else {
271+
return false
272+
}
273+
let id = ID(id)
274+
if let hintedID = hintAddress?.load(as: ID.self), hintedID != id {
275+
return false
276+
}
277+
outValue.initializeMemory(as: Self.self, to: Self(id: id, body: body))
278+
return true
279+
}
246280
}
247281

248282
@_spi(Experimental) @_spi(ForToolsIntegrationOnly)

Sources/Testing/Test+Discovery+Legacy.swift

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,12 +10,13 @@
1010

1111
private import _TestingInternals
1212

13+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
1314
/// A protocol describing a type that contains tests.
1415
///
1516
/// - Warning: This protocol is used to implement the `@Test` macro. Do not use
1617
/// it directly.
1718
@_alwaysEmitConformanceMetadata
18-
public protocol __TestContainer {
19+
public protocol __TestContainer: Sendable {
1920
/// The set of tests contained by this type.
2021
static var __tests: [Test] { get async }
2122
}
@@ -31,7 +32,7 @@ let testContainerTypeNameMagic = "__🟠$test_container__"
3132
/// macro. Do not use it directly.
3233
@_alwaysEmitConformanceMetadata
3334
@_spi(Experimental)
34-
public protocol __ExitTestContainer {
35+
public protocol __ExitTestContainer: Sendable {
3536
/// The unique identifier of the exit test.
3637
static var __id: (UInt64, UInt64) { get }
3738

@@ -60,3 +61,4 @@ func types(withNamesContaining nameSubstring: String) -> some Sequence<Any.Type>
6061
.map { unsafeBitCast($0, to: Any.Type.self) }
6162
}
6263
}
64+
#endif

Sources/Testing/Test+Discovery.swift

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,30 @@ extension Test {
2626
var rawValue: @Sendable () async -> Test
2727
}
2828

29+
/// Store the test generator function into the given memory.
30+
///
31+
/// - Parameters:
32+
/// - generator: The generator function to store.
33+
/// - outValue: The uninitialized memory to store `generator` into.
34+
/// - typeAddress: A pointer to the expected type of `generator` as passed
35+
/// to the test content record calling this function.
36+
///
37+
/// - Returns: Whether or not `generator` was stored into `outValue`.
38+
///
39+
/// - Warning: This function is used to implement the `@Test` macro. Do not
40+
/// use it directly.
41+
public static func __store(
42+
_ generator: @escaping @Sendable () async -> Test,
43+
into outValue: UnsafeMutableRawPointer,
44+
asTypeAt typeAddress: UnsafeRawPointer
45+
) -> CBool {
46+
guard typeAddress.load(as: Any.Type.self) == Generator.self else {
47+
return false
48+
}
49+
outValue.initializeMemory(as: Generator.self, to: .init(rawValue: generator))
50+
return true
51+
}
52+
2953
/// All available ``Test`` instances in the process, according to the runtime.
3054
///
3155
/// The order of values in this sequence is unspecified.
@@ -40,6 +64,7 @@ extension Test {
4064
// the legacy and new mechanisms, but we can set an environment variable
4165
// to explicitly select one or the other. When we remove legacy support,
4266
// we can also remove this enumeration and environment variable check.
67+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
4368
let (useNewMode, useLegacyMode) = switch Environment.flag(named: "SWT_USE_LEGACY_TEST_DISCOVERY") {
4469
case .none:
4570
(true, true)
@@ -48,6 +73,9 @@ extension Test {
4873
case .some(false):
4974
(true, false)
5075
}
76+
#else
77+
let useNewMode = true
78+
#endif
5179

5280
// Walk all test content and gather generator functions, then call them in
5381
// a task group and collate their results.
@@ -61,6 +89,7 @@ extension Test {
6189
}
6290
}
6391

92+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
6493
// Perform legacy test discovery if needed.
6594
if useLegacyMode && result.isEmpty {
6695
let types = types(withNamesContaining: testContainerTypeNameMagic).lazy
@@ -74,6 +103,7 @@ extension Test {
74103
result = await taskGroup.reduce(into: result) { $0.formUnion($1) }
75104
}
76105
}
106+
#endif
77107

78108
return result
79109
}

Sources/TestingMacros/CMakeLists.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ target_sources(TestingMacros PRIVATE
8787
Support/Additions/DeclGroupSyntaxAdditions.swift
8888
Support/Additions/EditorPlaceholderExprSyntaxAdditions.swift
8989
Support/Additions/FunctionDeclSyntaxAdditions.swift
90+
Support/Additions/IntegerLiteralExprSyntaxAdditions.swift
9091
Support/Additions/MacroExpansionContextAdditions.swift
9192
Support/Additions/TokenSyntaxAdditions.swift
9293
Support/Additions/TriviaPieceAdditions.swift
@@ -103,6 +104,7 @@ target_sources(TestingMacros PRIVATE
103104
Support/DiagnosticMessage+Diagnosing.swift
104105
Support/SourceCodeCapturing.swift
105106
Support/SourceLocationGeneration.swift
107+
Support/TestContentGeneration.swift
106108
TagMacro.swift
107109
TestDeclarationMacro.swift
108110
TestingMacrosMain.swift)

Sources/TestingMacros/ConditionMacro.swift

Lines changed: 39 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -452,26 +452,60 @@ extension ExitTestConditionMacro {
452452

453453
// Create a local type that can be discovered at runtime and which contains
454454
// the exit test body.
455-
let enumName = context.makeUniqueName("__🟠$exit_test_body__")
455+
let enumName = context.makeUniqueName("")
456+
let testContentRecordDecl = makeTestContentRecordDecl(
457+
named: .identifier("testContentRecord"),
458+
in: TypeSyntax(IdentifierTypeSyntax(name: enumName)),
459+
ofKind: .exitTest,
460+
accessingWith: .identifier("accessor")
461+
)
456462
decls.append(
457463
"""
464+
#if hasFeature(SymbolLinkageMarkers)
458465
@available(*, deprecated, message: "This type is an implementation detail of the testing library. Do not use it directly.")
459-
enum \(enumName): Testing.__ExitTestContainer, Sendable {
466+
enum \(enumName) {
467+
private static let accessor: Testing.__TestContentRecordAccessor = { outValue, type, hint in
468+
Testing.ExitTest.__store(
469+
\(exitTestIDExpr),
470+
\(bodyThunkName),
471+
into: outValue,
472+
asTypeAt: type,
473+
withHintAt: hint
474+
)
475+
}
476+
477+
\(testContentRecordDecl)
478+
}
479+
#endif
480+
"""
481+
)
482+
483+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
484+
// Emit a legacy type declaration if SymbolLinkageMarkers is off.
485+
let legacyEnumName = context.makeUniqueName("__🟠$exit_test_body__")
486+
decls.append(
487+
"""
488+
@available(*, deprecated, message: "This type is an implementation detail of the testing library. Do not use it directly.")
489+
enum \(legacyEnumName): Testing.__ExitTestContainer {
460490
static var __id: (Swift.UInt64, Swift.UInt64) {
461491
\(exitTestIDExpr)
462492
}
463-
static var __body: @Sendable () async throws -> Void {
493+
static var __body: @Sendable () async throws -> Swift.Void {
464494
\(bodyThunkName)
465495
}
466496
}
467497
"""
468498
)
499+
#endif
469500

470501
arguments[trailingClosureIndex].expression = ExprSyntax(
471502
ClosureExprSyntax {
472503
for decl in decls {
473-
CodeBlockItemSyntax(item: .decl(decl))
474-
.with(\.trailingTrivia, .newline)
504+
CodeBlockItemSyntax(
505+
leadingTrivia: .newline,
506+
item: .decl(decl),
507+
trailingTrivia: .newline
508+
)
475509
}
476510
}
477511
)

Sources/TestingMacros/SuiteDeclarationMacro.swift

Lines changed: 46 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,48 @@ public struct SuiteDeclarationMacro: MemberMacro, PeerMacro, Sendable {
127127
// Parse the @Suite attribute.
128128
let attributeInfo = AttributeInfo(byParsing: suiteAttribute, on: declaration, in: context)
129129

130+
let generatorName = context.makeUniqueName("generator")
131+
result.append(
132+
"""
133+
@available(*, deprecated, message: "This property is an implementation detail of the testing library. Do not use it directly.")
134+
@Sendable private static func \(generatorName)() async -> Testing.Test {
135+
.__type(
136+
\(declaration.type.trimmed).self,
137+
\(raw: attributeInfo.functionArgumentList(in: context))
138+
)
139+
}
140+
"""
141+
)
142+
143+
let accessorName = context.makeUniqueName("accessor")
144+
let accessorDecl: DeclSyntax = """
145+
@available(*, deprecated, message: "This property is an implementation detail of the testing library. Do not use it directly.")
146+
private static let \(accessorName): Testing.__TestContentRecordAccessor = { outValue, type, _ in
147+
Testing.Test.__store(\(generatorName), into: outValue, asTypeAt: type)
148+
}
149+
"""
150+
151+
let testContentRecordDecl = makeTestContentRecordDecl(
152+
named: context.makeUniqueName("testContentRecord"),
153+
in: declaration.type,
154+
ofKind: .testDeclaration,
155+
accessingWith: accessorName,
156+
context: attributeInfo.testContentRecordFlags
157+
)
158+
159+
result.append(
160+
"""
161+
#if hasFeature(SymbolLinkageMarkers)
162+
\(accessorDecl)
163+
164+
\(testContentRecordDecl)
165+
#endif
166+
"""
167+
)
168+
169+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
170+
// Emit a legacy type declaration if SymbolLinkageMarkers is off.
171+
//
130172
// The emitted type must be public or the compiler can optimize it away
131173
// (since it is not actually used anywhere that the compiler can see.)
132174
//
@@ -143,16 +185,14 @@ public struct SuiteDeclarationMacro: MemberMacro, PeerMacro, Sendable {
143185
@available(*, deprecated, message: "This type is an implementation detail of the testing library. Do not use it directly.")
144186
enum \(enumName): Testing.__TestContainer {
145187
static var __tests: [Testing.Test] {
146-
get async {[
147-
.__type(
148-
\(declaration.type.trimmed).self,
149-
\(raw: attributeInfo.functionArgumentList(in: context))
150-
)
151-
]}
188+
get async {
189+
[await \(generatorName)()]
190+
}
152191
}
153192
}
154193
"""
155194
)
195+
#endif
156196

157197
return result
158198
}
Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
//
2+
// This source file is part of the Swift.org open source project
3+
//
4+
// Copyright (c) 2024 Apple Inc. and the Swift project authors
5+
// Licensed under Apache License v2.0 with Runtime Library Exception
6+
//
7+
// See https://swift.org/LICENSE.txt for license information
8+
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
9+
//
10+
11+
import SwiftSyntax
12+
13+
extension IntegerLiteralExprSyntax {
14+
init(_ value: some BinaryInteger, radix: IntegerLiteralExprSyntax.Radix = .decimal) {
15+
let stringValue = "\(radix.literalPrefix)\(String(value, radix: radix.size))"
16+
self.init(literal: .integerLiteral(stringValue))
17+
}
18+
}

0 commit comments

Comments
 (0)