File: Assertions.swift

package info (click to toggle)
swiftlang 6.0.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 2,519,992 kB
  • sloc: cpp: 9,107,863; ansic: 2,040,022; asm: 1,135,751; python: 296,500; objc: 82,456; f90: 60,502; lisp: 34,951; pascal: 19,946; sh: 18,133; perl: 7,482; ml: 4,937; javascript: 4,117; makefile: 3,840; awk: 3,535; xml: 914; fortran: 619; cs: 573; ruby: 573
file content (607 lines) | stat: -rw-r--r-- 21,397 bytes parent folder | download
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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2023 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if swift(>=6.0)
import SwiftBasicFormat
public import SwiftDiagnostics
@_spi(FixItApplier) import SwiftIDEUtils
import SwiftParser
import SwiftParserDiagnostics
public import SwiftSyntax
public import SwiftSyntaxMacroExpansion
private import SwiftSyntaxMacros
private import _SwiftSyntaxGenericTestSupport
#else
import SwiftBasicFormat
import SwiftDiagnostics
@_spi(FixItApplier) import SwiftIDEUtils
import SwiftParser
import SwiftParserDiagnostics
import SwiftSyntax
import SwiftSyntaxMacroExpansion
import SwiftSyntaxMacros
import _SwiftSyntaxGenericTestSupport
#endif

/// Defines the location at which the a test failure should be anchored. This is typically the location where the
/// assertion function is called.
public struct TestFailureLocation {
  @_spi(XCTestFailureLocation) public let staticFileID: StaticString
  public var fileID: String { staticFileID.description }

  @_spi(XCTestFailureLocation) public let staticFilePath: StaticString
  public var filePath: String { staticFilePath.description }

  @_spi(XCTestFailureLocation) public let unsignedLine: UInt
  public var line: Int { Int(unsignedLine) }

  @_spi(XCTestFailureLocation) public let unsignedColumn: UInt
  public var column: Int { Int(unsignedColumn) }

  public init(
    fileID: StaticString,
    filePath: StaticString,
    line: UInt,
    column: UInt
  ) {
    self.staticFileID = fileID
    self.staticFilePath = filePath
    self.unsignedLine = line
    self.unsignedColumn = column
  }

  fileprivate init(underlying: _SwiftSyntaxGenericTestSupport.TestFailureLocation) {
    self.init(
      fileID: underlying.fileID,
      filePath: underlying.filePath,
      line: underlying.line,
      column: underlying.column
    )
  }

  /// This type is intentionally different to `_SwiftSyntaxGenericTestSupport.TestFailureLocation` so we can
  /// import `_SwiftSyntaxGenericTestSupport` privately and don't expose its internal types.
  fileprivate var underlying: _SwiftSyntaxGenericTestSupport.TestFailureLocation {
    _SwiftSyntaxGenericTestSupport.TestFailureLocation(
      fileID: self.staticFileID,
      filePath: self.staticFilePath,
      line: self.unsignedLine,
      column: self.unsignedColumn
    )
  }
}

/// Defines the details of a test failure, consisting of a message and the location at which the test failure should be
/// shown.
public struct TestFailureSpec {
  public let message: String
  public let location: TestFailureLocation

  public init(message: String, location: TestFailureLocation) {
    self.message = message
    self.location = location
  }

  fileprivate init(underlying: _SwiftSyntaxGenericTestSupport.TestFailureSpec) {
    self.init(
      message: underlying.message,
      location: TestFailureLocation(underlying: underlying.location)
    )
  }
}

// MARK: - Note

/// Describes a diagnostic note that tests expect to be created by a macro expansion.
public struct NoteSpec {
  /// The expected message of the note
  public let message: String

  /// The line to which the note is expected to point
  public let line: Int

  /// The column to which the note is expected to point
  public let column: Int

  /// The file and line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  internal let failureLocation: TestFailureLocation

  /// Creates a new ``NoteSpec`` that describes a note tests are expecting to be generated by a macro expansion.
  ///
  /// - Parameters:
  ///   - message: The expected message of the note
  ///   - line: The line to which the note is expected to point
  ///   - column: The column to which the note is expected to point
  ///   - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  ///   - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  public init(
    message: String,
    line: Int,
    column: Int,
    originatorFileID: StaticString = #fileID,
    originatorFile: StaticString = #filePath,
    originatorLine: UInt = #line,
    originatorColumn: UInt = #column
  ) {
    self.message = message
    self.line = line
    self.column = column
    self.failureLocation = TestFailureLocation(
      fileID: originatorFileID,
      filePath: originatorFile,
      line: originatorLine,
      column: originatorColumn
    )
  }
}

