Skip to content

Commit bd7ee04

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 e76a44f commit bd7ee04

20 files changed

+372
-54
lines changed

Documentation/ABI/TestContent.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -75,16 +75,16 @@ struct SWTTestContentRecord {
7575
};
7676
```
7777

78-
Do not use the `__TestContentRecord` or `__TestContentRecordAccessor` typealias
79-
defined in the testing library. These types exist to support the testing
78+
Do not use the `__TestContentRecord` or `__TestContentRecordAccessor` type
79+
aliases defined in the testing library. These types exist to support the testing
8080
library's macros and may change in the future (e.g. to accomodate a generic
8181
argument or to make use of a reserved field.)
8282

8383
Instead, define your own copy of these types where needed—you can copy the
8484
definitions above _verbatim_. If your test record type's `context` field (as
8585
described below) is a pointer type, make sure to change its type in your version
8686
of `TestContentRecord` accordingly so that, on systems with pointer
87-
authentication enabled, the pointer is correctly resigned at load time.
87+
authentication enabled, the pointer is correctly re-signed at load time.
8888

8989
### Record content
9090

Documentation/Porting.md

+6
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

+2
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

+9-2
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
}
@@ -101,9 +105,8 @@ private let _startCollectingSectionBounds: Void = {
101105
var size = CUnsignedLong(0)
102106
if let start = getsectiondata(mh, segmentName.utf8Start, sectionName.utf8Start, &size), size > 0 {
103107
let buffer = UnsafeRawBufferPointer(start: start, count: Int(clamping: size))
104-
let sb = SectionBounds(imageAddress: mh, buffer: buffer)
105108
_sectionBounds.withLock { sectionBounds in
106-
sectionBounds[kind]!.append(sb)
109+
sectionBounds[kind]!.append(SectionBounds(imageAddress: mh, buffer: buffer))
107110
}
108111
}
109112
}
@@ -165,8 +168,10 @@ private func _sectionBounds(_ kind: SectionBounds.Kind) -> [SectionBounds] {
165168
let range = switch context.pointee.kind {
166169
case .testContent:
167170
sections.swift5_tests
171+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
168172
case .typeMetadata:
169173
sections.swift5_type_metadata
174+
#endif
170175
}
171176
let start = UnsafeRawPointer(bitPattern: range.start)
172177
let size = Int(clamping: range.length)
@@ -255,8 +260,10 @@ private func _sectionBounds(_ kind: SectionBounds.Kind) -> some Sequence<Section
255260
let sectionName = switch kind {
256261
case .testContent:
257262
".sw5test"
263+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
258264
case .typeMetadata:
259265
".sw5tymd"
266+
#endif
260267
}
261268
return HMODULE.all.lazy.compactMap { _findSection(named: sectionName, in: $0) }
262269
}

Sources/Testing/Discovery.swift

+11
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,17 @@ public typealias __TestContentRecord = (
4949
reserved2: UInt
5050
)
5151

52+
/// Compare two move-only types.
53+
///
54+
/// This operator is provided because the Swift standard library does not yet
55+
/// provide a `==` operator for move-only types. ([134276458](rdar://134276458))
56+
///
57+
/// - Warning: This operator is used to implement the `#expect(exitsWith:)`
58+
/// macro. Do not use it directly. It will be removed in a future update.
59+
public func ==(__lhs: (some ~Copyable).Type, rhs: (some ~Copyable).Type) -> Bool {
60+
TypeInfo(describing: __lhs) == TypeInfo(describing: rhs)
61+
}
62+
5263
// MARK: -
5364

5465
/// A protocol describing a type that can be stored as test content at compile

Sources/Testing/ExitTests/ExitTest.swift

+4
Original file line numberDiff line numberDiff line change
@@ -247,11 +247,15 @@ extension ExitTest {
247247
}
248248
}
249249

250+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
250251
// Call the legacy lookup function that discovers tests embedded in types.
251252
return types(withNamesContaining: exitTestContainerTypeNameMagic).lazy
252253
.compactMap { $0 as? any __ExitTestContainer.Type }
253254
.first { $0.__id == id }
254255
.map { ExitTest(__identifiedBy: $0.__id, body: $0.__body) }
256+
#else
257+
return nil
258+
#endif
255259
}
256260
}
257261

Sources/Testing/Test+Discovery+Legacy.swift

+2
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
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
@@ -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

+6
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ extension Test {
5353
// the legacy and new mechanisms, but we can set an environment variable
5454
// to explicitly select one or the other. When we remove legacy support,
5555
// we can also remove this enumeration and environment variable check.
56+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
5657
let (useNewMode, useLegacyMode) = switch Environment.flag(named: "SWT_USE_LEGACY_TEST_DISCOVERY") {
5758
case .none:
5859
(true, true)
@@ -61,6 +62,9 @@ extension Test {
6162
case .some(false):
6263
(true, false)
6364
}
65+
#else
66+
let useNewMode = true
67+
#endif
6468

6569
// Walk all test content and gather generator functions, then call them in
6670
// a task group and collate their results.
@@ -79,6 +83,7 @@ extension Test {
7983
}
8084
}
8185

86+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
8287
// Perform legacy test discovery if needed.
8388
if useLegacyMode && result.isEmpty {
8489
let types = types(withNamesContaining: testContainerTypeNameMagic).lazy
@@ -92,6 +97,7 @@ extension Test {
9297
result = await taskGroup.reduce(into: result) { $0.formUnion($1) }
9398
}
9499
}
100+
#endif
95101

96102
return result
97103
}

