File: SkipUnless.swift

package info (click to toggle)
swiftlang 6.2.3-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 2,856,264 kB
  • sloc: cpp: 9,995,718; ansic: 2,234,019; asm: 1,092,167; python: 313,940; objc: 82,726; f90: 80,126; lisp: 38,373; pascal: 25,580; sh: 20,378; ml: 5,058; perl: 4,751; makefile: 4,725; awk: 3,535; javascript: 3,018; xml: 918; fortran: 664; cs: 573; ruby: 396
file content (378 lines) | stat: -rw-r--r-- 13,661 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
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//

import Foundation
import LanguageServerProtocol
import LanguageServerProtocolExtensions
import RegexBuilder
import SKLogging
import SourceKitD
import SourceKitLSP
import SwiftExtensions
import TSCExtensions
import ToolchainRegistry
import XCTest

import struct TSCBasic.AbsolutePath
import class TSCBasic.Process
import enum TSCBasic.ProcessEnv

// MARK: - Skip checks

/// Namespace for functions that are used to skip unsupported tests.
package actor SkipUnless {
  private enum FeatureCheckResult {
    case featureSupported
    case featureUnsupported(skipMessage: String)
  }

  private static let shared = SkipUnless()

  /// For any feature that has already been evaluated, the result of whether or not it should be skipped.
  private var checkCache: [String: FeatureCheckResult] = [:]

  /// Throw an `XCTSkip` if any of the following conditions hold
  ///  - The Swift version of the toolchain used for testing (`ToolchainRegistry.forTesting.default`) is older than
  ///    `swiftVersion`
  ///  - The Swift version of the toolchain used for testing is equal to `swiftVersion` and `featureCheck` returns
  ///    `false`. This is used for features that are introduced in `swiftVersion` but are not present in all toolchain
  ///    snapshots.
  ///
  /// Having the version check indicates when the check tests can be removed (namely when the minimum required version
  /// to test sourcekit-lsp is above `swiftVersion`) and it ensures that tests can’t stay in the skipped state over
  /// multiple releases.
  ///
  /// Independently of these checks, the tests are never skipped in Swift CI (identified by the presence of the `SWIFTCI_USE_LOCAL_DEPS` environment). Swift CI is assumed to always build its own toolchain, which is thus
  /// guaranteed to be up-to-date.
  private func skipUnlessSupportedByToolchain(
    swiftVersion: SwiftVersion,
    featureName: String = #function,
    file: StaticString,
    line: UInt,
    featureCheck: () async throws -> Bool
  ) async throws {
    return try await skipUnlessSupported(featureName: featureName, file: file, line: line) {
      let toolchainSwiftVersion = try await unwrap(ToolchainRegistry.forTesting.default).swiftVersion
      let requiredSwiftVersion = SwiftVersion(swiftVersion.major, swiftVersion.minor)
      if toolchainSwiftVersion < requiredSwiftVersion {
        return .featureUnsupported(
          skipMessage: """
            Skipping because toolchain has Swift version \(toolchainSwiftVersion) \
            but test requires at least \(requiredSwiftVersion)
            """
        )
      } else if toolchainSwiftVersion == requiredSwiftVersion {
        logger.info("Checking if feature '\(featureName)' is supported")
        defer {
          logger.info("Done checking if feature '\(featureName)' is supported")
        }
        if try await !featureCheck() {
          return .featureUnsupported(skipMessage: "Skipping because toolchain doesn't contain \(featureName)")
        } else {
          return .featureSupported
        }
      } else {
        return .featureSupported
      }
    }
  }

  private func skipUnlessSupported(
    allowSkippingInCI: Bool = false,
    featureName: String = #function,
    file: StaticString,
    line: UInt,
    featureCheck: () async throws -> FeatureCheckResult
  ) async throws {
    let checkResult: FeatureCheckResult
    if let cachedResult = checkCache[featureName] {
      checkResult = cachedResult
    } else if ProcessEnv.block["SWIFTCI_USE_LOCAL_DEPS"] != nil && !allowSkippingInCI {
      // In general, don't skip tests in CI. Toolchain should be up-to-date
      checkResult = .featureSupported
    } else {
      checkResult = try await featureCheck()
    }
    checkCache[featureName] = checkResult

    if case .featureUnsupported(let skipMessage) = checkResult {
      throw XCTSkip(skipMessage, file: file, line: line)
    }
  }

  /// A long test is a test that takes longer than 1-2s to execute.
  package static func longTestsEnabled() throws {
    if let value = ProcessInfo.processInfo.environment["SKIP_LONG_TESTS"], value == "1" || value == "YES" {
      throw XCTSkip("Long tests disabled using the `SKIP_LONG_TESTS` environment variable")
    }
  }

  package static func platformIsDarwin(_ message: String) throws {
    try XCTSkipUnless(Platform.current == .darwin, message)
  }

  package static func platformIsWindows(_ message: String) throws {
    try XCTSkipUnless(Platform.current == .windows, message)
  }

  package static func platformSupportsTaskPriorityElevation() throws {
    #if os(macOS)
    guard #available(macOS 14.0, *) else {
      // Priority elevation was implemented by https://github.com/apple/swift/pull/63019, which is available in the
      // Swift 5.9 runtime included in macOS 14.0+
      throw XCTSkip("Priority elevation of tasks is only supported on macOS 14 and above")
    }
    #endif
  }

  /// Check if we can use the build artifacts in the sourcekit-lsp build directory to build a macro package without
  /// re-building swift-syntax.
  package static func canBuildMacroUsingSwiftSyntaxFromSourceKitLSPBuild(
    file: StaticString = #filePath,
    line: UInt = #line
  ) async throws {
    try XCTSkipUnless(
      Platform.current != .windows,
      "Temporarily skipping as we need to fix these tests to use the cmake-built swift-syntax libraries on Windows."
    )

    return try await shared.skipUnlessSupported(file: file, line: line) {
      do {
        let project = try await SwiftPMTestProject(
          files: [
            "MyMacros/MyMacros.swift": #"""
            import SwiftParser

            func test() {
              _ = Parser.parse(source: "let a")
            }
            """#,
            "MyMacroClient/MyMacroClient.swift": """
            """,
          ],
          manifest: SwiftPMTestProject.macroPackageManifest
        )
        try await SwiftPMTestProject.build(
          at: project.scratchDirectory,
          extraArguments: ["--experimental-prepare-for-indexing"]
        )
        return .featureSupported
      } catch {
        return .featureUnsupported(
          skipMessage: """
            Skipping because macro could not be built using build artifacts in the sourcekit-lsp build directory. \
            This usually happens if sourcekit-lsp was built using a different toolchain than the one used at test-time.

            Reason:
            \(error)
            """
        )
      }
    }
  }

  package static func canSwiftPMCompileForIOS(
    file: StaticString = #filePath,
    line: UInt = #line
  ) async throws {
    return try await shared.skipUnlessSupported(allowSkippingInCI: true, file: file, line: line) {
      #if os(macOS)
      let project = try await SwiftPMTestProject(files: [
        "MyFile.swift": """
        public func foo() {}
        """
      ])
      do {
        try await SwiftPMTestProject.build(
          at: project.scratchDirectory,
          extraArguments: [
            "--swift-sdk", "arm64-apple-ios",
          ]
        )
        return .featureSupported
      } catch {
        return .featureUnsupported(skipMessage: "Cannot build for iOS: \(error)")
      }
      #else
      return .featureUnsupported(skipMessage: "Cannot build for iOS outside macOS by default")
      #endif
    }
  }

  package static func canCompileForWasm(
    file: StaticString = #filePath,
    line: UInt = #line
  ) async throws {
    return try await shared.skipUnlessSupported(allowSkippingInCI: true, file: file, line: line) {
      let swiftFrontend = try await unwrap(ToolchainRegistry.forTesting.default?.swift).deletingLastPathComponent()
        .appendingPathComponent("swift-frontend")
      return try await withTestScratchDir { scratchDirectory in
        let input = scratchDirectory.appendingPathComponent("Input.swift")
        guard FileManager.default.createFile(atPath: input.path, contents: nil) else {
          throw GenericError("Failed to create input file")
        }
        // If we can't compile for wasm, this fails complaining that it can't find the stdlib for wasm.
        let result = try await withTimeout(defaultTimeoutDuration) {
          try await Process.run(
            arguments: [
              try swiftFrontend.filePath,
              "-typecheck",
              try input.filePath,
              "-triple",
              "wasm32-unknown-none-wasm",
              "-enable-experimental-feature",
              "Embedded",
              "-Xcc",
              "-fdeclspec",
            ],
            workingDirectory: nil
          )
        }
        if result.exitStatus == .terminated(code: 0) {
          return .featureSupported
        }
        return .featureUnsupported(skipMessage: "Skipping because toolchain can not compile for wasm")
      }
    }
  }

  package static func sourcekitdSupportsPlugin(
    file: StaticString = #filePath,
    line: UInt = #line
  ) async throws {
    return try await shared.skipUnlessSupportedByToolchain(swiftVersion: SwiftVersion(6, 2), file: file, line: line) {
      guard let sourcekitdPath = await ToolchainRegistry.forTesting.default?.sourcekitd else {
        throw GenericError("Could not find SourceKitD")
      }
      let sourcekitd = try await SourceKitD.getOrCreate(
        dylibPath: sourcekitdPath,
        pluginPaths: try sourceKitPluginPaths
      )
      do {
        let response = try await sourcekitd.send(
          sourcekitd.dictionary([
            sourcekitd.keys.request: sourcekitd.requests.codeCompleteSetPopularAPI,
            sourcekitd.keys.codeCompleteOptions: [
              sourcekitd.keys.useNewAPI: 1
            ],
          ]),
          timeout: defaultTimeoutDuration,
          fileContents: nil
        )
        return response[sourcekitd.keys.useNewAPI] == 1
      } catch {
        return false
      }
    }
  }

  package static func canLoadPluginsBuiltByToolchain(
    file: StaticString = #filePath,
    line: UInt = #line
  ) async throws {
    return try await shared.skipUnlessSupported(file: file, line: line) {
      let project = try await SwiftPMTestProject(
        files: [
          "Plugins/plugin.swift": #"""
          import Foundation
          import PackagePlugin
          @main struct CodeGeneratorPlugin: BuildToolPlugin {
            func createBuildCommands(context: PluginContext, target: Target) throws -> [Command] {
              let genSourcesDir = context.pluginWorkDirectoryURL.appending(path: "GeneratedSources")
              guard let target = target as? SourceModuleTarget else { return [] }
              let codeGenerator = try context.tool(named: "CodeGenerator").url
              let generatedFile = genSourcesDir.appending(path: "\(target.name)-generated.swift")
              return [.buildCommand(
                displayName: "Generating code for \(target.name)",
                executable: codeGenerator,
                arguments: [
                  generatedFile.path
                ],
                inputFiles: [],
                outputFiles: [generatedFile]
              )]
            }
          }
          """#,

          "Sources/CodeGenerator/CodeGenerator.swift": #"""
          import Foundation
          try "let foo = 1".write(
            to: URL(fileURLWithPath: CommandLine.arguments[1]),
            atomically: true,
            encoding: String.Encoding.utf8
          )
          """#,

          "Sources/TestLib/TestLib.swift": #"""
          func useGenerated() {
            _ = 1️⃣foo
          }
          """#,
        ],
        manifest: """
          // swift-tools-version: 6.0
          import PackageDescription
          let package = Package(
            name: "PluginTest",
            targets: [
              .executableTarget(name: "CodeGenerator"),
              .target(
                name: "TestLib",
                plugins: [.plugin(name: "CodeGeneratorPlugin")]
              ),
              .plugin(
                name: "CodeGeneratorPlugin",
                capability: .buildTool(),
                dependencies: ["CodeGenerator"]
              ),
            ]
          )
          """,
        enableBackgroundIndexing: true
      )

      let (uri, positions) = try project.openDocument("TestLib.swift")

      let result = try await project.testClient.send(
        DefinitionRequest(textDocument: TextDocumentIdentifier(uri), position: positions["1️⃣"])
      )

      if result?.locations?.only == nil {
        return .featureUnsupported(skipMessage: "Skipping because plugin protocols do not match.")
      }
      return .featureSupported
    }
  }
}

// MARK: - Parsing Swift compiler version

fileprivate extension String {
  init?(bytes: [UInt8], encoding: Encoding) {
    self = bytes.withUnsafeBytes { buffer in
      guard let baseAddress = buffer.baseAddress else {
        return ""
      }
      let data = Data(bytes: baseAddress, count: buffer.count)
      return String(data: data, encoding: encoding)!
    }
  }
}

private struct GenericError: Error, CustomStringConvertible {
  var description: String

  init(_ message: String) {
    self.description = message
  }
}