func assertNote(
  _ note: Note,
  in expansionContext: BasicMacroExpansionContext,
  expected spec: NoteSpec,
  failureHandler: (TestFailureSpec) -> Void
) {
  assertStringsEqualWithDiff(
    note.message,
    spec.message,
    "message of note does not match",
    location: spec.failureLocation.underlying,
    failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) }
  )
  let location = expansionContext.location(for: note.position, anchoredAt: note.node, fileName: "")
  if location.line != spec.line {
    failureHandler(
      TestFailureSpec(
        message: "line of note \(location.line) does not match expected line \(spec.line)",
        location: spec.failureLocation
      )
    )
  }
  if location.column != spec.column {
    failureHandler(
      TestFailureSpec(
        message: "column of note \(location.column) does not match expected column \(spec.column)",
        location: spec.failureLocation
      )
    )
  }
}

// MARK: - Fix-It

/// Describes a Fix-It that tests expect to be created by a macro expansion.
///
/// Currently, it only compares the message of the Fix-It. In the future, it might
/// also compare the expected changes that should be performed by the Fix-It.
public struct FixItSpec {
  /// The expected message of the Fix-It
  public let message: String

  /// The file and line at which this ``FixItSpec`` was created, so that assertion failures can be reported at its location.
  internal let failureLocation: TestFailureLocation

  /// Creates a new ``FixItSpec`` that describes a Fix-It tests are expecting to be generated by a macro expansion.
  ///
  /// - Parameters:
  ///   - message: The expected message of the note
  ///   - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  ///   - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  public init(
    message: String,
    originatorFileID: StaticString = #fileID,
    originatorFile: StaticString = #filePath,
    originatorLine: UInt = #line,
    originatorColumn: UInt = #column
  ) {
    self.message = message
    self.failureLocation = TestFailureLocation(
      fileID: originatorFileID,
      filePath: originatorFile,
      line: originatorLine,
      column: originatorColumn
    )
  }
}

func assertFixIt(
  _ fixIt: FixIt,
  expected spec: FixItSpec,
  failureHandler: (TestFailureSpec) -> Void
) {
  assertStringsEqualWithDiff(
    fixIt.message.message,
    spec.message,
    "message of Fix-It does not match",
    location: spec.failureLocation.underlying,
    failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) }
  )
}

// MARK: - Diagnostic

/// Describes a diagnostic that tests expect to be created by a macro expansion.
public struct DiagnosticSpec {
  /// If not `nil`, the ID, which the diagnostic is expected to have.
  public let id: MessageID?

  /// The expected message of the diagnostic
  public let message: String

  /// The line to which the diagnostic is expected to point
  public let line: Int

  /// The column to which the diagnostic is expected to point
  public let column: Int

  /// The expected severity of the diagnostic
  public let severity: DiagnosticSeverity

  /// If not `nil`, the text fragments the diagnostic is expected to highlight
  public let highlights: [String]?

  /// The notes that are expected to be attached to the diagnostic
  public let notes: [NoteSpec]

  /// The messages of the Fix-Its the diagnostic is expected to produce
  public let fixIts: [FixItSpec]

  /// The file and line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  internal let failureLocation: TestFailureLocation

  /// Creates a new ``DiagnosticSpec`` that describes a diagnostic tests are expecting to be generated by a macro expansion.
  ///
  /// - Parameters:
  ///   - id: If not `nil`, the ID, which the diagnostic is expected to have.
  ///   - message: The expected message of the diagnostic
  ///   - line: The line to which the diagnostic is expected to point
  ///   - column: The column to which the diagnostic is expected to point
  ///   - severity: The expected severity of the diagnostic
  ///   - highlights: If not empty, the text fragments the diagnostic is expected to highlight
  ///   - notes: The notes that are expected to be attached to the diagnostic
  ///   - fixIts: The messages of the Fix-Its the diagnostic is expected to produce
  ///   - originatorFile: The file at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  ///   - originatorLine: The line at which this ``NoteSpec`` was created, so that assertion failures can be reported at its location.
  public init(
    id: MessageID? = nil,
    message: String,
    line: Int,
    column: Int,
    severity: DiagnosticSeverity = .error,
    highlights: [String]? = nil,
    notes: [NoteSpec] = [],
    fixIts: [FixItSpec] = [],
    originatorFileID: StaticString = #fileID,
    originatorFile: StaticString = #filePath,
    originatorLine: UInt = #line,
    originatorColumn: UInt = #column
  ) {
    self.id = id
    self.message = message
    self.line = line
    self.column = column
    self.severity = severity
    self.highlights = highlights
    self.notes = notes
    self.fixIts = fixIts
    self.failureLocation = TestFailureLocation(
      fileID: originatorFileID,
      filePath: originatorFile,
      line: originatorLine,
      column: originatorColumn
    )
  }
}