Sources/TestingMacros/CMakeLists.txt

+2
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

+41-4
Original file line numberDiff line numberDiff line change
@@ -452,11 +452,44 @@ 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+
guard type.load(as: (any ~Swift.Copyable.Type).self) == Testing.__ExitTest.self else {
469+
return false
470+
}
471+
let id = \(exitTestIDExpr)
472+
if let hintedID = hint?.load(as: Testing.__ExitTest.ID.self), hintedID != id {
473+
return false
474+
}
475+
let outValue = outValue.assumingMemoryBound(to: Testing.__ExitTest.self)
476+
outValue.initialize(to: .init(__identifiedBy: id, body: \(bodyThunkName)))
477+
return true
478+
}
479+
480+
\(testContentRecordDecl)
481+
}
482+
#endif
483+
"""
484+
)
485+
486+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
487+
// Emit a legacy type declaration if SymbolLinkageMarkers is off.
488+
let legacyEnumName = context.makeUniqueName("__🟠$exit_test_body__")
489+
decls.append(
490+
"""
491+
@available(*, deprecated, message: "This type is an implementation detail of the testing library. Do not use it directly.")
492+
enum \(legacyEnumName): Testing.__ExitTestContainer, Sendable {
460493
static var __id: Testing.__ExitTest.ID {
461494
\(exitTestIDExpr)
462495
}
@@ -466,12 +499,16 @@ extension ExitTestConditionMacro {
466499
}
467500
"""
468501
)
502+
#endif
469503

470504
arguments[trailingClosureIndex].expression = ExprSyntax(
471505
ClosureExprSyntax {
472506
for decl in decls {
473-
CodeBlockItemSyntax(item: .decl(decl))
474-
.with(\.trailingTrivia, .newline)
507+
CodeBlockItemSyntax(
508+
leadingTrivia: .newline,
509+
item: .decl(decl),
510+
trailingTrivia: .newline
511+
)
475512
}
476513
}
477514
)

Sources/TestingMacros/SuiteDeclarationMacro.swift

+52-6
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,54 @@ 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+
typealias Generator = @Sendable () async -> Testing.Test
148+
guard type.load(as: Any.Type.self) == Generator.self else {
149+
return false
150+
}
151+
let outValue = outValue.assumingMemoryBound(to: Generator.self)
152+
outValue.initialize(to: \(generatorName))
153+
return true
154+
}
155+
"""
156+
157+
let testContentRecordDecl = makeTestContentRecordDecl(
158+
named: context.makeUniqueName("testContentRecord"),
159+
in: declaration.type,
160+
ofKind: .testDeclaration,
161+
accessingWith: accessorName,
162+
context: attributeInfo.testContentRecordFlags
163+
)
164+
165+
result.append(
166+
"""
167+
#if hasFeature(SymbolLinkageMarkers)
168+
\(accessorDecl)
169+
170+
\(testContentRecordDecl)
171+
#endif
172+
"""
173+
)
174+
175+
#if !SWT_NO_LEGACY_TEST_DISCOVERY
176+
// Emit a legacy type declaration if SymbolLinkageMarkers is off.
177+
//
130178
// The emitted type must be public or the compiler can optimize it away
131179
// (since it is not actually used anywhere that the compiler can see.)
132180
//
@@ -143,16 +191,14 @@ public struct SuiteDeclarationMacro: MemberMacro, PeerMacro, Sendable {
143191
@available(*, deprecated, message: "This type is an implementation detail of the testing library. Do not use it directly.")
144192
enum \(enumName): Testing.__TestContainer {
145193
static var __tests: [Testing.Test] {
146-
get async {[
147-
.__type(
148-
\(declaration.type.trimmed).self,
149-
\(raw: attributeInfo.functionArgumentList(in: context))
150-
)
151-
]}
194+
get async {
195+
[await \(generatorName)()]
196+
}
152197
}
153198
}
154199
"""
155200
)
201+
#endif
156202

157203
return result
158204
}
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+
}

Sources/TestingMacros/Support/Additions/TokenSyntaxAdditions.swift

+11
Original file line numberDiff line numberDiff line change
@@ -47,3 +47,14 @@ extension TokenSyntax {
4747
return nil
4848
}
4949
}
50+
51+
/// The `static` keyword, if `typeName` is not `nil`.
52+
///
53+
/// - Parameters:
54+
/// - typeName: The name of the type containing the macro being expanded.
55+
///
56+
/// - Returns: A token representing the `static` keyword, or one representing
57+
/// nothing if `typeName` is `nil`.
58+
func staticKeyword(for typeName: TypeSyntax?) -> TokenSyntax {
59+
(typeName != nil) ? .keyword(.static) : .unknown("")
60+
}

0 commit comments

Comments
 (0)