-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathAssertMacro.swift
681 lines (639 loc) · 22.9 KB
/
AssertMacro.swift
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
import InlineSnapshotTesting
import SwiftDiagnostics
import SwiftOperators
import SwiftParser
import SwiftParserDiagnostics
import SwiftSyntax
import SwiftSyntaxMacroExpansion
import SwiftSyntaxMacros
import XCTest
/// Asserts that a given Swift source string matches an expected string with all macros expanded.
///
/// To write a macro assertion, you simply pass the mapping of macros to expand along with the
/// source code that should be expanded:
///
/// ```swift
/// func testMacro() {
/// assertMacro(["stringify": StringifyMacro.self]) {
/// """
/// #stringify(a + b)
/// """
/// }
/// }
/// ```
///
/// When this test is run, the result of the expansion is automatically written to the test file,
/// inlined, as a trailing argument:
///
/// ```swift
/// func testMacro() {
/// assertMacro(["stringify": StringifyMacro.self]) {
/// """
/// #stringify(a + b)
/// """
/// } expansion: {
/// """
/// (a + b, "a + b")
/// """
/// }
/// }
/// ```
///
/// If the expansion fails, diagnostics are inlined instead:
///
/// ```swift
/// assertMacro(["MetaEnum": MetaEnumMacro.self]) {
/// """
/// @MetaEnum struct Cell {
/// let integer: Int
/// let text: String
/// let boolean: Bool
/// }
/// """
/// } diagnostics: {
/// """
/// @MetaEnum struct Cell {
/// ┬────────
/// ╰─ 🛑 '@MetaEnum' can only be attached to an enum, not a struct
/// let integer: Int
/// let text: String
/// let boolean: Bool
/// }
/// """
/// }
/// ```
///
/// > Tip: Use ``withMacroTesting(indentationWidth:isRecording:macros:operation:)-5id9j`` in your
/// > test case's `invokeTest` to avoid the repetitive work of passing the macro mapping to every
/// > `assertMacro`:
/// >
/// > ```swift
/// > override func invokeTest() {
/// > // By wrapping each test with macro testing configuration...
/// > withMacroTesting(macros: ["stringify": StringifyMacro.self]) {
/// > super.invokeTest()
/// > }
/// > }
/// >
/// > func testMacro() {
/// > assertMacro { // ...we can omit it from the assertion.
/// > """
/// > #stringify(a + b)
/// > """
/// > } expansion: {
/// > """
/// > (a + b, "a + b")
/// > """
/// > }
/// > }
/// > ```
///
/// - Parameters:
/// - macros: The macros to expand in the original source string. Required, either implicitly via
/// ``withMacroTesting(indentationWidth:isRecording:macros:operation:)-5id9j``, or explicitly
/// via this parameter.
/// - indentationWidth: The `Trivia` for setting indentation during macro expansion
/// (e.g., `.spaces(2)`). Defaults to the original source's indentation if unspecified. If the
/// original source lacks indentation, it defaults to `.spaces(4)`.
/// - isRecording: Always records new snapshots when enabled.
/// - originalSource: A string of Swift source code.
/// - diagnosedSource: Swift source code annotated with expected diagnostics.
/// - fixedSource: Swift source code with expected fix-its applied.
/// - expandedSource: Expected Swift source string with macros expanded.
/// - file: The file where the assertion occurs. The default is the filename of the test case
/// where you call this function.
/// - function: The function where the assertion occurs. The default is the name of the test
/// method where you call this function.
/// - line: The line where the assertion occurs. The default is the line number where you call
/// this function.
/// - column: The column where the assertion occurs. The default is the column where you call this
/// function.
public func assertMacro(
_ macros: [String: Macro.Type]? = nil,
indentationWidth: Trivia? = nil,
record isRecording: Bool? = nil,
of originalSource: () throws -> String,
diagnostics diagnosedSource: (() -> String)? = nil,
fixes fixedSource: (() -> String)? = nil,
expansion expandedSource: (() -> String)? = nil,
file: StaticString = #filePath,
function: StaticString = #function,
line: UInt = #line,
column: UInt = #column
) {
let macros = macros ?? MacroTestingConfiguration.current.macros
guard !macros.isEmpty else {
XCTFail(
"""
No macros configured for this assertion. Pass a mapping to this function, e.g.:
assertMacro(["stringify": StringifyMacro.self]) { … }
Or wrap your assertion using 'withMacroTesting', e.g. in 'invokeTest':
class StringifyMacroTests: XCTestCase {
override func invokeTest() {
withMacroTesting(macros: ["stringify": StringifyMacro.self]) {
super.invokeTest()
}
}
…
}
""",
file: file,
line: line
)
return
}
let wasRecording = SnapshotTesting.isRecording
SnapshotTesting.isRecording = isRecording ?? MacroTestingConfiguration.current.isRecording
defer { SnapshotTesting.isRecording = wasRecording }
do {
var origSourceFile = Parser.parse(source: try originalSource())
if let foldedSourceFile = try OperatorTable.standardOperators.foldAll(origSourceFile).as(
SourceFileSyntax.self
) {
origSourceFile = foldedSourceFile
}
let origDiagnostics = ParseDiagnosticsGenerator.diagnostics(for: origSourceFile)
let indentationWidth =
indentationWidth
?? MacroTestingConfiguration.current.indentationWidth
?? Trivia(
stringLiteral: String(
SourceLocationConverter(fileName: "-", tree: origSourceFile).sourceLines
.first(where: { $0.first?.isWhitespace == true && $0 != "\n" })?
.prefix(while: { $0.isWhitespace })
?? " "
)
)
var context = BasicMacroExpansionContext(
sourceFiles: [
origSourceFile: .init(moduleName: "TestModule", fullFilePath: "Test.swift")
]
)
var expandedSourceFile = origSourceFile.expand(
macros: macros,
in: context,
indentationWidth: indentationWidth
)
var offset = 0
func anchor(_ diag: Diagnostic) -> Diagnostic {
let location = context.location(for: diag.position, anchoredAt: diag.node, fileName: "")
return Diagnostic(
node: diag.node,
position: AbsolutePosition(utf8Offset: location.offset),
message: diag.diagMessage,
highlights: diag.highlights,
notes: diag.notes,
fixIts: diag.fixIts
)
}
var allDiagnostics: [Diagnostic] { origDiagnostics + context.diagnostics }
if !allDiagnostics.isEmpty || diagnosedSource != nil {
offset += 1
let converter = SourceLocationConverter(fileName: "-", tree: origSourceFile)
let lineCount = converter.location(for: origSourceFile.endPosition).line
let diagnostics =
DiagnosticsFormatter
.annotatedSource(
tree: origSourceFile,
diags: allDiagnostics.map(anchor),
context: context,
contextSize: lineCount
)
.description
.replacingOccurrences(of: #"(^|\n) *\d* +│ "#, with: "$1", options: .regularExpression)
.trimmingCharacters(in: .newlines)
assertInlineSnapshot(
of: diagnostics,
as: ._lines,
message: """
Diagnostic output (\(newPrefix)) differed from expected output (\(oldPrefix)). \
Difference: …
""",
syntaxDescriptor: InlineSnapshotSyntaxDescriptor(
deprecatedTrailingClosureLabels: ["matches"],
trailingClosureLabel: "diagnostics",
trailingClosureOffset: offset
),
matches: diagnosedSource,
file: file,
function: function,
line: line,
column: column
)
} else if diagnosedSource != nil {
offset += 1
InlineSnapshotSyntaxDescriptor(
trailingClosureLabel: "diagnostics",
trailingClosureOffset: offset
)
.fail(
"Expected diagnostics, but there were none",
file: file,
line: line,
column: column
)
}
if !allDiagnostics.isEmpty && allDiagnostics.allSatisfy({ !$0.fixIts.isEmpty }) {
offset += 1
let edits =
context.diagnostics
.flatMap(\.fixIts)
.flatMap { $0.changes }
.map { $0.edit(in: context) }
var fixedSourceFile = origSourceFile
fixedSourceFile = Parser.parse(
source: FixItApplier.apply(
edits: edits, to: origSourceFile
)
.description
)
if let foldedSourceFile = try OperatorTable.standardOperators.foldAll(fixedSourceFile).as(
SourceFileSyntax.self
) {
fixedSourceFile = foldedSourceFile
}
assertInlineSnapshot(
of: fixedSourceFile.description.trimmingCharacters(in: .newlines),
as: ._lines,
message: """
Fixed output (\(newPrefix)) differed from expected output (\(oldPrefix)). \
Difference: …
""",
syntaxDescriptor: InlineSnapshotSyntaxDescriptor(
trailingClosureLabel: "fixes",
trailingClosureOffset: offset
),
matches: fixedSource,
file: file,
function: function,
line: line,
column: column
)
context = BasicMacroExpansionContext(
sourceFiles: [
fixedSourceFile: .init(moduleName: "TestModule", fullFilePath: "Test.swift")
]
)
expandedSourceFile = fixedSourceFile.expand(
macros: macros,
in: context,
indentationWidth: indentationWidth
)
} else if fixedSource != nil {
offset += 1
InlineSnapshotSyntaxDescriptor(
trailingClosureLabel: "fixes",
trailingClosureOffset: offset
)
.fail(
"Expected fix-its, but there were none",
file: file,
line: line,
column: column
)
}
if allDiagnostics.filter({ $0.diagMessage.severity == .error }).isEmpty {
offset += 1
assertInlineSnapshot(
of: expandedSourceFile.description.trimmingCharacters(in: .newlines),
as: ._lines,
message: """
Expanded output (\(newPrefix)) differed from expected output (\(oldPrefix)). \
Difference: …
""",
syntaxDescriptor: InlineSnapshotSyntaxDescriptor(
deprecatedTrailingClosureLabels: ["matches"],
trailingClosureLabel: "expansion",
trailingClosureOffset: offset
),
matches: expandedSource,
file: file,
function: function,
line: line,
column: column
)
} else if expandedSource != nil {
offset += 1
InlineSnapshotSyntaxDescriptor(
trailingClosureLabel: "expansion",
trailingClosureOffset: offset
)
.fail(
"Expected macro expansion, but there was none",
file: file,
line: line,
column: column
)
}
} catch {
XCTFail("Threw error: \(error)", file: file, line: line)
}
}
// From: https://github.com/apple/swift-syntax/blob/d647052/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift
extension FixIt.Change {
/// Returns the edit for this change, translating positions from detached nodes
/// to the corresponding locations in the original source file based on
/// `expansionContext`.
///
/// - SeeAlso: `FixIt.Change.edit`
fileprivate func edit(in expansionContext: BasicMacroExpansionContext) -> SourceEdit {
switch self {
case .replace(let oldNode, let newNode):
let start = expansionContext.position(of: oldNode.position, anchoredAt: oldNode)
let end = expansionContext.position(of: oldNode.endPosition, anchoredAt: oldNode)
return SourceEdit(
range: start..<end,
replacement: newNode.description
)
case .replaceLeadingTrivia(let token, let newTrivia):
let start = expansionContext.position(of: token.position, anchoredAt: token)
let end = expansionContext.position(
of: token.positionAfterSkippingLeadingTrivia, anchoredAt: token)
return SourceEdit(
range: start..<end,
replacement: newTrivia.description
)
case .replaceTrailingTrivia(let token, let newTrivia):
let start = expansionContext.position(
of: token.endPositionBeforeTrailingTrivia, anchoredAt: token)
let end = expansionContext.position(of: token.endPosition, anchoredAt: token)
return SourceEdit(
range: start..<end,
replacement: newTrivia.description
)
}
}
}
// From: https://github.com/apple/swift-syntax/blob/d647052/Sources/SwiftSyntaxMacrosTestSupport/Assertions.swift
extension BasicMacroExpansionContext {
/// Translates a position from a detached node to the corresponding position
/// in the original source file.
fileprivate func position(
of position: AbsolutePosition,
anchoredAt node: some SyntaxProtocol
) -> AbsolutePosition {
let location = self.location(for: position, anchoredAt: Syntax(node), fileName: "")
return AbsolutePosition(utf8Offset: location.offset)
}
}
/// Asserts that a given Swift source string matches an expected string with all macros expanded.
///
/// See ``assertMacro(_:indentationWidth:record:of:diagnostics:fixes:expansion:file:function:line:column:)-pkfi``
/// for more details.
///
/// - Parameters:
/// - macros: The macros to expand in the original source string. Required, either implicitly via
/// ``withMacroTesting(indentationWidth:isRecording:macros:operation:)-5id9j``, or explicitly
/// via this parameter.
/// - indentationWidth: The `Trivia` for setting indentation during macro expansion
/// (e.g., `.spaces(2)`). Defaults to the original source's indentation if unspecified. If the
/// original source lacks indentation, it defaults to `.spaces(4)`.
/// - isRecording: Always records new snapshots when enabled.
/// - originalSource: A string of Swift source code.
/// - diagnosedSource: Swift source code annotated with expected diagnostics.
/// - fixedSource: Swift source code with expected fix-its applied.
/// - expandedSource: Expected Swift source string with macros expanded.
/// - file: The file where the assertion occurs. The default is the filename of the test case
/// where you call this function.
/// - function: The function where the assertion occurs. The default is the name of the test
/// method where you call this function.
/// - line: The line where the assertion occurs. The default is the line number where you call
/// this function.
/// - column: The column where the assertion occurs. The default is the column where you call this
/// function.
public func assertMacro(
_ macros: [Macro.Type],
indentationWidth: Trivia? = nil,
record isRecording: Bool? = nil,
of originalSource: () throws -> String,
diagnostics diagnosedSource: (() -> String)? = nil,
fixes fixedSource: (() -> String)? = nil,
expansion expandedSource: (() -> String)? = nil,
file: StaticString = #filePath,
function: StaticString = #function,
line: UInt = #line,
column: UInt = #column
) {
assertMacro(
Dictionary(macros: macros),
indentationWidth: indentationWidth,
record: isRecording,
of: originalSource,
diagnostics: diagnosedSource,
fixes: fixedSource,
expansion: expandedSource,
file: file,
function: function,
line: line,
column: column
)
}
/// Customizes `assertMacro` for the duration of an operation.
///
/// Use this operation to customize how the `assertMacro` behaves in a test. It is most convenient
/// to use this tool to wrap `invokeTest` in a `XCTestCase` subclass so that the configuration
/// applies to every test method.
///
/// For example, to specify which macros will be expanded during an assertion for an entire test
/// case you can do the following:
///
/// ```swift
/// class StringifyTests: XCTestCase {
/// override func invokeTest() {
/// withMacroTesting(macros: [StringifyMacro.self]) {
/// super.invokeTest()
/// }
/// }
/// }
/// ```
///
/// And to re-record all macro expansions in a test case you can do the following:
///
/// ```swift
/// class StringifyTests: XCTestCase {
/// override func invokeTest() {
/// withMacroTesting(isRecording: true, macros: [StringifyMacro.self]) {
/// super.invokeTest()
/// }
/// }
/// }
/// ```
///
/// - Parameters:
/// - indentationWidth: The `Trivia` for setting indentation during macro expansion
/// (e.g., `.spaces(2)`). Defaults to the original source's indentation if unspecified. If the
/// original source lacks indentation, it defaults to `.spaces(4)`.
/// - isRecording: Determines if a new macro expansion will be recorded.
/// - macros: Specifies the macros to be expanded in the input Swift source string.
/// - operation: The operation to run with the configuration updated.
public func withMacroTesting<R>(
indentationWidth: Trivia? = nil,
isRecording: Bool? = nil,
macros: [String: Macro.Type]? = nil,
operation: () async throws -> R
) async rethrows {
var configuration = MacroTestingConfiguration.current
if let indentationWidth = indentationWidth { configuration.indentationWidth = indentationWidth }
if let isRecording = isRecording { configuration.isRecording = isRecording }
if let macros = macros { configuration.macros = macros }
try await MacroTestingConfiguration.$current.withValue(configuration) {
try await operation()
}
}
/// Customizes `assertMacro` for the duration of an operation.
///
/// See ``withMacroTesting(indentationWidth:isRecording:macros:operation:)-5id9j`` for
/// more details.
///
/// - Parameters:
/// - indentationWidth: The `Trivia` for setting indentation during macro expansion
/// (e.g., `.spaces(2)`). Defaults to the original source's indentation if unspecified. If the
/// original source lacks indentation, it defaults to `.spaces(4)`.
/// - isRecording: Determines if a new macro expansion will be recorded.
/// - macros: Specifies the macros to be expanded in the input Swift source string.
/// - operation: The operation to run with the configuration updated.
public func withMacroTesting<R>(
indentationWidth: Trivia? = nil,
isRecording: Bool? = nil,
macros: [String: Macro.Type]? = nil,
operation: () throws -> R
) rethrows {
var configuration = MacroTestingConfiguration.current
if let indentationWidth = indentationWidth { configuration.indentationWidth = indentationWidth }
if let isRecording = isRecording { configuration.isRecording = isRecording }
if let macros = macros { configuration.macros = macros }
try MacroTestingConfiguration.$current.withValue(configuration) {
try operation()
}
}
/// Customizes `assertMacro` for the duration of an operation.
///
/// See ``withMacroTesting(indentationWidth:isRecording:macros:operation:)-5id9j`` for
/// more details.
///
/// - Parameters:
/// - indentationWidth: The `Trivia` for setting indentation during macro expansion
/// (e.g., `.spaces(2)`). Defaults to the original source's indentation if unspecified. If the
/// original source lacks indentation, it defaults to `.spaces(4)`.
/// - isRecording: Determines if a new macro expansion will be recorded.
/// - macros: Specifies the macros to be expanded in the input Swift source string.
/// - operation: The operation to run with the configuration updated.
public func withMacroTesting<R>(
indentationWidth: Trivia? = nil,
isRecording: Bool? = nil,
macros: [Macro.Type],
operation: () async throws -> R
) async rethrows {
try await withMacroTesting(
indentationWidth: indentationWidth,
isRecording: isRecording,
macros: Dictionary(macros: macros),
operation: operation
)
}
/// Customizes `assertMacro` for the duration of an operation.
///
/// See ``withMacroTesting(indentationWidth:isRecording:macros:operation:)-5id9j`` for
/// more details.
///
/// - Parameters:
/// - indentationWidth: The `Trivia` for setting indentation during macro expansion
/// (e.g., `.spaces(2)`). Defaults to the original source's indentation if unspecified. If the
/// original source lacks indentation, it defaults to `.spaces(4)`.
/// - isRecording: Determines if a new macro expansion will be recorded.
/// - macros: Specifies the macros to be expanded in the input Swift source string.
/// - operation: The operation to run with the configuration updated.
public func withMacroTesting<R>(
indentationWidth: Trivia? = nil,
isRecording: Bool? = nil,
macros: [Macro.Type],
operation: () throws -> R
) rethrows {
try withMacroTesting(
indentationWidth: indentationWidth,
isRecording: isRecording,
macros: Dictionary(macros: macros),
operation: operation
)
}
extension Snapshotting where Value == String, Format == String {
fileprivate static let _lines = Snapshotting(
pathExtension: "txt",
diffing: Diffing(
toData: { Data($0.utf8) },
fromData: { String(decoding: $0, as: UTF8.self) }
) { old, new in
guard old != new else { return nil }
let newLines = new.split(separator: "\n", omittingEmptySubsequences: false)
let oldLines = old.split(separator: "\n", omittingEmptySubsequences: false)
let difference = newLines.difference(from: oldLines)
var result = ""
var insertions = [Int: Substring]()
var removals = [Int: Substring]()
for change in difference {
switch change {
case let .insert(offset, element, _):
insertions[offset] = element
case let .remove(offset, element, _):
removals[offset] = element
}
}
var oldLine = 0
var newLine = 0
while oldLine < oldLines.count || newLine < newLines.count {
if let removal = removals[oldLine] {
result += "\(oldPrefix) \(removal)\n"
oldLine += 1
} else if let insertion = insertions[newLine] {
result += "\(newPrefix) \(insertion)\n"
newLine += 1
} else {
result += "\(prefix) \(oldLines[oldLine])\n"
oldLine += 1
newLine += 1
}
}
let attachment = XCTAttachment(
data: Data(result.utf8),
uniformTypeIdentifier: "public.patch-file"
)
return (result, [attachment])
}
)
}
internal func macroName(className: String, isExpression: Bool) -> String {
var name =
className
.replacingOccurrences(of: "Macro$", with: "", options: .regularExpression)
if !name.isEmpty, isExpression {
var prefix = name.prefix(while: \.isUppercase)
if prefix.count > 1, name[prefix.endIndex...].first?.isLowercase == true {
prefix.removeLast()
}
name.replaceSubrange(prefix.startIndex..<prefix.endIndex, with: prefix.lowercased())
}
return name
}
struct MacroTestingConfiguration {
@TaskLocal static var current = Self()
var indentationWidth: Trivia? = nil
var isRecording = false
var macros: [String: Macro.Type] = [:]
}
extension Dictionary where Key == String, Value == Macro.Type {
init(macros: [Macro.Type]) {
self.init(
macros.map {
let name = macroName(
className: String(describing: $0),
isExpression: $0 is ExpressionMacro.Type
)
return (key: name, value: $0)
},
uniquingKeysWith: { _, rhs in rhs }
)
}
}
private let oldPrefix = "\u{2212}"
private let newPrefix = "+"
private let prefix = "\u{2007}"