extension DiagnosticSpec {
  @available(*, deprecated, message: "Use highlights instead")
  public var highlight: String? {
    guard let highlights else {
      return nil
    }
    return highlights.joined(separator: " ")
  }

  // swift-format-ignore
  @available(*, deprecated, message: "Use init(id:message:line:column:severity:highlights:notes:fixIts:originatorFile:originatorLine:) instead")
  @_disfavoredOverload
  public init(
    id: MessageID? = nil,
    message: String,
    line: Int,
    column: Int,
    severity: DiagnosticSeverity = .error,
    highlight: String? = nil,
    notes: [NoteSpec] = [],
    fixIts: [FixItSpec] = [],
    originatorFile: StaticString = #filePath,
    originatorLine: UInt = #line
  ) {
    self.init(
      id: id,
      message: message,
      line: line,
      column: column,
      severity: severity,
      highlights: highlight.map { [$0] },
      notes: notes,
      fixIts: fixIts
    )
  }
}

func assertDiagnostic(
  _ diag: Diagnostic,
  in expansionContext: BasicMacroExpansionContext,
  expected spec: DiagnosticSpec,
  failureHandler: (TestFailureSpec) -> Void
) {
  if let id = spec.id, diag.diagnosticID != id {
    failureHandler(
      TestFailureSpec(
        message: "diagnostic ID \(diag.diagnosticID) does not match expected id \(id)",
        location: spec.failureLocation
      )
    )
  }
  assertStringsEqualWithDiff(
    diag.message,
    spec.message,
    "message does not match",
    location: spec.failureLocation.underlying,
    failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) }
  )
  let location = expansionContext.location(for: diag.position, anchoredAt: diag.node, fileName: "")
  if location.line != spec.line {
    failureHandler(
      TestFailureSpec(
        message: "line \(location.line) does not match expected line \(spec.line)",
        location: spec.failureLocation
      )
    )
  }
  if location.column != spec.column {
    failureHandler(
      TestFailureSpec(
        message: "column \(location.column) does not match expected column \(spec.column)",
        location: spec.failureLocation
      )
    )
  }

  if spec.severity != diag.diagMessage.severity {
    failureHandler(
      TestFailureSpec(
        message: "severity \(diag.diagMessage.severity) does not match expected severity \(spec.severity)",
        location: spec.failureLocation
      )
    )
  }

  if let highlights = spec.highlights {
    if diag.highlights.count != highlights.count {
      failureHandler(
        TestFailureSpec(
          message: """
            Expected \(highlights.count) highlights but received \(diag.highlights.count):
            \(diag.highlights.map(\.trimmedDescription).joined(separator: "\n"))
            """,
          location: spec.failureLocation
        )
      )
    } else {
      for (actual, expected) in zip(diag.highlights, highlights) {
        assertStringsEqualWithDiff(
          actual.trimmedDescription,
          expected,
          "highlight does not match",
          location: spec.failureLocation.underlying,
          failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) }
        )
      }
    }
  }
  if diag.notes.count != spec.notes.count {
    failureHandler(
      TestFailureSpec(
        message: """
          Expected \(spec.notes.count) notes but received \(diag.notes.count):
          \(diag.notes.map(\.debugDescription).joined(separator: "\n"))
          """,
        location: spec.failureLocation
      )
    )
  } else {
    for (note, expectedNote) in zip(diag.notes, spec.notes) {
      assertNote(note, in: expansionContext, expected: expectedNote, failureHandler: failureHandler)
    }
  }
  if diag.fixIts.count != spec.fixIts.count {
    failureHandler(
      TestFailureSpec(
        message: """
          Expected \(spec.fixIts.count) Fix-Its but received \(diag.fixIts.count):
          \(diag.fixIts.map(\.message.message).joined(separator: "\n"))
          """,
        location: spec.failureLocation
      )
    )
  } else {
    for (fixIt, expectedFixIt) in zip(diag.fixIts, spec.fixIts) {
      assertFixIt(fixIt, expected: expectedFixIt, failureHandler: failureHandler)
    }
  }
}

/// Assert that expanding the given macros in the original source produces
/// the given expanded source code.
///
/// - Parameters:
///   - originalSource: The original source code, which is expected to contain
///     macros in various places (e.g., `#stringify(x + y)`).
///   - expectedExpandedSource: The source code that we expect to see after
///     performing macro expansion on the original source.
///   - diagnostics: The diagnostics when expanding any macro
///   - macroSpecs: The macros that should be expanded, provided as a dictionary
///     mapping macro names (e.g., `"CodableMacro"`) to specification with macro type
///     (e.g., `CodableMacro.self`) and a list of conformances macro provides
///     (e.g., `["Decodable", "Encodable"]`).
///   - applyFixIts: If specified, filters the Fix-Its that are applied to generate `fixedSource` to only those whose message occurs in this array. If `nil`, all Fix-Its from the diagnostics are applied.
///   - fixedSource: If specified, asserts that the source code after applying Fix-Its matches this string.
///   - testModuleName: The name of the test module to use.
///   - testFileName: The name of the test file name to use.
///   - indentationWidth: The indentation width used in the expansion.
public func assertMacroExpansion(
  _ originalSource: String,
  expandedSource expectedExpandedSource: String,
  diagnostics: [DiagnosticSpec] = [],
  macroSpecs: [String: MacroSpec],
  applyFixIts: [String]? = nil,
  fixedSource expectedFixedSource: String? = nil,
  testModuleName: String = "TestModule",
  testFileName: String = "test.swift",
  indentationWidth: Trivia = .spaces(4),
  failureHandler: (TestFailureSpec) -> Void,
  fileID: StaticString = #fileID,
  filePath: StaticString = #filePath,
  line: UInt = #line,
  column: UInt = #column
) {
  let failureLocation = TestFailureLocation(fileID: fileID, filePath: filePath, line: line, column: column)
  // Parse the original source file.
  let origSourceFile = Parser.parse(source: originalSource)

  // Expand all macros in the source.
  let context = BasicMacroExpansionContext(
    sourceFiles: [origSourceFile: .init(moduleName: testModuleName, fullFilePath: testFileName)]
  )

  func contextGenerator(_ syntax: Syntax) -> BasicMacroExpansionContext {
    return BasicMacroExpansionContext(sharingWith: context, lexicalContext: syntax.allMacroLexicalContexts())
  }

  let expandedSourceFile = origSourceFile.expand(
    macroSpecs: macroSpecs,
    contextGenerator: contextGenerator,
    indentationWidth: indentationWidth
  )
  let diags = ParseDiagnosticsGenerator.diagnostics(for: expandedSourceFile)
  if !diags.isEmpty {
    failureHandler(
      TestFailureSpec(
        message: """
          Expanded source should not contain any syntax errors, but contains:
          \(DiagnosticsFormatter.annotatedSource(tree: expandedSourceFile, diags: diags))

          Expanded syntax tree was:
          \(expandedSourceFile.debugDescription)
          """,
        location: failureLocation
      )
    )
  }

  assertStringsEqualWithDiff(
    expandedSourceFile.description.drop(while: \.isNewline).droppingLast(while: \.isNewline),
    expectedExpandedSource.drop(while: \.isNewline).droppingLast(while: \.isNewline),
    "Macro expansion did not produce the expected expanded source",
    additionalInfo: """
      Actual expanded source:
      \(expandedSourceFile)
      """,
    location: failureLocation.underlying,
    failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) }
  )

  if context.diagnostics.count != diagnostics.count {
    failureHandler(
      TestFailureSpec(
        message: """
          Expected \(diagnostics.count) diagnostics but received \(context.diagnostics.count):
          \(context.diagnostics.map(\.debugDescription).joined(separator: "\n"))
          """,
        location: failureLocation
      )
    )
  } else {
    for (actualDiag, expectedDiag) in zip(context.diagnostics, diagnostics) {
      assertDiagnostic(actualDiag, in: context, expected: expectedDiag, failureHandler: failureHandler)
    }
  }

  // Applying Fix-Its
  if let expectedFixedSource = expectedFixedSource {
    let messages = applyFixIts ?? context.diagnostics.compactMap { $0.fixIts.first?.message.message }

    let edits =
      context.diagnostics
      .flatMap(\.fixIts)
      .filter { messages.contains($0.message.message) }
      .flatMap { $0.changes }
      .map { $0.edit(in: context) }

    let fixedTree = FixItApplier.apply(edits: edits, to: origSourceFile)
    let fixedTreeDescription = fixedTree.description
    assertStringsEqualWithDiff(
      fixedTreeDescription.trimmingTrailingWhitespace(),
      expectedFixedSource.trimmingTrailingWhitespace(),
      location: failureLocation.underlying,
      failureHandler: { failureHandler(TestFailureSpec(underlying: $0)) }
    )
  }
}

fileprivate 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`
  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
      )
    }
  }
}

fileprivate extension BasicMacroExpansionContext {
  /// Translates a position from a detached node to the corresponding position
  /// in the original source file.
  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)
  }
}